utils.py 17 KB

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