|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import os |
| 5 | +from pathlib import Path |
| 6 | +import shlex |
| 7 | +import shutil |
| 8 | +import subprocess |
| 9 | +import sys |
| 10 | + |
| 11 | + |
| 12 | +def split_command(value): |
| 13 | + if not value: |
| 14 | + return None |
| 15 | + value = value.strip() |
| 16 | + if not value: |
| 17 | + return None |
| 18 | + return shlex.split(value, posix=(os.name != 'nt')) |
| 19 | + |
| 20 | + |
| 21 | +def find_compiler(): |
| 22 | + for var in ('CC', 'CXX'): |
| 23 | + command = split_command(os.environ.get(var)) |
| 24 | + if command and shutil.which(command[0]): |
| 25 | + return command |
| 26 | + |
| 27 | + for name in ('cl.exe', 'cl', 'clang-cl.exe', 'clang-cl', 'cc', 'clang', 'gcc'): |
| 28 | + path = shutil.which(name) |
| 29 | + if path: |
| 30 | + return [path] |
| 31 | + |
| 32 | + raise RuntimeError('Unable to locate a compiler for preprocessing assembly') |
| 33 | + |
| 34 | + |
| 35 | +def preprocess(args): |
| 36 | + compiler = find_compiler() |
| 37 | + output = Path(args.output) |
| 38 | + output.parent.mkdir(parents=True, exist_ok=True) |
| 39 | + |
| 40 | + if os.name == 'nt' and Path(compiler[0]).name.lower() in ('cl.exe', 'cl', 'clang-cl.exe', 'clang-cl'): |
| 41 | + command = compiler + ['/nologo', '/EP', '/TC'] |
| 42 | + command += [f'/I{include_dir}' for include_dir in args.include_dir] |
| 43 | + command += [f'/D{define}' for define in args.define] |
| 44 | + command += [args.input] |
| 45 | + else: |
| 46 | + command = compiler + ['-E', '-P', '-x', 'c'] |
| 47 | + command += [f'-I{include_dir}' for include_dir in args.include_dir] |
| 48 | + command += [f'-D{define}' for define in args.define] |
| 49 | + command += [args.input] |
| 50 | + |
| 51 | + result = subprocess.run(command, capture_output=True, text=True) |
| 52 | + if result.returncode != 0: |
| 53 | + sys.stderr.write(result.stderr) |
| 54 | + raise RuntimeError(f'Preprocessing failed: {" ".join(command)}') |
| 55 | + |
| 56 | + output.write_text(result.stdout, encoding='utf-8') |
| 57 | + |
| 58 | + |
| 59 | +def main(argv=None): |
| 60 | + parser = argparse.ArgumentParser(description='Preprocess libffi assembly source') |
| 61 | + parser.add_argument('--input', required=True) |
| 62 | + parser.add_argument('--output', required=True) |
| 63 | + parser.add_argument('--include-dir', action='append', default=[]) |
| 64 | + parser.add_argument('--define', action='append', default=[]) |
| 65 | + args = parser.parse_args(argv) |
| 66 | + |
| 67 | + preprocess(args) |
| 68 | + return 0 |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + raise SystemExit(main()) |
0 commit comments