diff options
Diffstat (limited to 'tools/pe_inspect.py')
| -rw-r--r-- | tools/pe_inspect.py | 416 |
1 files changed, 397 insertions, 19 deletions
diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py index 675e1ce58..07d2340a8 100644 --- a/tools/pe_inspect.py +++ b/tools/pe_inspect.py | |||
| @@ -91,6 +91,8 @@ class PeImage: | |||
| 91 | # 0x3c holds e_lfanew. Saying "no MZ header" here would blame a signature that is present. | 91 | # 0x3c holds e_lfanew. Saying "no MZ header" here would blame a signature that is present. |
| 92 | raise PeFormatError(f"file is {len(data)} bytes, shorter than the 64-byte MS-DOS header") | 92 | raise PeFormatError(f"file is {len(data)} bytes, shorter than the 64-byte MS-DOS header") |
| 93 | self.nt = struct.unpack_from("<I", data, 0x3C)[0] | 93 | self.nt = struct.unpack_from("<I", data, 0x3C)[0] |
| 94 | if self.nt < 0x40: | ||
| 95 | raise PeFormatError(f"file is {len(data)} bytes, PE header at 0x{self.nt:x} overlaps the 64-byte MS-DOS header") | ||
| 94 | if self.nt + 24 > len(data): | 96 | if self.nt + 24 > len(data): |
| 95 | raise PeFormatError(f"file is {len(data)} bytes, too short to hold the PE header at 0x{self.nt:x}") | 97 | raise PeFormatError(f"file is {len(data)} bytes, too short to hold the PE header at 0x{self.nt:x}") |
| 96 | if data[self.nt:self.nt + 4] != b"PE\0\0": | 98 | if data[self.nt:self.nt + 4] != b"PE\0\0": |
| @@ -114,6 +116,10 @@ class PeImage: | |||
| 114 | self.size_of_headers = struct.unpack_from("<I", data, opt + 60)[0] | 116 | self.size_of_headers = struct.unpack_from("<I", data, opt + 60)[0] |
| 115 | self.subsystem = struct.unpack_from("<H", data, opt + 68)[0] | 117 | self.subsystem = struct.unpack_from("<H", data, opt + 68)[0] |
| 116 | self.dll_characteristics = struct.unpack_from("<H", data, opt + 70)[0] | 118 | self.dll_characteristics = struct.unpack_from("<H", data, opt + 70)[0] |
| 119 | if self.size_of_image == 0: | ||
| 120 | raise PeFormatError("invalid SizeOfImage 0") | ||
| 121 | if self.size_of_headers > self.size_of_image: | ||
| 122 | raise PeFormatError(f"SizeOfHeaders {self.size_of_headers} exceeds SizeOfImage {self.size_of_image}") | ||
| 117 | 123 | ||
| 118 | # NumberOfRvaAndSizes counts the data directories: a slot past it is not a directory, whatever bytes it | 124 | # NumberOfRvaAndSizes counts the data directories: a slot past it is not a directory, whatever bytes it |
| 119 | # holds (runtime/src/pe_loader.cpp reads them the same way). The count is the dword before the table. | 125 | # holds (runtime/src/pe_loader.cpp reads them the same way). The count is the dword before the table. |
| @@ -257,42 +263,151 @@ def _imports(img: PeImage, kind: str, index: int, delay: bool = False) -> list[d | |||
| 257 | return entries | 263 | return entries |
| 258 | 264 | ||
| 259 | 265 | ||
| 260 | def _exports(img: PeImage) -> list[str]: | 266 | def _inspect_exports(img: PeImage) -> dict: |
| 261 | rva, size = img.directory(DIR_EXPORT) | 267 | rva, size = img.directory(DIR_EXPORT) |
| 262 | if not rva or size < 40: | 268 | if not rva or size < 40: |
| 263 | return [] | 269 | return { |
| 270 | "exports": [], | ||
| 271 | "forwarders": {}, | ||
| 272 | "invalid_export_count": 0, | ||
| 273 | "invalid_exports": [], | ||
| 274 | } | ||
| 264 | at = img.offset(rva, 40) | 275 | at = img.offset(rva, 40) |
| 265 | if at is None: | 276 | if at is None: |
| 266 | start = img.offset(rva) | 277 | start = img.offset(rva) |
| 267 | if start is not None and start + 40 > len(img.data): | 278 | if start is not None and start + 40 > len(img.data): |
| 268 | raise PeFormatError("truncated export directory") | 279 | raise PeFormatError("truncated export directory") |
| 269 | return [] | 280 | return { |
| 281 | "exports": [], | ||
| 282 | "forwarders": {}, | ||
| 283 | "invalid_export_count": 0, | ||
| 284 | "invalid_exports": [], | ||
| 285 | } | ||
| 270 | (_chars, _stamp, _major, _minor, _name, base, functions, name_count, addr_functions, | 286 | (_chars, _stamp, _major, _minor, _name, base, functions, name_count, addr_functions, |
| 271 | addr_names, addr_ordinals) = struct.unpack_from("<IIHHIIIIIII", img.data, at) | 287 | addr_names, addr_ordinals) = struct.unpack_from("<IIHHIIIIIII", img.data, at) |
| 272 | 288 | ||
| 273 | def has_export_at(index: int) -> bool: | 289 | dir_begin = rva |
| 290 | dir_end = rva + size | ||
| 291 | |||
| 292 | def get_export_rva(index: int) -> int | None: | ||
| 274 | if index >= functions: | 293 | if index >= functions: |
| 275 | return False | 294 | return None |
| 276 | # A zero RVA marks an unused slot. An RVA inside the export directory is a valid forwarder. | ||
| 277 | slot = img.offset(addr_functions + index * 4, 4) | 295 | slot = img.offset(addr_functions + index * 4, 4) |
| 278 | return slot is not None and struct.unpack_from("<I", img.data, slot)[0] != 0 | 296 | if slot is None: |
| 297 | return None | ||
| 298 | return struct.unpack_from("<I", img.data, slot)[0] | ||
| 299 | |||
| 300 | names = [] | ||
| 301 | forwarders = {} | ||
| 302 | forwarder_info = {} | ||
| 303 | invalid_exports = [] | ||
| 304 | invalid_export_count = 0 | ||
| 305 | |||
| 306 | def record_invalid(key: str, ord_num: int, exp_rva: int, reason: str) -> None: | ||
| 307 | nonlocal invalid_export_count | ||
| 308 | invalid_export_count += 1 | ||
| 309 | if len(invalid_exports) < 5: | ||
| 310 | invalid_exports.append({ | ||
| 311 | "symbol": key, | ||
| 312 | "ordinal": ord_num, | ||
| 313 | "rva": hex(exp_rva), | ||
| 314 | "reason": reason, | ||
| 315 | }) | ||
| 279 | 316 | ||
| 280 | named, names = set(), [] | 317 | def process_export(key: str, index: int, exp_rva: int) -> None: |
| 318 | ord_num = base + index | ||
| 319 | if dir_begin <= exp_rva < dir_end: | ||
| 320 | target = img.string_at(exp_rva) | ||
| 321 | if not target: | ||
| 322 | record_invalid(key, ord_num, exp_rva, "unreadable_forwarder") | ||
| 323 | target = "?" | ||
| 324 | else: | ||
| 325 | dot = target.rfind(".") | ||
| 326 | if dot <= 0 or dot + 1 >= len(target) or any(ord(c) < 0x20 or ord(c) >= 0x7F for c in target): | ||
| 327 | record_invalid(key, ord_num, exp_rva, "malformed_forwarder") | ||
| 328 | else: | ||
| 329 | fwd_sym = target[dot + 1:] | ||
| 330 | if fwd_sym.startswith("#"): | ||
| 331 | ord_str = fwd_sym[1:] | ||
| 332 | if not ord_str.isdigit() or int(ord_str) <= 0 or int(ord_str) > 0xFFFF: | ||
| 333 | record_invalid(key, ord_num, exp_rva, "malformed_forwarder") | ||
| 334 | forwarders[key] = target | ||
| 335 | forwarder_info[key] = (ord_num, exp_rva, target) | ||
| 336 | elif exp_rva >= img.size_of_image: | ||
| 337 | record_invalid(key, ord_num, exp_rva, "out_of_bounds") | ||
| 338 | |||
| 339 | named = set() | ||
| 281 | for i in range(min(name_count, MAX_ENTRIES)): | 340 | for i in range(min(name_count, MAX_ENTRIES)): |
| 282 | name_at = img.offset(addr_names + i * 4, 4) | 341 | name_at = img.offset(addr_names + i * 4, 4) |
| 283 | ord_at = img.offset(addr_ordinals + i * 2, 2) | 342 | ord_at = img.offset(addr_ordinals + i * 2, 2) |
| 284 | if name_at is None or ord_at is None: | 343 | if name_at is None or ord_at is None: |
| 285 | break | 344 | break |
| 345 | symbol_rva = struct.unpack_from("<I", img.data, name_at)[0] | ||
| 346 | symbol = img.string_at(symbol_rva) | ||
| 347 | key = symbol if symbol is not None else "?" | ||
| 286 | index = struct.unpack_from("<H", img.data, ord_at)[0] | 348 | index = struct.unpack_from("<H", img.data, ord_at)[0] |
| 287 | if not has_export_at(index): | 349 | if index >= functions: |
| 350 | record_invalid(key, base + index, 0, "out_of_range_ordinal") | ||
| 351 | continue | ||
| 352 | exp_rva = get_export_rva(index) | ||
| 353 | if exp_rva is None or exp_rva == 0: | ||
| 288 | continue | 354 | continue |
| 289 | symbol = img.string_at(struct.unpack_from("<I", img.data, name_at)[0]) | 355 | names.append(key) |
| 290 | names.append(symbol if symbol is not None else "?") | 356 | process_export(key, index, exp_rva) |
| 291 | named.add(index) | 357 | named.add(index) |
| 358 | |||
| 292 | for i in range(min(functions, MAX_ENTRIES)): | 359 | for i in range(min(functions, MAX_ENTRIES)): |
| 293 | if i not in named and has_export_at(i): | 360 | if i not in named: |
| 294 | names.append(f"#{base + i}") | 361 | exp_rva = get_export_rva(i) |
| 295 | return names | 362 | if exp_rva is not None and exp_rva != 0: |
| 363 | key = f"#{base + i}" | ||
| 364 | names.append(key) | ||
| 365 | process_export(key, i, exp_rva) | ||
| 366 | |||
| 367 | own_mod = img.string_at(_name) if _name else "" | ||
| 368 | |||
| 369 | def _stem(m: str) -> str: | ||
| 370 | s = m.lower() | ||
| 371 | return s[:-4] if s.endswith(".dll") else s | ||
| 372 | |||
| 373 | own_stem = _stem(own_mod) if own_mod else "" | ||
| 374 | if own_stem: | ||
| 375 | for fwd_key, (ord_num, exp_rva, target) in forwarder_info.items(): | ||
| 376 | if target == "?" or "." not in target: | ||
| 377 | continue | ||
| 378 | dot = target.rfind(".") | ||
| 379 | if dot <= 0 or _stem(target[:dot]) != own_stem: | ||
| 380 | continue | ||
| 381 | visited = [fwd_key] | ||
| 382 | curr_target = target | ||
| 383 | has_loop = False | ||
| 384 | while True: | ||
| 385 | c_dot = curr_target.rfind(".") | ||
| 386 | if c_dot <= 0 or _stem(curr_target[:c_dot]) != own_stem: | ||
| 387 | break | ||
| 388 | next_sym = curr_target[c_dot + 1:] | ||
| 389 | if next_sym in visited or len(visited) >= 8: | ||
| 390 | has_loop = True | ||
| 391 | break | ||
| 392 | if next_sym not in forwarders: | ||
| 393 | break | ||
| 394 | visited.append(next_sym) | ||
| 395 | curr_target = forwarders[next_sym] | ||
| 396 | if curr_target == "?": | ||
| 397 | break | ||
| 398 | if has_loop: | ||
| 399 | record_invalid(fwd_key, ord_num, exp_rva, "forwarder_loop") | ||
| 400 | |||
| 401 | return { | ||
| 402 | "exports": names, | ||
| 403 | "forwarders": forwarders, | ||
| 404 | "invalid_export_count": invalid_export_count, | ||
| 405 | "invalid_exports": invalid_exports, | ||
| 406 | } | ||
| 407 | |||
| 408 | |||
| 409 | def _exports(img: PeImage) -> list[str]: | ||
| 410 | return _inspect_exports(img)["exports"] | ||
| 296 | 411 | ||
| 297 | 412 | ||
| 298 | # The resource directory (data directory 2) and its RT_VERSION block. The version block names the build, and its | 413 | # The resource directory (data directory 2) and its RT_VERSION block. The version block names the build, and its |
| @@ -569,6 +684,203 @@ def _tls_callbacks(img: PeImage) -> int: | |||
| 569 | return count | 684 | return count |
| 570 | 685 | ||
| 571 | 686 | ||
| 687 | def _inspect_pdata(img: PeImage) -> dict: | ||
| 688 | """Exception Directory (.pdata / DIR_EXCEPTION = 3) validation and function table parsing. | ||
| 689 | |||
| 690 | Matches runtime/src/pe_loader.cpp (Loader::register_unwind) bounds, sorting, non-overlapping intervals, | ||
| 691 | and zero-length entries (e.g. symcryptk.dll). Non-x64 architectures (e.g. x86, ARM64) do not use x64 | ||
| 692 | 12-byte RUNTIME_FUNCTION tables and are gracefully rejected with informative format metadata. | ||
| 693 | """ | ||
| 694 | rva, size = img.directory(DIR_EXCEPTION) | ||
| 695 | present = bool(rva and size) | ||
| 696 | if not present: | ||
| 697 | return { | ||
| 698 | "present": False, | ||
| 699 | "rva": "0x0", | ||
| 700 | "size": 0, | ||
| 701 | "entry_count": 0, | ||
| 702 | "parsed_count": 0, | ||
| 703 | "trailing_bytes": 0, | ||
| 704 | "mapped": False, | ||
| 705 | "truncated": False, | ||
| 706 | "zero_length_count": 0, | ||
| 707 | "inverted_count": 0, | ||
| 708 | "out_of_bounds_count": 0, | ||
| 709 | "unsorted_count": 0, | ||
| 710 | "overlap_count": 0, | ||
| 711 | "min_begin": None, | ||
| 712 | "max_end": None, | ||
| 713 | "valid": True, | ||
| 714 | "sample_errors": [], | ||
| 715 | } | ||
| 716 | |||
| 717 | is_x64 = img.machine == 0x8664 | ||
| 718 | is_arm64 = img.machine == 0xAA64 | ||
| 719 | entry_size = 8 if is_arm64 else 12 | ||
| 720 | entry_count = size // entry_size | ||
| 721 | trailing_bytes = size % entry_size | ||
| 722 | |||
| 723 | bounds = img._range(rva) | ||
| 724 | |||
| 725 | if not is_x64: | ||
| 726 | if is_arm64: | ||
| 727 | fmt = "arm64" | ||
| 728 | reason = "ARM64 architecture uses 8-byte packed unwind records (not 12-byte RUNTIME_FUNCTION)" | ||
| 729 | elif img.machine == 0x14C: | ||
| 730 | fmt = "non-x64" | ||
| 731 | reason = "x86 architecture uses stack-based SEH (no 12-byte RUNTIME_FUNCTION table)" | ||
| 732 | else: | ||
| 733 | fmt = f"unsupported ({MACHINES.get(img.machine, hex(img.machine))})" | ||
| 734 | reason = f"unsupported machine architecture 0x{img.machine:x} (not x86-64)" | ||
| 735 | if bounds is None: | ||
| 736 | mapped = False | ||
| 737 | truncated = False | ||
| 738 | else: | ||
| 739 | start, end = bounds | ||
| 740 | mapped = True | ||
| 741 | needed_bytes = entry_count * entry_size | ||
| 742 | truncated = max(0, end - start) < needed_bytes | ||
| 743 | return { | ||
| 744 | "present": True, | ||
| 745 | "rva": hex(rva), | ||
| 746 | "size": size, | ||
| 747 | "entry_count": entry_count, | ||
| 748 | "parsed_count": 0, | ||
| 749 | "trailing_bytes": trailing_bytes, | ||
| 750 | "mapped": mapped, | ||
| 751 | "truncated": truncated, | ||
| 752 | "zero_length_count": 0, | ||
| 753 | "inverted_count": 0, | ||
| 754 | "out_of_bounds_count": 0, | ||
| 755 | "unsorted_count": 0, | ||
| 756 | "overlap_count": 0, | ||
| 757 | "min_begin": None, | ||
| 758 | "max_end": None, | ||
| 759 | "valid": True, | ||
| 760 | "sample_errors": [], | ||
| 761 | "format": fmt, | ||
| 762 | "rejection_reason": reason, | ||
| 763 | } | ||
| 764 | |||
| 765 | if bounds is None: | ||
| 766 | return { | ||
| 767 | "present": True, | ||
| 768 | "rva": hex(rva), | ||
| 769 | "size": size, | ||
| 770 | "entry_count": entry_count, | ||
| 771 | "parsed_count": 0, | ||
| 772 | "trailing_bytes": trailing_bytes, | ||
| 773 | "mapped": False, | ||
| 774 | "truncated": False, | ||
| 775 | "zero_length_count": 0, | ||
| 776 | "inverted_count": 0, | ||
| 777 | "out_of_bounds_count": 0, | ||
| 778 | "unsorted_count": 0, | ||
| 779 | "overlap_count": 0, | ||
| 780 | "min_begin": None, | ||
| 781 | "max_end": None, | ||
| 782 | "valid": False, | ||
| 783 | "sample_errors": [{"index": 0, "begin": "0x0", "end": "0x0", "unwind": "0x0", "reason": "unmapped"}], | ||
| 784 | } | ||
| 785 | |||
| 786 | start, end = bounds | ||
| 787 | available = max(0, end - start) | ||
| 788 | needed_bytes = entry_count * 12 | ||
| 789 | truncated = available < needed_bytes | ||
| 790 | can_parse = min(needed_bytes, available) // 12 | ||
| 791 | parsed_count = can_parse | ||
| 792 | mv = memoryview(img.data) | ||
| 793 | pdata_view = mv[start:start + can_parse * 12] | ||
| 794 | |||
| 795 | previous_begin = 0 | ||
| 796 | previous_end = 0 | ||
| 797 | min_begin = None | ||
| 798 | max_end = None | ||
| 799 | zero_length_count = 0 | ||
| 800 | inverted_count = 0 | ||
| 801 | out_of_bounds_count = 0 | ||
| 802 | unsorted_count = 0 | ||
| 803 | overlap_count = 0 | ||
| 804 | sample_errors = [] | ||
| 805 | |||
| 806 | def add_error(idx: int, b: int, e: int, u: int, reason: str) -> None: | ||
| 807 | if len(sample_errors) < 5: | ||
| 808 | sample_errors.append({ | ||
| 809 | "index": idx, | ||
| 810 | "begin": hex(b), | ||
| 811 | "end": hex(e), | ||
| 812 | "unwind": hex(u), | ||
| 813 | "reason": reason, | ||
| 814 | }) | ||
| 815 | |||
| 816 | for i, (b, e, u) in enumerate(struct.iter_unpack("<III", pdata_view)): | ||
| 817 | if min_begin is None or b < min_begin: | ||
| 818 | min_begin = b | ||
| 819 | if max_end is None or e > max_end: | ||
| 820 | max_end = e | ||
| 821 | |||
| 822 | entry_failed = False | ||
| 823 | |||
| 824 | if b == e: | ||
| 825 | zero_length_count += 1 | ||
| 826 | elif e < b: | ||
| 827 | inverted_count += 1 | ||
| 828 | add_error(i, b, e, u, "inverted") | ||
| 829 | entry_failed = True | ||
| 830 | |||
| 831 | info = u & ~1 | ||
| 832 | if (b > img.size_of_image or e > img.size_of_image | ||
| 833 | or info > img.size_of_image or (img.size_of_image - info < 4)): | ||
| 834 | out_of_bounds_count += 1 | ||
| 835 | if not entry_failed: | ||
| 836 | add_error(i, b, e, u, "out_of_bounds") | ||
| 837 | entry_failed = True | ||
| 838 | |||
| 839 | if i > 0: | ||
| 840 | if b < previous_begin: | ||
| 841 | unsorted_count += 1 | ||
| 842 | if not entry_failed: | ||
| 843 | add_error(i, b, e, u, "unsorted") | ||
| 844 | entry_failed = True | ||
| 845 | elif b < previous_end: | ||
| 846 | overlap_count += 1 | ||
| 847 | if not entry_failed: | ||
| 848 | add_error(i, b, e, u, "overlap") | ||
| 849 | entry_failed = True | ||
| 850 | |||
| 851 | previous_begin = b | ||
| 852 | if e >= b: | ||
| 853 | previous_end = max(previous_end, e) | ||
| 854 | |||
| 855 | valid = ( | ||
| 856 | not truncated | ||
| 857 | and inverted_count == 0 | ||
| 858 | and out_of_bounds_count == 0 | ||
| 859 | and unsorted_count == 0 | ||
| 860 | and overlap_count == 0 | ||
| 861 | ) | ||
| 862 | |||
| 863 | return { | ||
| 864 | "present": True, | ||
| 865 | "rva": hex(rva), | ||
| 866 | "size": size, | ||
| 867 | "entry_count": entry_count, | ||
| 868 | "parsed_count": parsed_count, | ||
| 869 | "trailing_bytes": trailing_bytes, | ||
| 870 | "mapped": True, | ||
| 871 | "truncated": truncated, | ||
| 872 | "zero_length_count": zero_length_count, | ||
| 873 | "inverted_count": inverted_count, | ||
| 874 | "out_of_bounds_count": out_of_bounds_count, | ||
| 875 | "unsorted_count": unsorted_count, | ||
| 876 | "overlap_count": overlap_count, | ||
| 877 | "min_begin": hex(min_begin) if min_begin is not None else None, | ||
| 878 | "max_end": hex(max_end) if max_end is not None else None, | ||
| 879 | "valid": valid, | ||
| 880 | "sample_errors": sample_errors, | ||
| 881 | } | ||
| 882 | |||
| 883 | |||
| 572 | _apiset_cache: dict[str, bool] = {} | 884 | _apiset_cache: dict[str, bool] = {} |
| 573 | 885 | ||
| 574 | 886 | ||
| @@ -846,12 +1158,13 @@ def _inspect(path: str, game_dir: str | None) -> dict: | |||
| 846 | for entry in imports: | 1158 | for entry in imports: |
| 847 | entry["where"] = classify_dll(entry["dll"], game_dir) | 1159 | entry["where"] = classify_dll(entry["dll"], game_dir) |
| 848 | 1160 | ||
| 849 | exports = _exports(img) | 1161 | exp = _inspect_exports(img) |
| 1162 | exports = exp["exports"] | ||
| 850 | own_names = (os.path.basename(path), _export_module_name(img)) | 1163 | own_names = (os.path.basename(path), _export_module_name(img)) |
| 851 | loads = dll_strings(img.data, {i["dll"].lower() for i in imports}, own_names) | 1164 | loads = dll_strings(img.data, {i["dll"].lower() for i in imports}, own_names) |
| 852 | for entry in loads: | 1165 | for entry in loads: |
| 853 | entry["where"] = classify_dll(entry["name"], game_dir) | 1166 | entry["where"] = classify_dll(entry["name"], game_dir) |
| 854 | pdata_rva, pdata_size = img.directory(DIR_EXCEPTION) | 1167 | pdata = _inspect_pdata(img) |
| 855 | reloc_rva, reloc_size = img.directory(DIR_BASERELOC) | 1168 | reloc_rva, reloc_size = img.directory(DIR_BASERELOC) |
| 856 | checked, system_dir = system_dll_source() | 1169 | checked, system_dir = system_dll_source() |
| 857 | 1170 | ||
| @@ -872,7 +1185,12 @@ def _inspect(path: str, game_dir: str | None) -> dict: | |||
| 872 | "imports": imports, | 1185 | "imports": imports, |
| 873 | "export_count": len(exports), | 1186 | "export_count": len(exports), |
| 874 | "exports": exports, | 1187 | "exports": exports, |
| 875 | "pdata_functions": pdata_size // 12 if pdata_rva and pdata_size >= 12 else 0, | 1188 | "forwarders": exp["forwarders"], |
| 1189 | "forwarder_count": len(exp["forwarders"]), | ||
| 1190 | "invalid_export_count": exp["invalid_export_count"], | ||
| 1191 | "invalid_exports": exp["invalid_exports"], | ||
| 1192 | "pdata_functions": pdata["entry_count"], | ||
| 1193 | "pdata": pdata, | ||
| 876 | "tls_callbacks": _tls_callbacks(img), | 1194 | "tls_callbacks": _tls_callbacks(img), |
| 877 | "runtime_load_candidates": loads, | 1195 | "runtime_load_candidates": loads, |
| 878 | # Where `system` was checked: "windows" (System32 and the OS API-set schema), "wine-prefix" (its system32 | 1196 | # Where `system` was checked: "windows" (System32 and the OS API-set schema), "wine-prefix" (its system32 |
| @@ -893,12 +1211,54 @@ def system_dlls_note(r: dict) -> str | None: | |||
| 893 | 1211 | ||
| 894 | 1212 | ||
| 895 | def to_markdown(r: dict) -> str: | 1213 | def to_markdown(r: dict) -> str: |
| 1214 | pdata_summary = f"{r['pdata_functions']:,}" | ||
| 1215 | p = r.get("pdata") | ||
| 1216 | if p and p.get("present"): | ||
| 1217 | if p.get("format"): | ||
| 1218 | pdata_summary += f" ({p['format']})" | ||
| 1219 | elif p.get("valid"): | ||
| 1220 | notes = [] | ||
| 1221 | if p.get("zero_length_count"): | ||
| 1222 | notes.append(f"{p['zero_length_count']} zero-length") | ||
| 1223 | if p.get("trailing_bytes"): | ||
| 1224 | notes.append(f"{p['trailing_bytes']} trailing bytes ignored") | ||
| 1225 | suffix = f", {', '.join(notes)}" if notes else "" | ||
| 1226 | pdata_summary += f" (OK{suffix})" | ||
| 1227 | else: | ||
| 1228 | issues = [] | ||
| 1229 | if not p.get("mapped"): | ||
| 1230 | issues.append("unmapped") | ||
| 1231 | if p.get("truncated"): | ||
| 1232 | issues.append("truncated") | ||
| 1233 | if p.get("inverted_count"): | ||
| 1234 | issues.append(f"{p['inverted_count']} inverted") | ||
| 1235 | if p.get("out_of_bounds_count"): | ||
| 1236 | issues.append(f"{p['out_of_bounds_count']} out of bounds") | ||
| 1237 | if p.get("unsorted_count"): | ||
| 1238 | issues.append(f"{p['unsorted_count']} unsorted") | ||
| 1239 | if p.get("overlap_count"): | ||
| 1240 | issues.append(f"{p['overlap_count']} overlapping") | ||
| 1241 | pdata_summary += f" (INVALID: {', '.join(issues)})" | ||
| 1242 | |||
| 1243 | exp_summary = f"{r['export_count']:,}" | ||
| 1244 | fwd_count = r.get("forwarder_count", 0) | ||
| 1245 | inv_count = r.get("invalid_export_count", 0) | ||
| 1246 | exp_parts = [] | ||
| 1247 | if fwd_count > 0: | ||
| 1248 | exp_parts.append(f"{fwd_count} forwarded") | ||
| 1249 | if inv_count > 0: | ||
| 1250 | inv_details = [f"{inv['symbol']} ({inv['reason']})" for inv in r.get("invalid_exports", [])] | ||
| 1251 | details_str = f": {', '.join(inv_details)}" if inv_details else "" | ||
| 1252 | exp_parts.append(f"INVALID: {inv_count} invalid{details_str}") | ||
| 1253 | if exp_parts: | ||
| 1254 | exp_summary += f" ({'; '.join(exp_parts)})" | ||
| 1255 | |||
| 896 | out = [f"# {r['file']}", "", | 1256 | out = [f"# {r['file']}", "", |
| 897 | f"- {r['machine']}, {'DLL' if r['is_dll'] else 'EXE'}, subsystem {r['subsystem']}, {r['size']:,} bytes", | 1257 | f"- {r['machine']}, {'DLL' if r['is_dll'] else 'EXE'}, subsystem {r['subsystem']}, {r['size']:,} bytes", |
| 898 | f"- image base {r['image_base']}, size {r['size_of_image']:,}, entry RVA {r['entry_rva']}", | 1258 | f"- image base {r['image_base']}, size {r['size_of_image']:,}, entry RVA {r['entry_rva']}", |
| 899 | f"- relocations: {'yes' if r['has_relocs'] else 'NO (must load at preferred base)'}; " | 1259 | f"- relocations: {'yes' if r['has_relocs'] else 'NO (must load at preferred base)'}; " |
| 900 | f"ASLR flag: {r['dynamic_base']}", | 1260 | f"ASLR flag: {r['dynamic_base']}", |
| 901 | f"- .pdata functions: {r['pdata_functions']:,}; TLS callbacks: {r['tls_callbacks']}; exports: {r['export_count']}", | 1261 | f"- .pdata functions: {pdata_summary}; TLS callbacks: {r['tls_callbacks']}; exports: {exp_summary}", |
| 902 | "", "## Sections", "", "| name | rva | vsize | exec | write | entropy | |", "|---|---|---|---|---|---|---|"] | 1262 | "", "## Sections", "", "| name | rva | vsize | exec | write | entropy | |", "|---|---|---|---|---|---|---|"] |
| 903 | for s in r["sections"]: | 1263 | for s in r["sections"]: |
| 904 | flag = "**encrypted?**" if s["looks_encrypted"] else "" | 1264 | flag = "**encrypted?**" if s["looks_encrypted"] else "" |
| @@ -931,6 +1291,16 @@ def to_markdown(r: dict) -> str: | |||
| 931 | out.append(", ".join(f"`{f}`" for f in imp["functions"])) | 1291 | out.append(", ".join(f"`{f}`" for f in imp["functions"])) |
| 932 | out.append("") | 1292 | out.append("") |
| 933 | out += resources_markdown(r.get("resources")) | 1293 | out += resources_markdown(r.get("resources")) |
| 1294 | forwarders = r.get("forwarders", {}) | ||
| 1295 | if forwarders: | ||
| 1296 | out += ["", "## Forwarded Exports", "", "| export | target |", "|---|---|"] | ||
| 1297 | items = sorted(forwarders.items()) | ||
| 1298 | for exp_name, target in items[:50]: | ||
| 1299 | esc_name = exp_name.replace("|", r"\|") | ||
| 1300 | esc_target = target.replace("|", r"\|") | ||
| 1301 | out.append(f"| `{esc_name}` | `{esc_target}` |") | ||
| 1302 | if len(items) > 50: | ||
| 1303 | out.append(f"| ... and {len(items) - 50} more | |") | ||
| 934 | return "\n".join(out) + "\n" | 1304 | return "\n".join(out) + "\n" |
| 935 | 1305 | ||
| 936 | 1306 | ||
| @@ -1063,7 +1433,15 @@ def main(argv: list[str] | None = None) -> int: | |||
| 1063 | enc = [s["name"] for s in r["sections"] if s["looks_encrypted"]] | 1433 | enc = [s["name"] for s in r["sections"] if s["looks_encrypted"]] |
| 1064 | shim = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "shim") | 1434 | shim = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "shim") |
| 1065 | unverified = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "unverified") | 1435 | unverified = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "unverified") |
| 1066 | print(f"{r['file']:<40} {r['machine']:<7} subsys={r['subsystem']!s:<7} pdata={r['pdata_functions']:<7} " | 1436 | pdata_status = "" |
| 1437 | p = r.get("pdata") | ||
| 1438 | if p and p.get("present"): | ||
| 1439 | if p.get("format"): | ||
| 1440 | pdata_status = p["format"] | ||
| 1441 | else: | ||
| 1442 | pdata_status = "OK" if p.get("valid") else "INVALID" | ||
| 1443 | pdata_col = f"{r['pdata_functions']} {pdata_status}".strip() | ||
| 1444 | print(f"{r['file']:<40} {r['machine']:<7} subsys={r['subsystem']!s:<7} pdata={pdata_col:<9} " | ||
| 1067 | f"shim-imports={shim:<5} encrypted={','.join(enc) or '-'}" | 1445 | f"shim-imports={shim:<5} encrypted={','.join(enc) or '-'}" |
| 1068 | + (f" unverified-imports={unverified}" if unverified else "")) | 1446 | + (f" unverified-imports={unverified}" if unverified else "")) |
| 1069 | note = system_dlls_note(r) | 1447 | note = system_dlls_note(r) |