bindepend.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2013-2023, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. """
  12. Find external dependencies of binary libraries.
  13. """
  14. import ctypes.util
  15. import functools
  16. import os
  17. import pathlib
  18. import re
  19. import sys
  20. import sysconfig
  21. import subprocess
  22. from PyInstaller import compat
  23. from PyInstaller import log as logging
  24. from PyInstaller.depend import dylib, utils
  25. from PyInstaller.utils.win32 import winutils
  26. from PyInstaller.exceptions import PythonLibraryNotFoundError
  27. if compat.is_darwin:
  28. import PyInstaller.utils.osx as osxutils
  29. logger = logging.getLogger(__name__)
  30. _exe_machine_type = None
  31. if compat.is_win:
  32. _exe_machine_type = winutils.get_pe_file_machine_type(compat.python_executable)
  33. #- High-level binary dependency analysis
  34. def _get_paths_for_parent_directory_preservation():
  35. """
  36. Return list of paths that serve as prefixes for parent-directory preservation of collected binaries and/or
  37. shared libraries. If a binary is collected from a location that starts with a path from this list, the relative
  38. directory structure is preserved within the frozen application bundle; otherwise, the binary is collected to the
  39. frozen application's top-level directory.
  40. """
  41. # Use only site-packages paths. We have no control over contents of `sys.path`, so using all paths from that may
  42. # lead to unintended behavior in corner cases. For example, if `sys.path` contained the drive root (see #7028),
  43. # all paths that do not match some other sub-path rooted in that drive will end up recognized as relative to the
  44. # drive root. In such case, any DLL collected from `c:\Windows\system32` will be collected into `Windows\system32`
  45. # sub-directory; ucrt DLLs collected from MSVC or Windows SDK installed in `c:\Program Files\...` will end up
  46. # collected into `Program Files\...` subdirectory; etc.
  47. #
  48. # On the other hand, the DLL parent directory preservation is primarily aimed at packages installed via PyPI
  49. # wheels, which are typically installed into site-packages. Therefore, limiting the directory preservation for
  50. # shared libraries collected from site-packages should do the trick, and should be reasonably safe.
  51. import site
  52. orig_paths = site.getsitepackages()
  53. orig_paths.append(site.getusersitepackages())
  54. # Explicitly excluded paths. `site.getsitepackages` seems to include `sys.prefix`, which we need to exclude, to
  55. # avoid issue swith DLLs in its sub-directories. We need both resolved and unresolved variant to handle cases
  56. # where `base_prefix` itself is a symbolic link (e.g., `scoop`-installed python on Windows, see #8023).
  57. excluded_paths = {
  58. pathlib.Path(sys.base_prefix),
  59. pathlib.Path(sys.base_prefix).resolve(),
  60. pathlib.Path(sys.prefix),
  61. pathlib.Path(sys.prefix).resolve(),
  62. }
  63. # For each path in orig_paths, append a resolved variant. This helps with linux venv where we need to consider
  64. # both `venv/lib/python3.11/site-packages` and `venv/lib/python3.11/site-packages` and `lib64` is a symlink
  65. # to `lib`.
  66. orig_paths += [pathlib.Path(path).resolve() for path in orig_paths]
  67. paths = set()
  68. for path in orig_paths:
  69. if not path:
  70. continue
  71. path = pathlib.Path(path)
  72. # Filter out non-directories (e.g., /path/to/python3x.zip) or non-existent paths
  73. if not path.is_dir():
  74. continue
  75. # Filter out explicitly excluded paths
  76. if path in excluded_paths:
  77. continue
  78. paths.add(path)
  79. # Sort by length (in term of path components) to ensure match against the longest common prefix (for example, match
  80. # /path/to/venv/lib/site-packages instead of /path/to/venv when both paths are in site paths).
  81. paths = sorted(paths, key=lambda x: len(x.parents), reverse=True)
  82. return paths
  83. def _select_destination_directory(src_filename, parent_dir_preservation_paths):
  84. # Check parent directory preservation paths
  85. for parent_dir_preservation_path in parent_dir_preservation_paths:
  86. if parent_dir_preservation_path in src_filename.parents:
  87. # Collect into corresponding sub-directory.
  88. return src_filename.relative_to(parent_dir_preservation_path)
  89. # Collect into top-level directory.
  90. return src_filename.name
  91. def binary_dependency_analysis(binaries, search_paths=None, symlink_suppression_patterns=None):
  92. """
  93. Perform binary dependency analysis on the given TOC list of collected binaries, by recursively scanning each binary
  94. for linked dependencies (shared library imports). Returns new TOC list that contains both original entries and their
  95. binary dependencies.
  96. Additional search paths for dependencies' full path resolution may be supplied via optional argument.
  97. """
  98. # Get all path prefixes for binaries' parent-directory preservation. For binaries collected from packages in (for
  99. # example) site-packages directory, we should try to preserve the parent directory structure.
  100. parent_dir_preservation_paths = _get_paths_for_parent_directory_preservation()
  101. # Keep track of processed binaries and processed dependencies.
  102. processed_binaries = set()
  103. processed_dependencies = set()
  104. # Keep track of unresolved dependencies, in order to defer the missing-library warnings until after everything has
  105. # been processed. This allows us to suppress warnings for dependencies that end up being collected anyway; for
  106. # details, see the end of this function.
  107. missing_dependencies = []
  108. # Populate output TOC with input binaries - this also serves as TODO list, as we iterate over it while appending
  109. # new entries at the end.
  110. output_toc = binaries[:]
  111. for dest_name, src_name, typecode in output_toc:
  112. # Do not process symbolic links (already present in input TOC list, or added during analysis below).
  113. if typecode == 'SYMLINK':
  114. continue
  115. # Keep track of processed binaries, to avoid unnecessarily repeating analysis of the same file. Use pathlib.Path
  116. # to avoid having to worry about case normalization.
  117. src_path = pathlib.Path(src_name)
  118. if src_path in processed_binaries:
  119. continue
  120. processed_binaries.add(src_path)
  121. logger.debug("Analyzing binary %r", src_name)
  122. # Analyze imports (linked dependencies)
  123. for dep_name, dep_src_path in get_imports(src_name, search_paths):
  124. logger.debug("Processing dependency, name: %r, resolved path: %r", dep_name, dep_src_path)
  125. # Skip unresolved dependencies. Defer the missing-library warnings until after binary dependency analysis
  126. # is complete.
  127. if not dep_src_path:
  128. missing_dependencies.append((dep_name, src_name))
  129. continue
  130. # Compare resolved dependency against global inclusion/exclusion rules.
  131. if not dylib.include_library(dep_src_path):
  132. logger.debug("Skipping dependency %r due to global exclusion rules.", dep_src_path)
  133. continue
  134. dep_src_path = pathlib.Path(dep_src_path) # Turn into pathlib.Path for subsequent processing
  135. # Avoid processing this dependency if we have already processed it.
  136. if dep_src_path in processed_dependencies:
  137. logger.debug("Skipping dependency %r due to prior processing.", str(dep_src_path))
  138. continue
  139. processed_dependencies.add(dep_src_path)
  140. # Try to preserve parent directory structure, if applicable.
  141. # NOTE: do not resolve the source path, because on macOS and linux, it may be a versioned .so (e.g.,
  142. # libsomething.so.1, pointing at libsomething.so.1.2.3), and we need to collect it under original name!
  143. dep_dest_path = _select_destination_directory(dep_src_path, parent_dir_preservation_paths)
  144. dep_dest_path = pathlib.PurePath(dep_dest_path) # Might be a str() if it is just a basename...
  145. # If we are collecting library into top-level directory on macOS, check whether it comes from a
  146. # .framework bundle. If it does, re-create the .framework bundle in the top-level directory
  147. # instead.
  148. if compat.is_darwin and dep_dest_path.parent == pathlib.PurePath('.'):
  149. if osxutils.is_framework_bundle_lib(dep_src_path):
  150. # dst_src_path is parent_path/Name.framework/Versions/Current/Name
  151. framework_parent_path = dep_src_path.parent.parent.parent.parent
  152. dep_dest_path = pathlib.PurePath(dep_src_path.relative_to(framework_parent_path))
  153. logger.debug("Collecting dependency %r as %r.", str(dep_src_path), str(dep_dest_path))
  154. output_toc.append((str(dep_dest_path), str(dep_src_path), 'BINARY'))
  155. # On non-Windows, if we are not collecting the binary into application's top-level directory ('.'),
  156. # add a symbolic link from top-level directory to the actual location. This is to accommodate
  157. # LD_LIBRARY_PATH being set to the top-level application directory on linux (although library search
  158. # should be mostly done via rpaths, so this might be redundant) and to accommodate library path
  159. # rewriting on macOS, which assumes that the library was collected into top-level directory.
  160. if compat.is_win:
  161. # We do not use symlinks on Windows.
  162. pass
  163. elif dep_dest_path.parent == pathlib.PurePath('.'):
  164. # The shared library itself is being collected into top-level application directory.
  165. pass
  166. elif any(dep_src_path.match(pattern) for pattern in symlink_suppression_patterns):
  167. # Honor symlink suppression patterns specified by hooks.
  168. logger.debug(
  169. "Skipping symbolic link from %r to top-level application directory due to source path matching one "
  170. "of symlink suppression path patterns.", str(dep_dest_path)
  171. )
  172. else:
  173. logger.debug("Adding symbolic link from %r to top-level application directory.", str(dep_dest_path))
  174. output_toc.append((str(dep_dest_path.name), str(dep_dest_path), 'SYMLINK'))
  175. # Handle missing dependencies: display warnings, add missing symbolic links to top-level application directory, etc.
  176. seen_binaries = {
  177. os.path.normcase(os.path.basename(src_name)): (dest_name, src_name, typecode)
  178. for dest_name, src_name, typecode in output_toc if typecode != 'SYMLINK'
  179. }
  180. existing_symlinks = set([dest_name for dest_name, src_name, typecode in output_toc if typecode == 'SYMLINK'])
  181. for dependency_name, referring_binary in missing_dependencies:
  182. # Ignore libraries that we would not collect in the first place.
  183. if not dylib.include_library(dependency_name):
  184. continue
  185. # If the binary with a matching basename happens to be among the discovered binaries, suppress the message as
  186. # well. This might happen either because the library was collected by some other mechanism (for example, via
  187. # hook, or supplied by the user), or because it was discovered during the analysis of another binary (which,
  188. # for example, had properly set run-paths on Linux/macOS or was located next to that other analyzed binary on
  189. # Windows).
  190. #
  191. # On non-Windows, also check if symbolic link to the discovered binary already exists in the top-level
  192. # application directory, and if not, create it. This is important especially on macOS, where our library path
  193. # rewriting assumes that all dependent libraries are available in the top-level application directory, or
  194. # linked into it.
  195. dependency_basename = os.path.normcase(os.path.basename(dependency_name))
  196. dependency_toc_entry = seen_binaries.get(dependency_basename, None)
  197. if dependency_toc_entry is None:
  198. # Not found, emit a warning (subject to global warning suppression rules).
  199. if not dylib.warn_missing_lib(dependency_name):
  200. continue
  201. logger.warning(
  202. "Library not found: could not resolve %r, dependency of %r.", dependency_name, referring_binary
  203. )
  204. elif not compat.is_win:
  205. # Found; generate symbolic link if necessary.
  206. dependency_dest_path = pathlib.PurePath(dependency_toc_entry[0])
  207. dependency_src_path = pathlib.Path(dependency_toc_entry[1])
  208. if dependency_dest_path.parent == pathlib.PurePath('.'):
  209. # The binary is collected into top-level application directory.
  210. continue
  211. elif dependency_basename in existing_symlinks:
  212. # The symbolic link already exists.
  213. continue
  214. # Keep honoring symlink suppression patterns specified by hooks (same as in main binary dependency analysis
  215. # loop).
  216. if any(dependency_src_path.match(pattern) for pattern in symlink_suppression_patterns):
  217. logger.info(
  218. "Missing dependency handling: skipping symbolic link from %r to top-level application directory "
  219. "due to source path matching one of symlink suppression path patterns.", str(dependency_dest_path)
  220. )
  221. continue
  222. # Create the symbolic link
  223. logger.info(
  224. "Missing dependency handling: adding symbolic link from %r to top-level application directory.",
  225. str(dependency_dest_path)
  226. )
  227. output_toc.append((dependency_basename, str(dependency_dest_path), 'SYMLINK'))
  228. existing_symlinks.add(dependency_basename)
  229. return output_toc
  230. #- Low-level import analysis
  231. def get_imports(filename, search_paths=None):
  232. """
  233. Analyze the given binary file (shared library or executable), and obtain the list of shared libraries it imports
  234. (i.e., link-time dependencies).
  235. Returns set of tuples (name, fullpath). The name component is the referenced name, and on macOS, may not be just
  236. a base name. If the library's full path cannot be resolved, fullpath element is None.
  237. Additional list of search paths may be specified via `search_paths`, to be used as a fall-back when the
  238. platform-specific resolution mechanism fails to resolve a library fullpath.
  239. """
  240. # Ensure search_paths is immutable, so that it can be hashed for the purposes of caching.
  241. if search_paths is not None:
  242. search_paths = tuple(search_paths)
  243. @functools.lru_cache
  244. def _get_imports(filename, search_paths):
  245. if compat.is_win:
  246. if str(filename).lower().endswith(".manifest"):
  247. return []
  248. return _get_imports_pefile(filename, search_paths)
  249. elif compat.is_darwin:
  250. return _get_imports_macholib(filename, search_paths)
  251. else:
  252. return _get_imports_ldd(filename, search_paths)
  253. return _get_imports(filename, search_paths)
  254. def _get_imports_pefile(filename, search_paths):
  255. """
  256. Windows-specific helper for `get_imports`, which uses the `pefile` library to walk through PE header.
  257. """
  258. import pefile
  259. output = set()
  260. # By default, pefile library parses all PE information. We are only interested in the list of dependent dlls.
  261. # Performance is improved by reading only needed information. https://code.google.com/p/pefile/wiki/UsageExamples
  262. pe = pefile.PE(filename, fast_load=True)
  263. pe.parse_data_directories(
  264. directories=[
  265. pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT'],
  266. pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT'],
  267. ],
  268. forwarded_exports_only=True,
  269. import_dllnames_only=True,
  270. )
  271. # If a library has no binary dependencies, pe.DIRECTORY_ENTRY_IMPORT does not exist.
  272. for entry in getattr(pe, 'DIRECTORY_ENTRY_IMPORT', []):
  273. dll_str = entry.dll.decode('utf-8')
  274. output.add(dll_str)
  275. # We must also read the exports table to find forwarded symbols:
  276. # http://blogs.msdn.com/b/oldnewthing/archive/2006/07/19/671238.aspx
  277. exported_symbols = getattr(pe, 'DIRECTORY_ENTRY_EXPORT', None)
  278. if exported_symbols:
  279. for symbol in exported_symbols.symbols:
  280. if symbol.forwarder is not None:
  281. # symbol.forwarder is a bytes object. Convert it to a string.
  282. forwarder = symbol.forwarder.decode('utf-8')
  283. # symbol.forwarder is for example 'KERNEL32.EnterCriticalSection'
  284. dll = forwarder.split('.')[0]
  285. output.add(dll + ".dll")
  286. pe.close()
  287. # Attempt to resolve full paths to referenced DLLs. Always add the input binary's parent directory to the search
  288. # paths.
  289. search_paths = (os.path.dirname(filename), *(search_paths or []))
  290. output = {(lib, resolve_library_path(lib, search_paths)) for lib in output}
  291. return output
  292. def _get_imports_ldd(filename, search_paths):
  293. """
  294. Helper for `get_imports`, which uses `ldd` to analyze shared libraries. Used on Linux and other POSIX-like platforms
  295. (with exception of macOS).
  296. """
  297. output = set()
  298. # Output of ldd varies between platforms...
  299. if compat.is_aix:
  300. # Match libs of the form
  301. # 'archivelib.a(objectmember.so/.o)'
  302. # or
  303. # 'sharedlib.so'
  304. # Will not match the fake lib '/unix'
  305. LDD_PATTERN = re.compile(r"^\s*(((?P<libarchive>(.*\.a))(?P<objectmember>\(.*\)))|((?P<libshared>(.*\.so))))$")
  306. elif compat.is_hpux:
  307. # Match libs of the form
  308. # sharedlib.so => full-path-to-lib
  309. # e.g.
  310. # libpython2.7.so => /usr/local/lib/hpux32/libpython2.7.so
  311. LDD_PATTERN = re.compile(r"^\s+(.*)\s+=>\s+(.*)$")
  312. elif compat.is_solar:
  313. # Match libs of the form
  314. # sharedlib.so => full-path-to-lib
  315. # e.g.
  316. # libpython2.7.so.1.0 => /usr/local/lib/libpython2.7.so.1.0
  317. # Will not match the platform specific libs starting with '/platform'
  318. LDD_PATTERN = re.compile(r"^\s+(.*)\s+=>\s+(.*)$")
  319. elif compat.is_termux:
  320. # Match libs of the form
  321. # sharedlib.so => full-path-to-lib
  322. # e.g.
  323. # libpython3.13.so => /data/data/com.termux/files/usr/lib/libpython3.13.so
  324. # See: https://github.com/termux/termux-packages/blob/adb6efd/packages/ldd/ldd.in#L71-L72
  325. LDD_PATTERN = re.compile(r"^\s+(.*)\s+=>\s+(.*)$")
  326. elif compat.is_linux:
  327. # Match libs of the form
  328. # libpython3.13.so.1.0 => /home/brenainn/.pyenv/versions/3.13.0/lib/libpython3.13.so.1.0 (0x00007a9e15800000)
  329. # or
  330. # /tmp/python/install/bin/../lib/libpython3.13.so.1.0 (0x00007b9489c82000)
  331. LDD_PATTERN = re.compile(r"^\s*(?:(.*?)\s+=>\s+)?(.*?)\s+\(.*\)")
  332. else:
  333. LDD_PATTERN = re.compile(r"\s*(.*?)\s+=>\s+(.*?)\s+\(.*\)")
  334. # Resolve symlinks since GNU ldd contains a bug in processing a symlink to a binary
  335. # using $ORIGIN: https://sourceware.org/bugzilla/show_bug.cgi?id=25263
  336. p = subprocess.run(
  337. ['ldd', os.path.realpath(filename)],
  338. stdin=subprocess.DEVNULL,
  339. stderr=subprocess.PIPE,
  340. stdout=subprocess.PIPE,
  341. encoding='utf-8',
  342. )
  343. ldd_warnings = []
  344. for line in p.stderr.splitlines():
  345. if not line:
  346. continue
  347. # Python extensions (including stdlib ones) are not linked against python.so but rely on Python's symbols having
  348. # already been loaded into symbol space at runtime. musl's ldd issues a series of harmless warnings to stderr
  349. # telling us that those symbols are unfindable. These should be suppressed.
  350. elif line.startswith("Error relocating ") and line.endswith(" symbol not found"):
  351. continue
  352. # Shared libraries should have the executable bits set; however, this is not the case for shared libraries
  353. # shipped in PyPI wheels, which cause ldd to emit `ldd: warning: you do not have execution permission for ...`
  354. # warnings. Suppress these.
  355. elif line.startswith("ldd: warning: you do not have execution permission for "):
  356. continue
  357. # When `ldd` is ran against a file that is not a dynamic binary (i.e., is not a binary at all, or is a static
  358. # binary), it emits a "not a dynamic executable" warning. Suppress it.
  359. elif "not a dynamic executable" in line:
  360. continue
  361. # Propagate any other warnings it might have.
  362. ldd_warnings.append(line)
  363. if ldd_warnings:
  364. logger.warning("ldd warnings for %r:\n%s", filename, "\n".join(ldd_warnings))
  365. for line in p.stdout.splitlines():
  366. name = None # Referenced name
  367. lib = None # Resolved library path
  368. m = LDD_PATTERN.search(line)
  369. if m:
  370. if compat.is_aix:
  371. libarchive = m.group('libarchive')
  372. if libarchive:
  373. # We matched an archive lib with a request for a particular embedded shared object.
  374. # 'archivelib.a(objectmember.so/.o)'
  375. lib = libarchive
  376. name = os.path.basename(lib) + m.group('objectmember')
  377. else:
  378. # We matched a stand-alone shared library.
  379. # 'sharedlib.so'
  380. lib = m.group('libshared')
  381. name = os.path.basename(lib)
  382. elif compat.is_hpux:
  383. name, lib = m.group(1), m.group(2)
  384. else:
  385. name, lib = m.group(1), m.group(2)
  386. name = name or os.path.basename(lib)
  387. if compat.is_linux:
  388. # Skip all ld variants listed https://sourceware.org/glibc/wiki/ABIList
  389. # plus musl's ld-musl-*.so.* and Termux' ld-android.so.
  390. if re.fullmatch(r"ld(64)?(-linux|-musl)?(-.+)?\.so(\..+)?", os.path.basename(lib)):
  391. continue
  392. if name[:10] in ('linux-gate', 'linux-vdso'):
  393. # linux-gate is a fake library which does not exist and should be ignored. See also:
  394. # http://www.trilithium.com/johan/2005/08/linux-gate/
  395. continue
  396. if compat.is_cygwin:
  397. # exclude Windows system library
  398. if lib.lower().startswith('/cygdrive/c/windows/system'):
  399. continue
  400. # Reset library path if it does not exist
  401. if not os.path.exists(lib):
  402. lib = None
  403. elif line.endswith("not found"):
  404. # On glibc-based linux distributions, missing libraries are marked with name.so => not found
  405. tokens = line.split('=>')
  406. if len(tokens) != 2:
  407. continue
  408. name = tokens[0].strip()
  409. lib = None
  410. else:
  411. # TODO: should we warn about unprocessed lines?
  412. continue
  413. # Fall back to searching the supplied search paths, if any.
  414. if not lib:
  415. lib = _resolve_library_path_in_search_paths(
  416. os.path.basename(name), # Search for basename of the referenced name.
  417. search_paths,
  418. )
  419. # Normalize the resolved path, to remove any extraneous "../" elements.
  420. if lib:
  421. lib = os.path.normpath(lib)
  422. # Return referenced name as-is instead of computing a basename, to provide additional context when library
  423. # cannot be resolved.
  424. output.add((name, lib))
  425. return output
  426. def _get_imports_macholib(filename, search_paths):
  427. """
  428. macOS-specific helper for `get_imports`, which uses `macholib` to analyze library load commands in Mach-O headers.
  429. """
  430. from macholib.dyld import dyld_find
  431. from macholib.mach_o import LC_RPATH
  432. from macholib.MachO import MachO
  433. try:
  434. from macholib.dyld import _dyld_shared_cache_contains_path
  435. except ImportError:
  436. _dyld_shared_cache_contains_path = None
  437. output = set()
  438. # Parent directory of the input binary and parent directory of python executable, used to substitute @loader_path
  439. # and @executable_path. The macOS dylib loader (dyld) fully resolves the symbolic links when using @loader_path
  440. # and @executable_path references, so we need to do the same using `os.path.realpath`.
  441. bin_path = os.path.dirname(os.path.realpath(filename))
  442. python_bin = os.path.realpath(sys.executable)
  443. python_bin_path = os.path.dirname(python_bin)
  444. def _get_referenced_libs(m):
  445. # Collect referenced libraries from MachO object.
  446. referenced_libs = set()
  447. for header in m.headers:
  448. for idx, name, lib in header.walkRelocatables():
  449. referenced_libs.add(lib)
  450. return referenced_libs
  451. def _get_run_paths(m):
  452. # Find LC_RPATH commands to collect rpaths from MachO object.
  453. # macholib does not handle @rpath, so we need to handle run paths ourselves.
  454. run_paths = []
  455. for header in m.headers:
  456. for command in header.commands:
  457. # A command is a tuple like:
  458. # (<macholib.mach_o.load_command object at 0x>,
  459. # <macholib.mach_o.rpath_command object at 0x>,
  460. # '../lib\x00\x00')
  461. cmd_type = command[0].cmd
  462. if cmd_type == LC_RPATH:
  463. rpath = command[2].decode('utf-8')
  464. # Remove trailing '\x00' characters. E.g., '../lib\x00\x00'
  465. rpath = rpath.rstrip('\x00')
  466. # If run path starts with @, ensure it starts with either @loader_path or @executable_path.
  467. # We cannot process anything else.
  468. if rpath.startswith("@") and not rpath.startswith(("@executable_path", "@loader_path")):
  469. logger.warning("Unsupported rpath format %r found in binary %r - ignoring...", rpath, filename)
  470. continue
  471. run_paths.append(rpath)
  472. return run_paths
  473. @functools.lru_cache
  474. def get_run_paths_and_referenced_libs(filename):
  475. # Walk through Mach-O headers, and collect all referenced libraries and run paths.
  476. m = MachO(filename)
  477. return _get_referenced_libs(m), _get_run_paths(m)
  478. @functools.lru_cache
  479. def get_run_paths(filename):
  480. # Walk through Mach-O headers, and collect only run paths.
  481. return _get_run_paths(MachO(filename))
  482. # Collect referenced libraries and run paths from the input binary.
  483. referenced_libs, run_paths = get_run_paths_and_referenced_libs(filename)
  484. # On macOS, run paths (rpaths) are inherited from the executable that loads the given shared library (or from the
  485. # shared library that loads the given shared library). This means that shared libraries and python binary extensions
  486. # can reference other shared libraries using @rpath without having set any run paths themselves.
  487. #
  488. # In order to simulate the run path inheritance that happens in unfrozen python programs, we need to augment the
  489. # run paths from the given binary with those set by the python interpreter executable (`sys.executable`). Anaconda
  490. # python, for example, sets the run path on the python executable to `@loader_path/../lib`, which allows python
  491. # extensions to reference shared libraries in the Anaconda environment's `lib` directory via only `@rpath`
  492. # (for example, the `_ssl` extension can reference the OpenSSL library as `@rpath/libssl.3.dylib`). In another
  493. # example, python executable has its run path set to the top-level directory of its .framework bundle; in this
  494. # case the `ssl` extension references the OpenSSL library as `@rpath/Versions/3.10/lib/libssl.1.1.dylib`.
  495. run_paths += get_run_paths(python_bin)
  496. # This fallback should be fully superseded by the above recovery of run paths from python executable; but for now,
  497. # keep it around in case of unforeseen corner cases.
  498. run_paths.append(os.path.join(compat.base_prefix, 'lib'))
  499. # De-duplicate run_paths while preserving their order.
  500. run_paths = list(dict.fromkeys(run_paths))
  501. def _resolve_using_path(lib):
  502. # Absolute paths should not be resolved; we should just check whether the library exists or not. This used to
  503. # be done using macholib's dyld_find() as well (as it properly handles system libraries that are hidden on
  504. # Big Sur and later), but it turns out that even if given an absolute path, it gives precedence to search paths
  505. # from DYLD_LIBRARY_PATH. This leads to confusing errors when directory in DYLD_LIBRARY_PATH contains a file
  506. # (shared library or data file) that happens to have the same name as a library from a system framework.
  507. if os.path.isabs(lib):
  508. if _dyld_shared_cache_contains_path is not None and _dyld_shared_cache_contains_path(lib):
  509. return lib
  510. if os.path.isfile(lib):
  511. return lib
  512. return None
  513. try:
  514. return dyld_find(lib)
  515. except ValueError:
  516. return None
  517. def _resolve_using_loader_path(lib, bin_path, python_bin_path):
  518. # Strictly speaking, @loader_path should be anchored to parent directory of analyzed binary (`bin_path`), while
  519. # @executable_path should be anchored to the parent directory of the process' executable. Typically, this would
  520. # be python executable (`python_bin_path`). Unless we are analyzing a collected 3rd party executable; in that
  521. # case, `bin_path` is correct option. So we first try resolving using `bin_path`, and then fall back to
  522. # `python_bin_path`. This does not account for transitive run paths of higher-order dependencies, but there is
  523. # only so much we can do here...
  524. #
  525. # NOTE: do not use macholib's `dyld_find`, because its fallback search locations might end up resolving wrong
  526. # instance of the library! For example, if our `bin_path` and `python_bin_path` are anchored in an Anaconda
  527. # python environment and the candidate library path does not exit (because we are calling this function when
  528. # trying to resolve @rpath with multiple candidate run paths), we do not want to fall back to eponymous library
  529. # that happens to be present in the Homebrew python environment...
  530. if lib.startswith('@loader_path/'):
  531. lib = lib[len('@loader_path/'):]
  532. elif lib.startswith('@executable_path/'):
  533. lib = lib[len('@executable_path/'):]
  534. # Try resolving with binary's path first...
  535. resolved_lib = _resolve_using_path(os.path.join(bin_path, lib))
  536. if resolved_lib is not None:
  537. return resolved_lib
  538. # ... and fall-back to resolving with python executable's path
  539. return _resolve_using_path(os.path.join(python_bin_path, lib))
  540. # Try to resolve full path of the referenced libraries.
  541. for referenced_lib in referenced_libs:
  542. resolved_lib = None
  543. # If path starts with @rpath, we have to handle it ourselves.
  544. if referenced_lib.startswith('@rpath'):
  545. lib = os.path.join(*referenced_lib.split(os.sep)[1:]) # Remove the @rpath/ prefix
  546. # Try all run paths.
  547. for run_path in run_paths:
  548. # Join the path.
  549. lib_path = os.path.join(run_path, lib)
  550. if lib_path.startswith(("@executable_path", "@loader_path")):
  551. # Run path starts with @executable_path or @loader_path.
  552. lib_path = _resolve_using_loader_path(lib_path, bin_path, python_bin_path)
  553. else:
  554. # If run path was relative, anchor it to binary's location.
  555. if not os.path.isabs(lib_path):
  556. os.path.join(bin_path, lib_path)
  557. lib_path = _resolve_using_path(lib_path)
  558. if lib_path and os.path.exists(lib_path):
  559. resolved_lib = lib_path
  560. break
  561. else:
  562. if referenced_lib.startswith(("@executable_path", "@loader_path")):
  563. resolved_lib = _resolve_using_loader_path(referenced_lib, bin_path, python_bin_path)
  564. else:
  565. resolved_lib = _resolve_using_path(referenced_lib)
  566. # Fall back to searching the supplied search paths, if any.
  567. if not resolved_lib:
  568. resolved_lib = _resolve_library_path_in_search_paths(
  569. os.path.basename(referenced_lib), # Search for basename of the referenced name.
  570. search_paths,
  571. )
  572. # Normalize the resolved path, to remove any extraneous "../" elements.
  573. if resolved_lib:
  574. resolved_lib = os.path.normpath(resolved_lib)
  575. # Return referenced library name as-is instead of computing a basename. Full referenced name carries additional
  576. # information that might be useful for the caller to determine how to deal with unresolved library (e.g., ignore
  577. # unresolved libraries that are supposed to be located in system-wide directories).
  578. output.add((referenced_lib, resolved_lib))
  579. return output
  580. #- Library full path resolution
  581. def resolve_library_path(name, search_paths=None):
  582. """
  583. Given a library name, attempt to resolve full path to that library. The search for library is done via
  584. platform-specific mechanism and fall back to optionally-provided list of search paths. Returns None if library
  585. cannot be resolved. If give library name is already an absolute path, the given path is returned without any
  586. processing.
  587. """
  588. # No-op if path is already absolute.
  589. if os.path.isabs(name):
  590. return name
  591. if compat.is_unix:
  592. # Use platform-specific helper.
  593. fullpath = _resolve_library_path_unix(name)
  594. if fullpath:
  595. return fullpath
  596. # Fall back to searching the supplied search paths, if any
  597. return _resolve_library_path_in_search_paths(name, search_paths)
  598. elif compat.is_win:
  599. # Try the caller-supplied search paths, if any.
  600. fullpath = _resolve_library_path_in_search_paths(name, search_paths)
  601. if fullpath:
  602. return fullpath
  603. # Fall back to default Windows search paths, using the PATH environment variable (which should also include
  604. # the system paths, such as c:\windows and c:\windows\system32)
  605. win_search_paths = [path for path in compat.getenv('PATH', '').split(os.pathsep) if path]
  606. return _resolve_library_path_in_search_paths(name, win_search_paths)
  607. else:
  608. return ctypes.util.find_library(name)
  609. return None
  610. # Compatibility aliases for hooks from contributed hooks repository. All of these now point to the high-level
  611. # `resolve_library_path`.
  612. findLibrary = resolve_library_path
  613. findSystemLibrary = resolve_library_path
  614. def _resolve_library_path_in_search_paths(name, search_paths=None):
  615. """
  616. Low-level helper for resolving given library name to full path in given list of search paths.
  617. """
  618. for search_path in search_paths or []:
  619. fullpath = os.path.join(search_path, name)
  620. if not os.path.isfile(fullpath):
  621. continue
  622. # On Windows, ensure that architecture matches that of running python interpreter.
  623. if compat.is_win:
  624. try:
  625. dll_machine_type = winutils.get_pe_file_machine_type(fullpath)
  626. except Exception:
  627. # A search path might contain a DLL that we cannot analyze; for example, a stub file. Skip over.
  628. continue
  629. if dll_machine_type != _exe_machine_type:
  630. continue
  631. return os.path.normpath(fullpath)
  632. return None
  633. def _resolve_library_path_unix(name):
  634. """
  635. UNIX-specific helper for resolving library path.
  636. Emulates the algorithm used by dlopen. `name` must include the prefix, e.g., ``libpython2.4.so``.
  637. """
  638. assert compat.is_unix, "Current implementation for Unix only (Linux, Solaris, AIX, FreeBSD)"
  639. if name.endswith('.so') or '.so.' in name:
  640. # We have been given full library name that includes suffix. Use `_resolve_library_path_in_search_paths` to find
  641. # the exact match.
  642. lib_search_func = _resolve_library_path_in_search_paths
  643. else:
  644. # We have been given a library name without suffix. Use `_which_library` as search function, which will try to
  645. # find library with matching basename.
  646. lib_search_func = _which_library
  647. # Look in the LD_LIBRARY_PATH according to platform.
  648. if compat.is_aix:
  649. lp = compat.getenv('LIBPATH', '')
  650. elif compat.is_darwin:
  651. lp = compat.getenv('DYLD_LIBRARY_PATH', '')
  652. else:
  653. lp = compat.getenv('LD_LIBRARY_PATH', '')
  654. lib = lib_search_func(name, filter(None, lp.split(os.pathsep)))
  655. # Look in /etc/ld.so.cache
  656. # Solaris does not have /sbin/ldconfig. Just check if this file exists.
  657. if lib is None:
  658. utils.load_ldconfig_cache()
  659. lib = utils.LDCONFIG_CACHE.get(name)
  660. if lib:
  661. assert os.path.isfile(lib)
  662. # Look in the known safe paths.
  663. if lib is None:
  664. # Architecture independent locations.
  665. paths = ['/lib', '/usr/lib']
  666. # Architecture dependent locations.
  667. if compat.architecture == '32bit':
  668. paths.extend(['/lib32', '/usr/lib32'])
  669. else:
  670. paths.extend(['/lib64', '/usr/lib64'])
  671. # Machine dependent locations.
  672. if compat.machine == 'intel':
  673. if compat.architecture == '32bit':
  674. paths.extend(['/usr/lib/i386-linux-gnu'])
  675. else:
  676. paths.extend(['/usr/lib/x86_64-linux-gnu'])
  677. # On Debian/Ubuntu /usr/bin/python is linked statically with libpython. Newer Debian/Ubuntu with multiarch
  678. # support puts the libpythonX.Y.so in paths like /usr/lib/i386-linux-gnu/. Try to query the arch-specific
  679. # sub-directory, if available.
  680. arch_subdir = sysconfig.get_config_var('multiarchsubdir')
  681. if arch_subdir:
  682. arch_subdir = os.path.basename(arch_subdir)
  683. paths.append(os.path.join('/usr/lib', arch_subdir))
  684. else:
  685. logger.debug('Multiarch directory not detected.')
  686. # Termux (a Ubuntu like subsystem for Android) has an additional libraries directory.
  687. if os.path.isdir('/data/data/com.termux/files/usr/lib'):
  688. paths.append('/data/data/com.termux/files/usr/lib')
  689. if compat.is_aix:
  690. paths.append('/opt/freeware/lib')
  691. elif compat.is_hpux:
  692. if compat.architecture == '32bit':
  693. paths.append('/usr/local/lib/hpux32')
  694. else:
  695. paths.append('/usr/local/lib/hpux64')
  696. elif compat.is_freebsd or compat.is_openbsd:
  697. paths.append('/usr/local/lib')
  698. lib = lib_search_func(name, paths)
  699. return lib
  700. def _which_library(name, dirs):
  701. """
  702. Search for a shared library in a list of directories.
  703. Args:
  704. name:
  705. The library name including the `lib` prefix but excluding any `.so` suffix.
  706. dirs:
  707. An iterable of folders to search in.
  708. Returns:
  709. The path to the library if found or None otherwise.
  710. """
  711. matcher = _library_matcher(name)
  712. for path in filter(os.path.exists, dirs):
  713. for _path in os.listdir(path):
  714. if matcher(_path):
  715. return os.path.join(path, _path)
  716. def _library_matcher(name):
  717. """
  718. Create a callable that matches libraries if **name** is a valid library prefix for input library full names.
  719. """
  720. return re.compile(name + r"[0-9]*\.").match
  721. #- Python shared library search
  722. def get_python_library_path():
  723. """
  724. Find Python shared library that belongs to the current interpreter.
  725. Return full path to Python dynamic library or None when not found.
  726. PyInstaller needs to collect the Python shared library, so that bootloader can load it, import Python C API
  727. symbols, and use them to set up the embedded Python interpreter.
  728. The name of the shared library is typically fixed (`python3.X.dll` on Windows, libpython3.X.so on Unix systems,
  729. and `libpython3.X.dylib` on macOS for shared library builds and `Python.framework/Python` for framework build).
  730. Its location can usually be inferred from the Python interpreter executable, when the latter is dynamically
  731. linked against the shared library.
  732. However, some situations require extra handling due to various quirks; for example, Debian-based linux
  733. distributions statically link the Python interpreter executable against the Python library, while also providing
  734. a shared library variant for external users.
  735. """
  736. # With Windows Python builds, this is pretty straight-forward: `sys.dllhandle` provides a handle to the loaded
  737. # Python DLL, and we can resolve its path using `GetModuleFileName()` from win32 API.
  738. # This is applicable to python.org Windows builds, Anaconda on Windows, and MSYS2 Python.
  739. if compat.is_win:
  740. if hasattr(sys, 'dllhandle'):
  741. import _winapi
  742. return _winapi.GetModuleFileName(sys.dllhandle)
  743. else:
  744. raise PythonLibraryNotFoundError(
  745. "Python was built without a shared library, which is required by PyInstaller."
  746. )
  747. # On other (POSIX) platforms, the name of the Python shared library is available in the `INSTSONAME` variable
  748. # exposed by the `sysconfig` module. There is also the `LDLIBRARY` variable, which points to the unversioned .so
  749. # symbolic link for linking purposes; however, we are interested in the actual, fully-versioned soname.
  750. # This should cover all variations in the naming schemes across different platforms as well as different build
  751. # options (debug build, free-threaded build, etc.).
  752. #
  753. # However, `INSTSONAME` points to the shared library only if shared library is enabled; in static-library builds,
  754. # it points to the static library, which is of no use to us. We can check if Python was built with shared library
  755. # (i.e., the `--enable-shared` option) by checking `Py_ENABLE_SHARED` variable, which should be set to 1 in this
  756. # case (and 0 in the case of a static-library build). On macOS, builds made with `--enable-framework` have
  757. # `Py_ENABLE_SHARED` set to 0, but have `PYTHONFRAMEWORK`set to a non-empty string.
  758. #
  759. # The above description is further complicated by the fact that in some Python builds, the `python` executable is
  760. # built against static Python library, and the shared library is built separately and provided for development and
  761. # for embedders (such as PyInstaller). Presumably, this is done for performance reasons. Also, it is enabled by the
  762. # fact that on POSIX, Python extensions do not need to have the referenced Python symbols resolved at link-time;
  763. # rather, these symbols can be resolved at run-time from the running Python process (and are effectively provided
  764. # by the `python` executable). Such builds come in two variants. In the first variant, `Py_ENABLE_SHARED` is 0 and
  765. # `INSTSONAME` points to the static library; an example of such build is Anaconda Python. In the second variant,
  766. # `Py_ENABLE_SHARED` is 1 and `INSTSONAME` points to the shared library, but `python` executable is not linked
  767. # against it; examples of such build are Debian-packaged Python and `astral-sh/python-build-standalone` Python.
  768. #
  769. # Therefore, our strategy is as follows: if we determine that shared library was enabled (via `Py_ENABLE_SHARED`
  770. # on all platforms and/or via `PYTHONFRAMEWORK` on macOS), we use the name given by `INSTSONAME`. First, we try
  771. # to locate it by analyzing binary dependencies of `python` executable (regular shared-library-enabled build),
  772. # then fall back to standard search locations (second variant of static-executable-with-separate-shared-library).
  773. # If `Py_ENABLE_SHARED` is set to 0, we try to guess the library name based on version and feature flags, but we
  774. # search only `sys.base_prefix` and `lib` directory under `sys.base_prefix`; if the shared library is not found
  775. # there, we assume it is unavailable and raise an error. This attempts to accommodate Anaconda python (and corner
  776. # cases when we cannot reliably identify Anaconda python - see #9273) and prevent accidental bundling of
  777. # system-wide Python shared library in cases when user tries to use custom Python build without shared library.
  778. def _find_lib_in_libdirs(name, *libdirs):
  779. for libdir in libdirs:
  780. full_path = os.path.join(libdir, name)
  781. if not os.path.exists(full_path):
  782. continue
  783. # Resolve potential symbolic links to achieve consistent results with linker-based search; e.g., on
  784. # POSIX systems, linker resolves unversioned library names (python3.X.so) to versioned ones
  785. # (libpython3.X.so.1.0) due to former being symbolic links to the latter. See #6831.
  786. full_path = os.path.realpath(full_path)
  787. if not os.path.exists(full_path):
  788. continue
  789. return full_path
  790. return None
  791. is_shared = (
  792. # Builds made with `--enable-shared` have `Py_ENABLE_SHARED` set to 1. This is true even for Debian-packaged
  793. # Python, which has the `python` executable statically linked against the Python library.
  794. sysconfig.get_config_var("Py_ENABLE_SHARED") or
  795. # On macOS, builds made with `--enable-framework` have `Py_ENABLE_SHARED` set to 0, but have `PYTHONFRAMEWORK`
  796. # set to a non-empty string.
  797. (compat.is_darwin and sysconfig.get_config_var("PYTHONFRAMEWORK"))
  798. )
  799. if not is_shared:
  800. # Anaconda Python; this codepath used to be under `compat.is_conda` switch, but we may also be dealing with
  801. # Anaconda Python without `conda-meta` directory (see #9273). Or some other Python build where shared library
  802. # is provided but `Py_ENABLE_SHARED` is set to 0.
  803. py_major, py_minor = sys.version_info[:2]
  804. py_suffix = "t" if compat.is_nogil else "" # TODO: does Anaconda provide debug builds with "d" suffix?
  805. if compat.is_darwin:
  806. # macOS
  807. expected_name = f"libpython{py_major}.{py_minor}{py_suffix}.dylib"
  808. else:
  809. # Linux; assume any other potential POSIX builds use the same naming scheme.
  810. expected_name = f"libpython{py_major}.{py_minor}{py_suffix}.so.1.0"
  811. # Allow the library to be only in `sys.base_prefix` or the `lib` directory under it. This should prevent us from
  812. # picking up an unrelated copy of shared library that might happen to be available in standard search path, when
  813. # we should instead be raising an error due to Python having been built without a shared library. (In true
  814. # static-library builds, Python's own extension modules are usually turned into built-ins. So picking up an
  815. # unrelated Python shared library that happens to be of the same version results in run-time errors due to
  816. # missing extensions - because in the build that produced the shared library, those extensions are expected to
  817. # be external extension modules!)
  818. python_libname = _find_lib_in_libdirs(
  819. expected_name, # Full name
  820. compat.base_prefix,
  821. os.path.join(compat.base_prefix, 'lib'),
  822. )
  823. if python_libname:
  824. return python_libname
  825. # Raise PythonLibraryNotFoundError
  826. option_str = (
  827. "either the `--enable-shared` or the `--enable-framework` option"
  828. if compat.is_darwin else "the `--enable-shared` option"
  829. )
  830. raise PythonLibraryNotFoundError(
  831. "Python was built without a shared library, which is required by PyInstaller. "
  832. f"If you built Python from source, rebuild it with {option_str}."
  833. )
  834. # Use the library name from `INSTSONAME`.
  835. expected_name = sysconfig.get_config_var('INSTSONAME')
  836. # In Cygwin builds (and also MSYS2 python, although that should be handled by Windows-specific codepath...),
  837. # INSTSONAME is available, but the name has a ".dll.a" suffix; remove that trailing ".a".
  838. if (compat.is_win or compat.is_cygwin) and os.path.normcase(expected_name).endswith('.dll.a'):
  839. expected_name = expected_name[:-2]
  840. # NOTE: on macOS with .framework bundle build, INSTSONAME contains full name of the .framework library, for example
  841. # `Python.framework/Versions/3.13/Python`. Pre-compute a basename for comparisons that are using only basename.
  842. expected_basename = os.path.normcase(os.path.basename(expected_name))
  843. # First, try to find the expected name among the libraries against which the Python executable is linked. This
  844. # assumes that the Python executable was not statically linked against the library (as is the case with
  845. # Debian-packaged Python or `astral-sh/python-build-standalone` Python).
  846. imported_libraries = get_imports(compat.python_executable) # (name, fullpath) tuples
  847. for _, lib_path in imported_libraries:
  848. if lib_path is None:
  849. continue # Skip unresolved imports
  850. if os.path.normcase(os.path.basename(lib_path)) == expected_basename: # Basename comparison
  851. # Python library found. Return absolute path to it.
  852. return lib_path
  853. # As a fallback, try to find the library in several "standard" search locations...
  854. # First, search the `sys.base_prefix` and `lib` directory in `sys.base_prefix`, as these locations have the closest
  855. # ties to our current Python process. This caters to builds such as `astral-sh/python-build-standalone` Python.
  856. python_libname = _find_lib_in_libdirs(
  857. expected_name, # Full name
  858. compat.base_prefix,
  859. os.path.join(compat.base_prefix, 'lib'),
  860. )
  861. if python_libname:
  862. return python_libname
  863. # Perform search in the configured library search locations. This should be done after exhausting all other options;
  864. # it primarily caters to Debian-packaged Python, but we need to make sure that we do not collect shared library from
  865. # system-installed Python when the current interpreter is in fact some other Python build (such as, for example,
  866. # `astral-sh/python-build-standalone` Python that is handled in the preceding code block).
  867. python_libname = resolve_library_path(expected_basename) # Basename
  868. if python_libname:
  869. return python_libname
  870. # Not found. Raise a PythonLibraryNotFoundError with corresponding message.
  871. message = f"ERROR: Python shared library ({expected_name!r}) was not found!"
  872. if compat.is_linux and os.path.isfile('/etc/debian_version'):
  873. # The shared library is provided by `libpython3.x` package (i.e., no need to install full `python3-dev`).
  874. pkg_name = f"libpython3.{sys.version_info.minor}"
  875. message += (
  876. " If you are using system python on Debian/Ubuntu, you might need to install a separate package by running "
  877. f"`apt install {pkg_name}`."
  878. )
  879. raise PythonLibraryNotFoundError(message)
  880. #- Binary vs data (re)classification
  881. def classify_binary_vs_data(filename):
  882. """
  883. Classify the given file as either BINARY or a DATA, using appropriate platform-specific method. Returns 'BINARY'
  884. or 'DATA' string depending on the determined file type, or None if classification cannot be performed (non-existing
  885. file, missing tool, and other errors during classification).
  886. """
  887. # We cannot classify non-existent files.
  888. if not os.path.isfile(filename):
  889. return None
  890. # Use platform-specific implementation.
  891. return _classify_binary_vs_data(filename)
  892. if compat.is_linux:
  893. def _classify_binary_vs_data(filename):
  894. # First check for ELF signature, in order to avoid calling `objdump` on every data file, which can be costly.
  895. try:
  896. with open(filename, 'rb') as fp:
  897. sig = fp.read(4)
  898. except Exception:
  899. return None
  900. if sig != b"\x7FELF":
  901. return "DATA"
  902. # Verify the binary by checking if `objdump` recognizes the file. The preceding ELF signature check should
  903. # ensure that this is an ELF file, while this check should ensure that it is a valid ELF file. In the future,
  904. # we could try checking that the architecture matches the running platform.
  905. cmd_args = ['objdump', '-a', filename]
  906. try:
  907. p = subprocess.run(
  908. cmd_args,
  909. stdout=subprocess.PIPE,
  910. stderr=subprocess.PIPE,
  911. stdin=subprocess.DEVNULL,
  912. encoding='utf8',
  913. )
  914. except Exception:
  915. return None # Failed to run `objdump` or `objdump` unavailable.
  916. return 'BINARY' if p.returncode == 0 else 'DATA'
  917. elif compat.is_win:
  918. @functools.lru_cache()
  919. def _no_op_pefile_gc():
  920. # Disable pefile's reduntant and very slow call to gc.collect(). See #8762.
  921. import types
  922. import gc
  923. import pefile
  924. fake_gc = types.ModuleType("gc")
  925. fake_gc.__dict__.update(gc.__dict__)
  926. fake_gc.collect = lambda *_, **__: None
  927. pefile.gc = fake_gc
  928. def _classify_binary_vs_data(filename):
  929. import pefile
  930. _no_op_pefile_gc()
  931. # First check for MZ signature, which should allow us to quickly classify the majority of data files.
  932. try:
  933. with open(filename, 'rb') as fp:
  934. sig = fp.read(2)
  935. except Exception:
  936. return None
  937. if sig != b"MZ":
  938. return "DATA"
  939. # Check if the file can be opened using `pefile`.
  940. try:
  941. with pefile.PE(filename, fast_load=True) as pe: # noqa: F841
  942. pass
  943. return 'BINARY'
  944. except pefile.PEFormatError:
  945. return 'DATA'
  946. except Exception:
  947. pass
  948. return None
  949. elif compat.is_darwin:
  950. def _classify_binary_vs_data(filename):
  951. # See if the file can be opened using `macholib`.
  952. import macholib.MachO
  953. try:
  954. macho = macholib.MachO.MachO(filename) # noqa: F841
  955. return 'BINARY'
  956. except Exception:
  957. # TODO: catch only `ValueError`?
  958. pass
  959. return 'DATA'
  960. else:
  961. def _classify_binary_vs_data(filename):
  962. # Classification not implemented for the platform.
  963. return None