| 1 | #!/usr/bin/env python3 |
| 2 | """Lists what an executable imports that Windows 7 lacks, which stops it loading there: |
| 3 | `imports.py EXE DLLS`, DLLS a folder of Windows 7's System32 DLLs (copied from the lab VM), |
| 4 | reading both with llvm-mingw's llvm-readobj.""" |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | import re |
| 8 | import subprocess |
| 9 | import sys |
| 10 | |
| 11 | ROOT = Path(__file__).resolve().parents[2] |
| 12 | READOBJ = Path(os.environ.get('LLVM_MINGW', ROOT / 'target/windows/llvm-mingw')) / 'bin/llvm-readobj' |
| 13 | |
| 14 | |
| 15 | def readobj(flag, path): |
| 16 | return subprocess.run([READOBJ, flag, path], capture_output=True, text=True, check=True).stdout |
| 17 | |
| 18 | |
| 19 | def imports(executable): |
| 20 | """Each imported DLL, lowercased, with the names imported from it.""" |
| 21 | found, dll = {}, None |
| 22 | for line in readobj('--coff-imports', executable).splitlines(): |
| 23 | if match := re.match(r'\s*Name: (\S+)', line): |
| 24 | dll = found.setdefault(match[1].lower(), set()) |
| 25 | elif (match := re.match(r'\s*Symbol: (\S+)', line)) and dll is not None: |
| 26 | dll.add(match[1]) |
| 27 | return found |
| 28 | |
| 29 | |
| 30 | def main(): |
| 31 | executable, folder = map(Path, sys.argv[1:3]) |
| 32 | dlls = {path.name.lower(): path for path in folder.iterdir()} |
| 33 | missing = [] |
| 34 | for dll, names in sorted(imports(executable).items()): |
| 35 | if dll not in dlls: |
| 36 | missing.append(f'{dll} (no such DLL): {", ".join(sorted(names))}') |
| 37 | continue |
| 38 | exported = set(re.findall(r'Name: (\S+)', readobj('--coff-exports', dlls[dll]))) |
| 39 | missing += [f'{dll}!{name}' for name in sorted(names - exported)] |
| 40 | print('\n'.join(missing) or 'Every import exists on Windows 7.') |
| 41 | sys.exit(1 if missing else 0) |
| 42 | |
| 43 | |
| 44 | if __name__ == '__main__': |
| 45 | main() |