|
| 1 | +import contextlib |
| 2 | +import functools |
| 3 | +import os |
| 4 | +import platform |
| 5 | +import re |
| 6 | +import subprocess |
| 7 | +import tempfile |
| 8 | +from typing import List, Optional, Union |
| 9 | +from ptrlib.arch.arm import is_arch_arm, ConstsTableArm |
| 10 | +from ptrlib.arch.intel import is_arch_intel, ConstsTableIntel |
| 11 | + |
| 12 | +try: |
| 13 | + cache = functools.cache |
| 14 | +except AttributeError: |
| 15 | + cache = functools.lru_cache |
| 16 | + |
| 17 | + |
| 18 | +_TEMPLATE_C = """ |
| 19 | +#include <stdio.h> |
| 20 | +#include <{0}> |
| 21 | +
|
| 22 | +#define print_const(X) (void)_Generic((X), \ |
| 23 | + char*: printf("S:%s\\n", (const char*)(X)), \ |
| 24 | + default: printf("V:%lu\\n", (size_t)(X)) \ |
| 25 | +) |
| 26 | +
|
| 27 | +int main() {{ |
| 28 | + print_const({1}); |
| 29 | + return 0; |
| 30 | +}} |
| 31 | +""" |
| 32 | + |
| 33 | +# ConstsTableLinux: Experimental feature |
| 34 | +class ConstsTableLinux(object): |
| 35 | + def resolve_constant(self, |
| 36 | + const: str, |
| 37 | + include_path: Optional[List[str]] = None) -> Union[int, str]: |
| 38 | + from ptrlib.arch.common import which |
| 39 | + |
| 40 | + if len(const) == 0: |
| 41 | + raise KeyError("Empty name '{}'".format(const)) |
| 42 | + |
| 43 | + if include_path is not None: |
| 44 | + include_path = include_path + ['/usr/include'] |
| 45 | + else: |
| 46 | + include_path = ['/usr/include'] |
| 47 | + |
| 48 | + def heuristic_redirect(path: str) -> str: |
| 49 | + """Convert include path""" |
| 50 | + with open(path, 'r') as f: |
| 51 | + buf = f.read() |
| 52 | + found = re.findall(r"Never use <.+> directly; include <(.+)> instead\.", buf) |
| 53 | + if found: |
| 54 | + return found[0] |
| 55 | + else: |
| 56 | + return path |
| 57 | + |
| 58 | + def test_constant(path: str, name: str, gcc_path: str) -> Optional[Union[int, str]]: |
| 59 | + """Compile and run C code to get constant value""" |
| 60 | + path = heuristic_redirect(path) |
| 61 | + fname_c = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())+'.c' |
| 62 | + fname_bin = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())+'.bin' |
| 63 | + with open(fname_c, 'w') as f: |
| 64 | + f.write(_TEMPLATE_C.format(path, name)) |
| 65 | + |
| 66 | + with contextlib.suppress(FileNotFoundError): |
| 67 | + p = subprocess.run([gcc_path, fname_c, '-o', fname_bin], |
| 68 | + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) |
| 69 | + os.unlink(fname_c) |
| 70 | + |
| 71 | + if p.returncode == 0: |
| 72 | + p = subprocess.run([fname_bin], |
| 73 | + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) |
| 74 | + os.unlink(fname_bin) |
| 75 | + |
| 76 | + if p.returncode == 0: |
| 77 | + if p.stdout.startswith(b"S:"): |
| 78 | + return p.stdout[2:].decode().strip() |
| 79 | + elif p.stdout.startswith(b"V:"): |
| 80 | + return int(p.stdout[2:]) |
| 81 | + else: |
| 82 | + raise RuntimeError(f"Unexpected output: {p.stdout.decode()}") |
| 83 | + |
| 84 | + return |
| 85 | + |
| 86 | + # We rely on grep since it's much faster |
| 87 | + grep_path = which('grep') |
| 88 | + if grep_path is None: |
| 89 | + raise FileNotFoundError("'grep' not found") |
| 90 | + |
| 91 | + if is_arch_intel(platform.machine()): |
| 92 | + gcc_path = which('gcc') |
| 93 | + else: |
| 94 | + gcc_path = which('x86_64-linux-gnu-gcc') |
| 95 | + if gcc_path is None: |
| 96 | + raise FileNotFoundError("Install 'gcc' for this architecture") |
| 97 | + |
| 98 | + for dpath in include_path: |
| 99 | + # We can directly build regex since `const` is a valid Python variable name |
| 100 | + p = subprocess.run([grep_path, '-E', f'#\\s*define\\s+{const}', '-rl', dpath], |
| 101 | + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) |
| 102 | + if p.returncode != 0: |
| 103 | + continue |
| 104 | + |
| 105 | + for path in p.stdout.decode().split('\n'): |
| 106 | + if not os.path.exists(path): |
| 107 | + continue |
| 108 | + |
| 109 | + c = test_constant(path, const, gcc_path) |
| 110 | + if c is not None: |
| 111 | + return c |
| 112 | + |
| 113 | + raise KeyError("Could not find constant: {}".format(const)) |
| 114 | + |
| 115 | + @cache |
| 116 | + def __getitem__(self, const_or_arch: str) -> Union[int, str, ConstsTableIntel, ConstsTableArm]: |
| 117 | + if is_arch_intel(const_or_arch): |
| 118 | + return ConstsTableIntel() |
| 119 | + elif is_arch_arm(const_or_arch): |
| 120 | + return ConstsTableArm() |
| 121 | + elif const_or_arch.isupper(): |
| 122 | + return self.resolve_constant(const_or_arch) |
| 123 | + else: |
| 124 | + raise KeyError("Invalid name '{}'".format(arch)) |
| 125 | + |
| 126 | + def __getattr__(self, arch: str): |
| 127 | + return self[arch] |
| 128 | + |
| 129 | + |
| 130 | +consts = ConstsTableLinux() |
0 commit comments