|
1 | 1 | import re
|
2 | 2 | import sys
|
3 | 3 |
|
| 4 | +from subprocess import Popen, PIPE |
4 | 5 | from typing import List
|
5 | 6 |
|
| 7 | +RE_IS_INCLUDE = re.compile(rb'^\s*#\s*include\b') |
| 8 | +RE_RESULT = re.compile(rb'__RESULT\((.*?)\)RESULT__') |
| 9 | + |
| 10 | +ACTION = sys.argv[1] |
| 11 | +SEP_INDEX = sys.argv[2:].index('--') |
| 12 | +CC_COMMAND = sys.argv[2:][:SEP_INDEX] |
| 13 | +FILES = sys.argv[2:][SEP_INDEX + 1:] |
6 | 14 |
|
7 |
| -def find_symbols(*wrapper_names: str) -> List[str]: |
8 |
| - fun_matches = '|'.join(map(re.escape, wrapper_names)) |
9 |
| - wrap_sym_re = re.compile(rf'(?:{fun_matches})\s*\(\s*(\S+?)\s*\)') |
10 | 15 |
|
| 16 | +def find_symbols(*wrapper_names: str) -> List[str]: |
| 17 | + args = map(lambda n: f'-D{n}(x)=__RESULT(x)RESULT__', wrapper_names) |
| 18 | + cmd = CC_COMMAND + ['-E'] + list(args) + ['-'] |
11 | 19 | symbols = []
|
12 |
| - for path in sys.argv[2:]: |
13 |
| - with open(path, 'r') as src: |
| 20 | + for path in FILES: |
| 21 | + with open(path, 'rb') as src: |
| 22 | + process = Popen(cmd, stdin=PIPE, stdout=PIPE) |
14 | 23 | for line in src:
|
15 |
| - if line.lstrip().startswith('#'): |
| 24 | + if RE_IS_INCLUDE.match(line): |
16 | 25 | continue
|
17 |
| - for match in wrap_sym_re.finditer(line): |
18 |
| - symbols.append(match.group(1)) |
19 |
| - return symbols |
| 26 | + process.stdin.write(line) |
| 27 | + process.stdin.close() |
| 28 | + data = process.stdout.read() |
| 29 | + process.wait() |
| 30 | + symbols += [m.group(1) for m in RE_RESULT.finditer(data)] |
| 31 | + return [sym.decode() for sym in symbols] |
20 | 32 |
|
21 | 33 |
|
22 |
| -if sys.argv[1] == '--map': |
| 34 | +if ACTION == '--map': |
23 | 35 | symbols = find_symbols('WRAP_SYM', 'EXPORT_SYM')
|
24 | 36 | exported = ''.join(map(lambda s: ' "' + s + '";', symbols))
|
25 | 37 | sys.stdout.write("{\n global:" + exported + "\n local: *;\n};\n")
|
26 |
| -elif sys.argv[1] == '--ldscript': |
| 38 | +elif ACTION == '--ldscript': |
27 | 39 | symbols = find_symbols('WRAP_SYM')
|
28 | 40 | lines = map(lambda s: f'PROVIDE({s} = ip2unix_wrap_{s});', symbols)
|
29 | 41 | sys.stdout.write("\n".join(lines) + "\n")
|
0 commit comments