Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pyvex/native.py: 82%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import getpass
2import hashlib
3import importlib.resources
4import os
5import pickle
6import sys
7import tempfile
8from typing import Any
10import cffi
12from .vex_ffi import ffi_str as _ffi_str
14ffi = cffi.FFI()
17def _parse_ffi_str():
18 hash_ = hashlib.md5(_ffi_str.encode("utf-8")).hexdigest()
19 cache_location = os.path.join(tempfile.gettempdir(), f"pyvex_ffi_parser_cache.{getpass.getuser()}.{hash_}")
21 if os.path.isfile(cache_location):
22 # load the cache
23 with open(cache_location, "rb") as f:
24 cache = pickle.loads(f.read())
25 ffi._parser._declarations = cache["_declarations"]
26 ffi._parser._int_constants = cache["_int_constants"]
27 else:
28 ffi.cdef(_ffi_str)
29 # cache the result
30 cache = {
31 "_declarations": ffi._parser._declarations,
32 "_int_constants": ffi._parser._int_constants,
33 }
34 # atomically write cache
35 with tempfile.NamedTemporaryFile(delete=False) as temp_file:
36 temp_file.write(pickle.dumps(cache))
37 temp_file_name = temp_file.name
38 os.replace(temp_file_name, cache_location)
41def _find_c_lib():
42 # Load the c library for calling into VEX
43 if sys.platform in ("win32", "cygwin"):
44 library_file = "pyvex.dll"
45 elif sys.platform == "darwin":
46 library_file = "libpyvex.dylib"
47 else:
48 library_file = "libpyvex.so"
50 pyvex_path = str(importlib.resources.files("pyvex") / "lib" / library_file)
51 # parse _ffi_str and use cache if possible
52 _parse_ffi_str()
53 # RTLD_GLOBAL used for sim_unicorn.so
54 lib = ffi.dlopen(pyvex_path)
56 if not lib.vex_init():
57 raise ImportError("libvex failed to initialize")
58 # this looks up all the definitions (wtf)
59 dir(lib)
60 return lib
63pvc: Any = _find_c_lib() # This should be properly typed, but this seems non trivial