utils.py 17 KB

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