Skip to content

Instantly share code, notes, and snippets.

@nullableVoidPtr
Created September 24, 2018 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullableVoidPtr/c77e51837466d137dfdc240e966ae5bf to your computer and use it in GitHub Desktop.
Save nullableVoidPtr/c77e51837466d137dfdc240e966ae5bf to your computer and use it in GitHub Desktop.
#!/usr/bin/python
from sys import argv
from struct import unpack
def dump_coff(input_buffer):
header = dict(zip(['signature', 'bytes_in_last_block', 'blocks_in_file',
'num_relocs', 'header_paragraphs', 'min_extra_paragraphs',
'max_extra_paragraphs', 'ss', 'sp', 'checksum', 'ip', 'cs',
'reloc_table_offset', 'overlay_number'], unpack("<HHHHHHHHHHHHHH", input_buffer[:28])))
if header['signature'] != 0x5A4D:
raise RuntimeError("Invalid signature!")
return input_buffer[header['blocks_in_file'] * 512 - (512 - header['bytes_in_last_block'] if header['bytes_in_last_block'] else 0):]
def dump_flat(input_coff, out_file):
header = dict(zip(['f_magic', 'f_nscns', 'f_timdat', 'f_symptr',
'f_nsyms', 'f_opthdr', 'f_flags'], unpack("<HHLLLHH", input_coff[:20])))
if header['f_magic'] != 0x014C:
raise RuntimeError("Invalid COFF magic!")
for section in [dict(zip(['s_name', 's_paddr', 's_vaddr', 's_size', 's_scnptr', 's_relptr', 's_lnnoptr', 's_nreloc', 's_nlnno', 's_flags'], unpack("8sLLLLLLHHL",input_coff[begin:end]))) for begin, end in [(20+header['f_opthdr']+(n*40), 60+header['f_opthdr']+(n*40)) for n in range(header['f_nscns'])]]:
out_file.seek(section['s_paddr'])
out_file.write(chr(0)*section['s_size'] if section['s_flags'] == 0x80 else input_coff[section['s_scnptr']:section['s_scnptr']+section['s_size']])
if __name__ == '__main__':
if len(argv) < 3:
exit(1)
else:
try:
with open(argv[1], 'rb') as file:
with open(argv[2], 'wb') as flat:
dump_flat(dump_coff(file.read()), flat)
except EnvironmentError:
print("Unable to open file!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment