Skip to content

Instantly share code, notes, and snippets.

@ReplayCoding
Created January 30, 2023 00:58
Show Gist options
  • Save ReplayCoding/2db926a0e5bb6064984855dde3d57a99 to your computer and use it in GitHub Desktop.
Save ReplayCoding/2db926a0e5bb6064984855dde3d57a99 to your computer and use it in GitHub Desktop.
#Generates byte patterns & masks based on function code
#@author ReplayCoding
#@category User Scripts
#@keybinding
#@menupath
#@toolbar magnifier.png
from __future__ import print_function
listing = currentProgram.getListing()
def build_mask_from_instruction(instr):
proto = instr.getPrototype()
# for idx in range(instr.getNumOperands()):
# print(idx, proto.getOperandValueMask(idx).getBytes())
return proto.getInstructionMask().getBytes()
def get_instructions_of_func(body):
instr_bytes_mask_pair_lists = []
for i in listing.getInstructions(body, True):
instr_bytes = i.getBytes()
mask = build_mask_from_instruction(i)
instr_bytes_mask_pair_lists.append((i.getAddress(), instr_bytes, mask))
# print("{}: {} ({}) [{}]".format(i.getAddress(), i, instr_bytes, ))
return instr_bytes_mask_pair_lists
functionManager = currentProgram.getFunctionManager()
function = functionManager.getFunctionContaining(currentAddress)
print("Function: ", function)
instrs_in_func = get_instructions_of_func(function.getBody())
ins_bytes = []
mask_bytes = []
next_expected_addr = None
for (addr, ins, mask) in sorted(instrs_in_func, key = lambda x: x[0]):
if (next_expected_addr != None) and (addr != next_expected_addr):
assert(addr.getAddressSpace() == next_expected_addr.getAddressSpace())
offs = addr.getOffset()
expected_offs = next_expected_addr.getOffset()
diff = offs - expected_offs
ins_bytes.extend([0xFF] * diff)
mask_bytes.extend([0x00] * diff)
# print("PADDING @ {} ({} diff)".format(addr, diff))
ins_bytes.extend(ins)
mask_bytes.extend(mask)
next_expected_addr = addr.add(len(ins))
# Truncate patterns
MAX_PAT_SIZE = 64
def truncate(l):
if len(l) > MAX_PAT_SIZE:
return l[0:MAX_PAT_SIZE]
else:
return l
ins_bytes = truncate(ins_bytes)
mask_bytes = truncate(mask_bytes)
def print_bytes(b):
for x in b:
# if (x == 0xff):
# print('..', end=' ')
# continue
print('{:02x}'.format(x & 0xff), end = '')
print('')
print("Pat:")
print_bytes(ins_bytes)
print("Mask:")
print_bytes(mask_bytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment