utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. # -*- coding: utf-8 -*-
  2. #-----------------------------------------------------------------------------
  3. # Copyright (c) 2005-2022, PyInstaller Development Team.
  4. #
  5. # Distributed under the terms of the GNU General Public License (version 2
  6. # or later) with exception for distributing the bootloader.
  7. #
  8. # The full license is in the file COPYING.txt, distributed with this software.
  9. #
  10. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  11. #-----------------------------------------------------------------------------
  12. """
  13. Utility functions related to analyzing/bundling dependencies.
  14. """
  15. import ctypes.util
  16. import io
  17. import os
  18. import re
  19. import struct
  20. import zipfile
  21. from types import CodeType
  22. from importlib.util import source_hash as importlib_source_hash
  23. import marshal
  24. from PyInstaller import compat
  25. from PyInstaller import log as logging
  26. from PyInstaller.depend import bytecode
  27. from PyInstaller.depend.dylib import include_library
  28. from PyInstaller.exceptions import ExecCommandFailed
  29. from PyInstaller.lib.modulegraph import modulegraph
  30. logger = logging.getLogger(__name__)
  31. # TODO find out if modules from base_library.zip could be somehow bundled into the .exe file.
  32. def create_py3_base_library(libzip_filename, graph):
  33. """
  34. Package basic Python modules into .zip file. The .zip file with basic modules is necessary to have on PYTHONPATH
  35. for initializing libpython3 in order to run the frozen executable with Python 3.
  36. """
  37. # Import strip_paths_in_code locally to avoid cyclic import between building.utils and depend.utils (this module);
  38. # building.utils imports depend.bindepend, which in turn imports depend.utils.
  39. from PyInstaller.building.utils import strip_paths_in_code
  40. # Construct regular expression for matching modules that should be bundled into base_library.zip. Excluded are plain
  41. # 'modules' or 'submodules.ANY_NAME'. The match has to be exact - start and end of string not substring.
  42. regex_modules = '|'.join([rf'(^{x}$)' for x in compat.PY3_BASE_MODULES])
  43. regex_submod = '|'.join([rf'(^{x}\..*$)' for x in compat.PY3_BASE_MODULES])
  44. regex_str = regex_modules + '|' + regex_submod
  45. module_filter = re.compile(regex_str)
  46. try:
  47. # Remove .zip from previous run.
  48. if os.path.exists(libzip_filename):
  49. os.remove(libzip_filename)
  50. logger.debug('Adding python files to base_library.zip')
  51. # Class zipfile.PyZipFile is not suitable for PyInstaller needs.
  52. with zipfile.ZipFile(libzip_filename, mode='w') as zf:
  53. zf.debug = 3
  54. # Sort the graph nodes by identifier to ensure repeatable builds
  55. graph_nodes = list(graph.iter_graph())
  56. graph_nodes.sort(key=lambda item: item.identifier)
  57. for mod in graph_nodes:
  58. if type(mod) in (modulegraph.SourceModule, modulegraph.Package, modulegraph.CompiledModule):
  59. # Bundling just required modules.
  60. if module_filter.match(mod.identifier):
  61. # Name inside the archive. The ZIP format specification requires forward slashes as directory
  62. # separator.
  63. if type(mod) is modulegraph.Package:
  64. new_name = mod.identifier.replace('.', '/') + '/__init__.pyc'
  65. else:
  66. new_name = mod.identifier.replace('.', '/') + '.pyc'
  67. # Write code to a file. This code is similar to py_compile.compile().
  68. with io.BytesIO() as fc:
  69. # Prepare all data in byte stream file-like object.
  70. fc.write(compat.BYTECODE_MAGIC)
  71. # Additional bitfield according to PEP 552 0b01 means hash based but don't check the
  72. # hash
  73. fc.write(struct.pack('<I', 0b01))
  74. with open(mod.filename, 'rb') as fs:
  75. source_bytes = fs.read()
  76. source_hash = importlib_source_hash(source_bytes)
  77. fc.write(source_hash)
  78. code = strip_paths_in_code(mod.code) # Strip paths
  79. marshal.dump(code, fc)
  80. # Use a ZipInfo to set timestamp for deterministic build.
  81. info = zipfile.ZipInfo(new_name)
  82. zf.writestr(info, fc.getvalue())
  83. except Exception:
  84. logger.error('base_library.zip could not be created!')
  85. raise
  86. def scan_code_for_ctypes(co):
  87. binaries = __recursively_scan_code_objects_for_ctypes(co)
  88. # If any of the libraries has been requested with anything else than the basename, drop that entry and warn the
  89. # user - PyInstaller would need to patch the compiled pyc file to make it work correctly!
  90. binaries = set(binaries)
  91. for binary in list(binaries):
  92. # 'binary' might be in some cases None. Some Python modules (e.g., PyObjC.objc._bridgesupport) might contain
  93. # code like this:
  94. # dll = ctypes.CDLL(None)
  95. if not binary:
  96. # None values have to be removed too.
  97. binaries.remove(binary)
  98. elif binary != os.path.basename(binary):
  99. # TODO make these warnings show up somewhere.
  100. try:
  101. filename = co.co_filename
  102. except Exception:
  103. filename = 'UNKNOWN'
  104. logger.warning(
  105. "Ignoring %s imported from %s - only basenames are supported with ctypes imports!", binary, filename
  106. )
  107. binaries.remove(binary)
  108. binaries = _resolveCtypesImports(binaries)
  109. return binaries
  110. def __recursively_scan_code_objects_for_ctypes(code: CodeType):
  111. """
  112. Detects ctypes dependencies, using reasonable heuristics that should cover most common ctypes usages; returns a
  113. list containing names of binaries detected as dependencies.
  114. """
  115. from PyInstaller.depend.bytecode import any_alias, search_recursively
  116. binaries = []
  117. ctypes_dll_names = {
  118. *any_alias("ctypes.CDLL"),
  119. *any_alias("ctypes.cdll.LoadLibrary"),
  120. *any_alias("ctypes.WinDLL"),
  121. *any_alias("ctypes.windll.LoadLibrary"),
  122. *any_alias("ctypes.OleDLL"),
  123. *any_alias("ctypes.oledll.LoadLibrary"),
  124. *any_alias("ctypes.PyDLL"),
  125. *any_alias("ctypes.pydll.LoadLibrary"),
  126. }
  127. find_library_names = {
  128. *any_alias("ctypes.util.find_library"),
  129. }
  130. for calls in bytecode.recursive_function_calls(code).values():
  131. for (name, args) in calls:
  132. if not len(args) == 1 or not isinstance(args[0], str):
  133. continue
  134. if name in ctypes_dll_names:
  135. # ctypes.*DLL() or ctypes.*dll.LoadLibrary()
  136. binaries.append(*args)
  137. elif name in find_library_names:
  138. # ctypes.util.find_library() needs to be handled separately, because we need to resolve the library base
  139. # name given as the argument (without prefix and suffix, e.g. 'gs') into corresponding full name (e.g.,
  140. # 'libgs.so.9').
  141. libname = args[0]
  142. if libname:
  143. libname = ctypes.util.find_library(libname)
  144. if libname:
  145. # On Windows, `find_library` may return a full pathname. See issue #1934.
  146. libname = os.path.basename(libname)
  147. binaries.append(libname)
  148. # The above handles any flavour of function/class call. We still need to capture the (albeit rarely used) case of
  149. # loading libraries with ctypes.cdll's getattr.
  150. for i in search_recursively(_scan_code_for_ctypes_getattr, code).values():
  151. binaries.extend(i)
  152. return binaries
  153. _ctypes_getattr_regex = bytecode.bytecode_regex(
  154. rb"""
  155. # Matches 'foo.bar' or 'foo.bar.whizz'.
  156. # Load the 'foo'.
  157. ((?:`EXTENDED_ARG`.)*
  158. (?:`LOAD_NAME`|`LOAD_GLOBAL`|`LOAD_FAST`).)
  159. # Load the 'bar.whizz'.
  160. ((?:(?:`EXTENDED_ARG`.)*
  161. (?:`LOAD_METHOD`|`LOAD_ATTR`).)+)
  162. """
  163. )
  164. def _scan_code_for_ctypes_getattr(code: CodeType):
  165. """
  166. Detect uses of ``ctypes.cdll.library_name``, which implies that ``library_name.dll`` should be collected.
  167. """
  168. key_names = ("cdll", "oledll", "pydll", "windll")
  169. for match in bytecode.finditer(_ctypes_getattr_regex, code.co_code):
  170. name, attrs = match.groups()
  171. name = bytecode.load(name, code)
  172. attrs = bytecode.loads(attrs, code)
  173. if attrs and attrs[-1] == "LoadLibrary":
  174. continue
  175. # Capture `from ctypes import ole; ole.dll_name`.
  176. if len(attrs) == 1:
  177. if name in key_names:
  178. yield attrs[0] + ".dll"
  179. # Capture `import ctypes; ctypes.ole.dll_name`.
  180. if len(attrs) == 2:
  181. if name == "ctypes" and attrs[0] in key_names:
  182. yield attrs[1] + ".dll"
  183. # TODO: reuse this code with modulegraph implementation.
  184. def _resolveCtypesImports(cbinaries):
  185. """
  186. Completes ctypes BINARY entries for modules with their full path.
  187. Input is a list of c-binary-names (as found by `scan_code_instruction_for_ctypes`). Output is a list of tuples
  188. ready to be appended to the ``binaries`` of a modules.
  189. This function temporarily extents PATH, LD_LIBRARY_PATH or DYLD_LIBRARY_PATH (depending on the platform) by
  190. CONF['pathex'] so shared libs will be search there, too.
  191. Example:
  192. >>> _resolveCtypesImports(['libgs.so'])
  193. [(libgs.so', ''/usr/lib/libgs.so', 'BINARY')]
  194. """
  195. from ctypes.util import find_library
  196. from PyInstaller.config import CONF
  197. if compat.is_unix:
  198. envvar = "LD_LIBRARY_PATH"
  199. elif compat.is_darwin:
  200. envvar = "DYLD_LIBRARY_PATH"
  201. else:
  202. envvar = "PATH"
  203. def _setPaths():
  204. path = os.pathsep.join(CONF['pathex'])
  205. old = compat.getenv(envvar)
  206. if old is not None:
  207. path = os.pathsep.join((path, old))
  208. compat.setenv(envvar, path)
  209. return old
  210. def _restorePaths(old):
  211. if old is None:
  212. compat.unsetenv(envvar)
  213. else:
  214. compat.setenv(envvar, old)
  215. ret = []
  216. # Try to locate the shared library on the disk. This is done by calling ctypes.util.find_library with
  217. # ImportTracker's local paths temporarily prepended to the library search paths (and restored after the call).
  218. old = _setPaths()
  219. for cbin in cbinaries:
  220. try:
  221. # There is an issue with find_library() where it can run into errors trying to locate the library. See
  222. # #5734.
  223. cpath = find_library(os.path.splitext(cbin)[0])
  224. except FileNotFoundError:
  225. # In these cases, find_library() should return None.
  226. cpath = None
  227. if compat.is_unix:
  228. # CAVEAT: find_library() is not the correct function. ctype's documentation says that it is meant to resolve
  229. # only the filename (as a *compiler* does) not the full path. Anyway, it works well enough on Windows and
  230. # Mac OS. On Linux, we need to implement more code to find out the full path.
  231. if cpath is None:
  232. cpath = cbin
  233. # "man ld.so" says that we should first search LD_LIBRARY_PATH and then the ldcache.
  234. for d in compat.getenv(envvar, '').split(os.pathsep):
  235. if os.path.isfile(os.path.join(d, cpath)):
  236. cpath = os.path.join(d, cpath)
  237. break
  238. else:
  239. if LDCONFIG_CACHE is None:
  240. load_ldconfig_cache()
  241. if cpath in LDCONFIG_CACHE:
  242. cpath = LDCONFIG_CACHE[cpath]
  243. assert os.path.isfile(cpath)
  244. else:
  245. cpath = None
  246. if cpath is None:
  247. # Skip warning message if cbin (basename of library) is ignored. This prevents messages like:
  248. # 'W: library kernel32.dll required via ctypes not found'
  249. if not include_library(cbin):
  250. continue
  251. logger.warning("Library %s required via ctypes not found", cbin)
  252. else:
  253. if not include_library(cpath):
  254. continue
  255. ret.append((cbin, cpath, "BINARY"))
  256. _restorePaths(old)
  257. return ret
  258. LDCONFIG_CACHE = None # cache the output of `/sbin/ldconfig -p`
  259. def load_ldconfig_cache():
  260. """
  261. Create a cache of the `ldconfig`-output to call it only once.
  262. It contains thousands of libraries and running it on every dylib is expensive.
  263. """
  264. global LDCONFIG_CACHE
  265. if LDCONFIG_CACHE is not None:
  266. return
  267. if compat.is_musl:
  268. # Musl deliberately doesn't use ldconfig. The ldconfig executable either doesn't exist or it's a functionless
  269. # executable which, on calling with any arguments, simply tells you that those arguments are invalid.
  270. LDCONFIG_CACHE = {}
  271. return
  272. from distutils.spawn import find_executable
  273. ldconfig = find_executable('ldconfig')
  274. if ldconfig is None:
  275. # If `ldconfig` is not found in $PATH, search for it in some fixed directories. Simply use a second call instead
  276. # of fiddling around with checks for empty env-vars and string-concat.
  277. ldconfig = find_executable('ldconfig', '/usr/sbin:/sbin:/usr/bin:/usr/sbin')
  278. # If we still could not find the 'ldconfig' command...
  279. if ldconfig is None:
  280. LDCONFIG_CACHE = {}
  281. return
  282. if compat.is_freebsd or compat.is_openbsd:
  283. # This has a quite different format than other Unixes:
  284. # [vagrant@freebsd-10 ~]$ ldconfig -r
  285. # /var/run/ld-elf.so.hints:
  286. # search directories: /lib:/usr/lib:/usr/lib/compat:...
  287. # 0:-lgeom.5 => /lib/libgeom.so.5
  288. # 184:-lpython2.7.1 => /usr/local/lib/libpython2.7.so.1
  289. ldconfig_arg = '-r'
  290. splitlines_count = 2
  291. pattern = re.compile(r'^\s+\d+:-l(\S+)(\s.*)? => (\S+)')
  292. else:
  293. # Skip first line of the library list because it is just an informative line and might contain localized
  294. # characters. Example of first line with locale set to cs_CZ.UTF-8:
  295. #$ /sbin/ldconfig -p
  296. #V keši „/etc/ld.so.cache“ nalezeno knihoven: 2799
  297. # libzvbi.so.0 (libc6,x86-64) => /lib64/libzvbi.so.0
  298. # libzvbi-chains.so.0 (libc6,x86-64) => /lib64/libzvbi-chains.so.0
  299. ldconfig_arg = '-p'
  300. splitlines_count = 1
  301. pattern = re.compile(r'^\s+(\S+)(\s.*)? => (\S+)')
  302. try:
  303. text = compat.exec_command(ldconfig, ldconfig_arg)
  304. except ExecCommandFailed:
  305. logger.warning("Failed to execute ldconfig. Disabling LD cache.")
  306. LDCONFIG_CACHE = {}
  307. return
  308. text = text.strip().splitlines()[splitlines_count:]
  309. LDCONFIG_CACHE = {}
  310. for line in text:
  311. # :fixme: this assumes library names do not contain whitespace
  312. m = pattern.match(line)
  313. # Sanitize away any abnormal lines of output.
  314. if m is None:
  315. # Warn about it then skip the rest of this iteration.
  316. if re.search("Cache generated by:", line):
  317. # See #5540. This particular line is harmless.
  318. pass
  319. else:
  320. logger.warning("Unrecognised line of output %r from ldconfig", line)
  321. continue
  322. path = m.groups()[-1]
  323. if compat.is_freebsd or compat.is_openbsd:
  324. # Insert `.so` at the end of the lib's basename. soname and filename may have (different) trailing versions.
  325. # We assume the `.so` in the filename to mark the end of the lib's basename.
  326. bname = os.path.basename(path).split('.so', 1)[0]
  327. name = 'lib' + m.group(1)
  328. assert name.startswith(bname)
  329. name = bname + '.so' + name[len(bname):]
  330. else:
  331. name = m.group(1)
  332. # ldconfig may know about several versions of the same lib, e.g., different arch, different libc, etc.
  333. # Use the first entry.
  334. if name not in LDCONFIG_CACHE:
  335. LDCONFIG_CACHE[name] = path
  336. def get_path_to_egg(path):
  337. """
  338. Return the path to the python egg file, if the given path points to a file inside (or directly to) an egg.
  339. Return `None` otherwise.
  340. """
  341. # This assumes that eggs are not nested.
  342. # TODO: add support for unpacked eggs and for new .whl packages.
  343. lastpath = None # marker to stop recursion
  344. while path and path != lastpath:
  345. if os.path.splitext(path)[1].lower() == ".egg":
  346. if os.path.isfile(path) or os.path.isdir(path):
  347. return path
  348. lastpath = path
  349. path = os.path.dirname(path)
  350. return None
  351. def is_path_to_egg(path):
  352. """
  353. Check if the given path points to a file inside (or directly to) a python egg file.
  354. """
  355. return get_path_to_egg(path) is not None