#Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Change2CUI=y #AutoIt3Wrapper_Run_Tidy=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** AutoItSetOption("MustDeclareVars", 1) ;~ A demonstration to show how to perform a regular expression ;~ search over binary files from command line. ;~ https://www.autoitscript.com/forum/topic/188564-use-regexp-on-binary-data ;~ Examples: ;~ BinFind "C:\Windows\System32\notepad.exe" "\x4D\x5A.." ;~ BinFind "C:\Windows\System32\notepad.exe" "\x89\x84.." #include #include If $CmdLine[0] <> 2 Then ConsoleWrite("Wrong command line arguments." & @CRLF & @CRLF & "Usage: BinFind " & @CRLF) ; Exit EndIf Local Const $sFilePath = $CmdLine[1] Local Const $sPattern = $CmdLine[2] If Not FileExists($sFilePath) Then ConsoleWrite("File not found: " & $sFilePath & @CRLF) Exit EndIf ConsoleWrite("Filename: " & $sFilePath & @CRLF) ConsoleWrite("RegExp pattern: " & $sPattern & @CRLF) ; Get the binary data Local $hFileOpen = FileOpen($sFilePath, $FO_READ + $FO_Binary) If $hFileOpen = -1 Then ConsoleWrite("An error occurred when reading the file." & @CRLF) Exit EndIf Local $BinaryData = FileRead($hFileOpen) FileClose($hFileOpen) ; Convert the binary data into a string with identical one-to-one ; byte to character representation. This is useful for performing ; regular expressions on binary data. Local $sBinaryText = "" For $i = 1 To BinaryLen($BinaryData) Local $iCode = BinaryMid($BinaryData, $i, 1) Local $sChrW = ChrW($iCode) $sBinaryText &= $sChrW Next ; Perform a regular expression search on the mirror-image text. ; Note: search is not run over the original byte array. Local $aMatch = 0, _ $iOffset = 1, _ $iMatches = 0 While 1 $aMatch = StringRegExp($sBinaryText, _ "(?sx)" & $sPattern, _ $STR_REGEXPARRAYFULLMATCH, _ $iOffset _ ) If @error Then ExitLoop $iOffset = @extended $iMatches += 1 Local $sMatch = $aMatch[0] ; get the full match as the first array element Local $iPos = $iOffset - StringLen($sMatch) - 1 ; seek to start of match ConsoleWrite("Offset: 0x" & Hex($iPos) & " ") ConsoleWrite("Length: " & StringLen($sMatch) & " ") ConsoleWrite("Bytes: ") For $j = 1 To StringLen($sMatch) Local $sChrW = StringMid($sMatch, $j, 1) Local $iCode = AscW($sChrW) ConsoleWrite("0x" & Hex($iCode, 2) & " ") Next ;~ ConsoleWrite(@TAB & "Char: [" & $sMatch & "]" & @CRLF) ConsoleWrite(@TAB & "Char: [" & StringRegExpReplace($sMatch, "[\x0\x09\x0D\x0A]", "?") & "]" & @CRLF) WEnd If $iMatches = 0 Then ConsoleWrite("No matches could be found." & @CRLF) EndIf