DSCF

.co.uk

PC32

A ColorForth compiler and editor for x86-64
git clone https://dscf.co.uk/clone/PC32.git
Log | Files | Refs | README

pepatch.py (1703B)


      1 #!/usr/bin/env python3
      2 """Post-link fixups for PC32.exe (the VM needs fixed addresses and executable data).
      3 
      4  - clears DYNAMIC_BASE (ASLR) and NX_COMPAT (DEP opt-in) in DllCharacteristics: the
      5    Debian MinGW linker (binutils 2.31) sets both by default and has no option to turn them off
      6  - makes the VM's sections (.pc32t code, .pc32d data) readable+writable+executable (nasm 2.14's
      7    win32 format doesn't honour the section attributes, so it's done here)
      8 
      9 usage: pepatch.py FILE.exe
     10 """
     11 import struct, sys
     12 fn = sys.argv[1]
     13 b = bytearray(open(fn, "rb").read(65536))   # headers only
     14 pe = struct.unpack_from("<I", b, 0x3c)[0]
     15 assert b[pe:pe+4] == b"PE\0\0", "not a PE file"
     16 nsec = struct.unpack_from("<H", b, pe + 6)[0]
     17 opt = struct.unpack_from("<H", b, pe + 20)[0]
     18 o = pe + 24
     19 dllch = struct.unpack_from("<H", b, o + 70)[0]
     20 new = dllch & ~(0x0040 | 0x0100 | 0x0020)        # dynamic base, NX compat, high-entropy VA
     21 if new != dllch:
     22     with open(fn, "r+b") as f:
     23         f.seek(o + 70); f.write(struct.pack("<H", new))
     24     print("DllCharacteristics %04x -> %04x" % (dllch, new))
     25 st = o + opt
     26 RWX = 0xE0000000           # IMAGE_SCN_MEM_EXECUTE | MEM_READ | MEM_WRITE
     27 found = 0
     28 for i in range(nsec):
     29     off = st + i*40
     30     name = b[off:off+8].rstrip(b"\0").decode()
     31     if name in (".pc32t", ".pc32d"):
     32         ch = struct.unpack_from("<I", b, off + 36)[0]
     33         new = ch | RWX
     34         found += 1
     35         if new != ch:
     36             with open(fn, "r+b") as f:
     37                 f.seek(off + 36); f.write(struct.pack("<I", new))
     38         print("%s section flags %08x -> %08x (read+write+execute)" % (name, ch, new))
     39 if found != 2:
     40     sys.exit("expected the .pc32t and .pc32d sections, found %d" % found)