Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re for opcode parsing

I just wrote some code to try and parse opcodes out of an objdump output of the following format :-

 8048060:   89 e7                   mov    edi,esp
 8048062:   89 fe                   mov    esi,edi
 8048064:   6a 6b                   push   0x6b
 8048066:   58                      pop    eax
 8048067:   aa                      stos   BYTE PTR es:[edi],al
 8048068:   6a 65                   push   0x65
 804806a:   58                      pop    eax
 804806b:   aa                      stos   BYTE PTR es:[edi],al
 804806c:   6a 79                   push   0x79
 804806e:   58                      pop    eax
 804806f:   aa                      stos   BYTE PTR es:[edi],al
 8048070:   31 c0                   xor    eax,eax
 8048072:   aa                      stos   BYTE PTR es:[edi],al
 8048073:   40                      inc    eax
 8048074:   cd 80                   int    0x80

I wish to extract the opcodes as 89 e7 89 f3 .... cd 80. I tried using the following regex statement :-

opcode = ""
for line in f.readlines():
  match = re.search(r' ([\da-f]+):\s+([0-9a-f ]+)', line)
  opcode += match.group(2).strip() + " "

Though the above snippet kinda works for all my samples im sure that it would fail in the case where I had an instruction that ended with [a-f][space].

Could someone suggest a better regular expression for the same?


2 Answers

You could try the following:

r' ([\da-f]+):\s+((?:[0-9a-f]{2} )+)'

This should stop more reliably after the opcodes.

like image 197
Andrew Clark Avatar answered Jul 31 '26 20:07

Andrew Clark


You don't necessarily need regular expressions. You can just split() the string as in the following (note: this approach works if the spaces are always exactly as shown in your sample data, which seems likely since it's generated):

opcodes = []
for line in f.readlines():
    opcode = []
    for x in line.split(' ')[4:]:
        if x:
            opcode.append(x)
        else:
            opcodes.append(opcode)
            break
print opcodes

Output: [['89', 'e7'], ['89', 'fe'], ['6a', '6b'], ['58'], ['aa'], ['6a', '65'], ['58'], ['aa'], ['6a', '79'], ['58'], ['aa'], ['31', 'c0'], ['aa'], ['40'], ['cd', '80']]

#if you need strings:
print [' '.join(sublist) for sublist in opcodes]

Output: ['89 e7', '89 fe', '6a 6b', '58', 'aa', '6a 65', '58', 'aa', '6a 79', '58', 'aa', '31 c0', 'aa', '40', 'cd 80']

like image 37
alan Avatar answered Jul 31 '26 19:07

alan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!