|
| 1 | +#Generates a Mesos file from the current program. |
| 2 | +#@author marpie (Markus Piéton - [email protected]) |
| 3 | +#@category Mesos |
| 4 | +#@keybinding |
| 5 | +#@menupath |
| 6 | +#@toolbar |
| 7 | + |
| 8 | +import struct |
| 9 | +import ghidra.program.model.block.SimpleBlockModel as SimpleBlockModel |
| 10 | + |
| 11 | +def get_simple_blocks_by_function(image_base, listing): |
| 12 | + model = SimpleBlockModel(currentProgram) |
| 13 | + |
| 14 | + entries = {} |
| 15 | + block_iter = model.getCodeBlocks(monitor) |
| 16 | + while block_iter.hasNext() and (not monitor.isCancelled()): |
| 17 | + block = block_iter.next() |
| 18 | + for block_addr in block.getStartAddresses(): |
| 19 | + if monitor.isCancelled(): |
| 20 | + break |
| 21 | + block_offset = block_addr.getOffset() - image_base |
| 22 | + |
| 23 | + func_name = block.getName() |
| 24 | + func_offset = 0 |
| 25 | + func_offset_rel = 0 |
| 26 | + func_of_block = listing.getFunctionContaining(block_addr) |
| 27 | + if func_of_block: |
| 28 | + func_name = func_of_block.getName() |
| 29 | + func_offset = func_of_block.getEntryPoint().getOffset() |
| 30 | + func_offset_rel = func_offset - image_base |
| 31 | + block_offset = block_addr.getOffset() - func_offset |
| 32 | + |
| 33 | + try: |
| 34 | + entries["{}_{}".format(func_offset_rel,func_name)][2].append(block_offset) |
| 35 | + except KeyError: |
| 36 | + entries["{}_{}".format(func_offset_rel,func_name)] = [func_offset_rel, func_name, [block_offset]] |
| 37 | + |
| 38 | + return entries |
| 39 | + |
| 40 | +ghidra_file = askFile("Please select the Mesos Output-File", "Save To File") |
| 41 | + |
| 42 | +with open(ghidra_file.getAbsolutePath(), "wb") as fd: |
| 43 | + input_name = currentProgram.getName() |
| 44 | + image_base = currentProgram.getImageBase().getOffset() |
| 45 | + |
| 46 | + listing = currentProgram.getListing() |
| 47 | + |
| 48 | + # Write record type 0 (module) |
| 49 | + # unsigned 16-bit module name |
| 50 | + # And module name |
| 51 | + fd.write(struct.pack("<BH", 0, len(input_name)) + input_name) |
| 52 | + |
| 53 | + for func_offset, func_name, blocks in get_simple_blocks_by_function(image_base, listing).values(): |
| 54 | + # Write record type 1 (function) and unsigned 16-bit function name length |
| 55 | + fd.write(struct.pack("<BH", 1, len(func_name))) |
| 56 | + # Write function name |
| 57 | + fd.write(func_name) |
| 58 | + |
| 59 | + # Write unsigned 64-bit offset of the function WRT the module base |
| 60 | + fd.write(struct.pack("<Q", func_offset)) |
| 61 | + |
| 62 | + blocks = list(set(blocks)) |
| 63 | + blocks.sort() |
| 64 | + |
| 65 | + blockoffs = bytearray() |
| 66 | + for offset in blocks: |
| 67 | + # Write signed 32-bit offset from base of function |
| 68 | + blockoffs += struct.pack("<i", offset) |
| 69 | + |
| 70 | + # Unsigned 32-bit number of blocks |
| 71 | + fd.write(struct.pack("<I", len(blockoffs) / 4)) |
| 72 | + fd.write(blockoffs) |
0 commit comments