aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/client/standalone_text_data.py (10083B)


      1 """Extract identified data from executable sections, never unknown byte gaps."""
      2 
      3 import bisect
      4 import re
      5 import struct
      6 
      7 import capstone
      8 import capstone.x86_const
      9 
     10 
     11 def extract(pe, source_directory):
     12     base = pe.OPTIONAL_HEADER.ImageBase
     13     sections = [section for section in pe.sections if section.Characteristics & 0x20000000]
     14     image = pe.get_memory_mapped_image()
     15     addresses = set()
     16     references = set()
     17     for source in sorted(source_directory.glob("*.c")):
     18         text = source.read_text(encoding="ascii")
     19         addresses.update(int(value, 16) for value in re.findall(
     20             r"(?:/\* 0x|^L_)([0-9A-Fa-f]{8})(?::)", text, re.MULTILINE))
     21         references.update(int(match.group(1), 16) for match in re.finditer(
     22             r"/\* 0x([0-9A-Fa-f]{8}): [^*\n]*\[[^\]\n]*0x[^\]\n]*\]", text))
     23         references.update(int(value, 16) for value in re.findall(
     24             r"L_([0-9A-F]{8}):\s+\{ _itail_tgt = [^\n]*MEM", text))
     25     ordered = sorted(addresses)
     26     decoder = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
     27     decoder.detail = True
     28 
     29     def code_section(address):
     30         return next((section for section in sections if
     31             base + section.VirtualAddress <= address < base + section.VirtualAddress
     32             + min(section.SizeOfRawData, section.Misc_VirtualSize)), None)
     33 
     34     def instruction(address):
     35         return next(decoder.disasm(image[address - base:address - base + 15], address, count=1))
     36 
     37     # A range must not overlap any instruction already represented by generated C.
     38     def is_data(address, size):
     39         section = code_section(address)
     40         if section is None or address + size > base + section.VirtualAddress + section.Misc_VirtualSize:
     41             return False
     42         index = bisect.bisect_left(ordered, address)
     43         if index < len(ordered) and ordered[index] < address + size:
     44             return False
     45         if index:
     46             previous = instruction(ordered[index - 1])
     47             if previous.address + previous.size > address:
     48                 return False
     49         return True
     50 
     51     spans = []
     52     classifications = []
     53     unresolved = []
     54     handlers = {}
     55 
     56     def retain(address, size, kind, referring_instruction, checked_switch=False):
     57         overlap = not is_data(address, size)
     58         if overlap and not checked_switch:
     59             unresolved.append({"instruction": referring_instruction, "address": address,
     60                                "size": size, "reason": "data overlaps discovered instructions"})
     61             return
     62         spans.append((address - base, address - base + size))
     63         classifications.append({"instruction": referring_instruction, "address": address,
     64                                 "size": size, "kind": kind,
     65                                 "overlaps_incidental_decode": overlap})
     66 
     67     def index_limit(address, register):
     68         prior = bisect.bisect_left(ordered, address)
     69         guarded = False
     70         stack_slot = None
     71         for previous in reversed(ordered[max(0, prior - 12):prior]):
     72             check = instruction(previous)
     73             if check.mnemonic == "ja" and not previous < check.operands[0].imm <= address:
     74                 guarded = True
     75             # Debug-build switches spill the checked index into a local variable.
     76             if stack_slot is None and check.mnemonic == "mov" \
     77                     and check.operands[0].type == capstone.x86_const.X86_OP_REG \
     78                     and check.operands[0].reg == register \
     79                     and check.operands[1].type == capstone.x86_const.X86_OP_MEM:
     80                 memory = check.operands[1].mem
     81                 stack_slot = (memory.base, memory.index, memory.scale, memory.disp)
     82                 continue
     83             matches = False
     84             if check.operands:
     85                 first = check.operands[0]
     86                 if stack_slot is None:
     87                     matches = first.type == capstone.x86_const.X86_OP_REG and first.reg == register
     88                 elif first.type == capstone.x86_const.X86_OP_MEM:
     89                     memory = first.mem
     90                     matches = stack_slot == (memory.base, memory.index, memory.scale, memory.disp)
     91             if check.mnemonic == "cmp" and len(check.operands) == 2 \
     92                     and matches \
     93                     and check.operands[1].type == capstone.x86_const.X86_OP_IMM:
     94                 limit = check.operands[1].imm
     95                 if guarded and 0 <= limit < 65536:
     96                     return limit
     97             if stack_slot is None and register in check.regs_access()[1]:
     98                 break
     99             if stack_slot is not None and matches and check.operands[0].access & capstone.CS_AC_WRITE:
    100                 break
    101         return None
    102 
    103     # The runtime formerly read these instruction bytes to locate exception data.
    104     # Emit their meaning as metadata; none of the handler machine code is retained.
    105     for section in sections:
    106         raw = section.get_data()
    107         for match in re.finditer(rb"\xb8(.{4})(?:\xe9|\xff\x25)", raw, re.DOTALL):
    108             info = struct.unpack("<I", match.group(1))[0]
    109             if base <= info <= base + len(image) - 20 and struct.unpack_from(
    110                     "<I", image, info - base)[0] in (0x19930520, 0x19930521, 0x19930522):
    111                 handlers[base + section.VirtualAddress + match.start()] = info
    112 
    113     # Decode only source-referenced memory operands, not a linear sweep through data.
    114     for address in sorted(references):
    115         decoded = instruction(address)
    116         for operand in decoded.operands:
    117             if operand.type != capstone.x86_const.X86_OP_MEM:
    118                 continue
    119             target = operand.mem.disp & 0xFFFFFFFF
    120             if code_section(target) is None or decoded.mnemonic == "lea":
    121                 continue
    122             if decoded.mnemonic == "jmp" and not operand.mem.base \
    123                     and operand.mem.index and operand.mem.scale == 4:
    124                 count = 0
    125                 limit = index_limit(address, operand.mem.index)
    126                 while code_section(target + count * 4 + 3) is not None:
    127                     value = struct.unpack_from("<I", image, target - base + count * 4)[0]
    128                     if value not in addresses:
    129                         break
    130                     count += 1
    131                     if limit is not None and count == limit + 1:
    132                         break
    133                 if count and (limit is None or count == limit + 1):
    134                     retain(target, count * 4, "switch-targets", address, limit is not None)
    135                     continue
    136             elif not operand.mem.base and not operand.mem.index:
    137                 retain(target, operand.size, "absolute-memory-operand", address)
    138                 continue
    139             elif not (operand.mem.base and operand.mem.index):
    140                 # MSVC compact switches range-check an index before a byte lookup.
    141                 register = operand.mem.index or operand.mem.base
    142                 scale = operand.mem.scale if operand.mem.index else 1
    143                 limit = index_limit(address, register)
    144                 if limit is not None:
    145                     # A compact switch can resemble instructions to a speculative scan.
    146                     # Prove its byte values select real case labels before retaining it.
    147                     compact_switch = False
    148                     if decoded.mnemonic == "mov" and operand.size == 1 and scale == 1 \
    149                             and decoded.operands[0].type == capstone.x86_const.X86_OP_REG:
    150                         jump = instruction(address + decoded.size)
    151                         destination = decoded.reg_name(decoded.operands[0].reg)
    152                         parent = {"al": "eax", "bl": "ebx", "cl": "ecx", "dl": "edx"}.get(destination)
    153                         if jump.mnemonic == "jmp" and jump.operands[0].type == capstone.x86_const.X86_OP_MEM:
    154                             table = jump.operands[0].mem
    155                             if not table.base and table.scale == 4 and jump.reg_name(table.index) == parent:
    156                                 indices = image[target - base:target - base + limit + 1]
    157                                 table_address = table.disp & 0xffffffff
    158                                 table_size = (max(indices) + 1) * 4
    159                                 if len(indices) == limit + 1 and code_section(target) is code_section(target + limit) \
    160                                         and code_section(table_address) is not None and is_data(table_address, table_size):
    161                                     cases = struct.unpack_from(f"<{table_size // 4}I", image, table_address - base)
    162                                     compact_switch = all(case in addresses and not target <= case < target + limit + 1
    163                                                          for case in cases)
    164                     retain(target, limit * scale + operand.size, "range-checked-index", address, compact_switch)
    165                 else:
    166                     unresolved.append({"instruction": address, "address": target,
    167                                        "reason": "indexed memory operand without proven bound"})
    168                 continue
    169             unresolved.append({"instruction": address, "address": target,
    170                                "reason": "unclassified executable-section memory operand"})
    171 
    172     # Merge only overlapping/adjacent classified ranges; never bridge an unknown gap.
    173     merged = []
    174     for start, end in sorted(spans):
    175         if merged and start <= merged[-1][1]:
    176             merged[-1] = (merged[-1][0], max(end, merged[-1][1]))
    177         else:
    178             merged.append((start, end))
    179     ranges = [(start, image[start:end]) for start, end in merged]
    180     audit = {"classified": classifications, "unresolved": unresolved,
    181              "instruction_addresses": len(addresses), "exception_handlers": len(handlers),
    182              "retained_text_bytes": sum(len(data) for _, data in ranges),
    183              "code_outside_executable_sections": [address for address in ordered
    184                  if code_section(address) is None]}
    185     return ranges, handlers, audit