build_main.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-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. Build packages using spec files.
  13. NOTE: All global variables, classes and imported modules create API for .spec files.
  14. """
  15. import glob
  16. import os
  17. import pathlib
  18. import pprint
  19. import shutil
  20. import enum
  21. import re
  22. import sys
  23. from PyInstaller import DEFAULT_DISTPATH, DEFAULT_WORKPATH, HOMEPATH, compat
  24. from PyInstaller import log as logging
  25. from PyInstaller.building.api import COLLECT, EXE, MERGE, PYZ
  26. from PyInstaller.building.datastruct import (
  27. TOC, Target, Tree, _check_guts_eq, normalize_toc, normalize_pyz_toc, toc_process_symbolic_links
  28. )
  29. from PyInstaller.building.osx import BUNDLE
  30. from PyInstaller.building.splash import Splash
  31. from PyInstaller.building.utils import (
  32. _check_guts_toc, _check_guts_toc_mtime, _should_include_system_binary, format_binaries_and_datas, compile_pymodule,
  33. destination_name_for_extension, postprocess_binaries_toc_pywin32, postprocess_binaries_toc_pywin32_anaconda,
  34. create_base_library_zip
  35. )
  36. from PyInstaller.compat import is_win, is_conda, is_darwin, is_linux
  37. from PyInstaller.depend import bindepend
  38. from PyInstaller.depend.analysis import initialize_modgraph, HOOK_PRIORITY_USER_HOOKS
  39. from PyInstaller.depend.utils import scan_code_for_ctypes
  40. from PyInstaller import isolated
  41. from PyInstaller.utils.misc import absnormpath, get_path_to_toplevel_modules, mtime
  42. from PyInstaller.utils.hooks import get_package_paths
  43. from PyInstaller.utils.hooks.gi import compile_glib_schema_files
  44. if is_darwin:
  45. from PyInstaller.utils import osx as osxutils
  46. logger = logging.getLogger(__name__)
  47. STRINGTYPE = type('')
  48. TUPLETYPE = type((None,))
  49. rthooks = {}
  50. # Place where the loader modules and initialization scripts live.
  51. _init_code_path = os.path.join(HOMEPATH, 'PyInstaller', 'loader')
  52. IMPORT_TYPES = [
  53. 'top-level', 'conditional', 'delayed', 'delayed, conditional', 'optional', 'conditional, optional',
  54. 'delayed, optional', 'delayed, conditional, optional'
  55. ]
  56. WARNFILE_HEADER = """\
  57. This file lists modules PyInstaller was not able to find. This does not
  58. necessarily mean these modules are required for running your program. Both
  59. Python's standard library and 3rd-party Python packages often conditionally
  60. import optional modules, some of which may be available only on certain
  61. platforms.
  62. Types of import:
  63. * top-level: imported at the top-level - look at these first
  64. * conditional: imported within an if-statement
  65. * delayed: imported within a function
  66. * optional: imported within a try-except-statement
  67. IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
  68. tracking down the missing module yourself. Thanks!
  69. """
  70. @isolated.decorate
  71. def discover_hook_directories():
  72. """
  73. Discover hook directories via pyinstaller40 entry points. Perform the discovery in an isolated subprocess
  74. to avoid importing the package(s) in the main process.
  75. :return: list of discovered hook directories.
  76. """
  77. from traceback import format_exception_only
  78. from PyInstaller.log import logger
  79. from PyInstaller.compat import importlib_metadata
  80. from PyInstaller.depend.analysis import HOOK_PRIORITY_CONTRIBUTED_HOOKS, HOOK_PRIORITY_UPSTREAM_HOOKS
  81. # The “selectable” entry points (via group and name keyword args) were introduced in importlib_metadata 4.6 and
  82. # Python 3.10. The compat module ensures we are using a compatible version.
  83. entry_points = importlib_metadata.entry_points(group='pyinstaller40', name='hook-dirs')
  84. # Ensure that pyinstaller_hooks_contrib comes last so that hooks from packages providing their own take priority.
  85. # In pyinstaller-hooks-contrib >= 2024.8, the entry-point module is `_pyinstaller_hooks_contrib`; in earlier
  86. # versions, it was `_pyinstaller_hooks_contrib.hooks`.
  87. entry_points = sorted(entry_points, key=lambda x: x.module.startswith("_pyinstaller_hooks_contrib"))
  88. hook_directories = []
  89. for entry_point in entry_points:
  90. # Query hook directory location(s) from entry point
  91. try:
  92. hook_directory_entries = entry_point.load()()
  93. except Exception as e:
  94. msg = "".join(format_exception_only(type(e), e)).strip()
  95. logger.warning("discover_hook_directories: Failed to process hook entry point '%s': %s", entry_point, msg)
  96. continue
  97. # Determine location-based priority: upstream hooks vs. hooks from contributed hooks package.
  98. location_priority = (
  99. HOOK_PRIORITY_CONTRIBUTED_HOOKS
  100. if entry_point.module.startswith("_pyinstaller_hooks_contrib") else HOOK_PRIORITY_UPSTREAM_HOOKS
  101. )
  102. # Append entries
  103. hook_directories.extend([(hook_directory_entry, location_priority)
  104. for hook_directory_entry in hook_directory_entries])
  105. logger.debug("discover_hook_directories: Hook directories: %s", hook_directories)
  106. return hook_directories
  107. def find_binary_dependencies(binaries, import_packages, symlink_suppression_patterns):
  108. """
  109. Find dynamic dependencies (linked shared libraries) for the provided list of binaries.
  110. On Windows, this function performs additional pre-processing in an isolated environment in an attempt to handle
  111. dynamic library search path modifications made by packages during their import. The packages from the given list
  112. of collected packages are imported one by one, while keeping track of modifications made by `os.add_dll_directory`
  113. calls and additions to the `PATH` environment variable. The recorded additional search paths are then passed to
  114. the binary dependency analysis step.
  115. binaries
  116. List of binaries to scan for dynamic dependencies.
  117. import_packages
  118. List of packages to import prior to scanning binaries.
  119. symlink_suppression_patterns
  120. Set of paths and/or path patterns for which binary dependency analysis should not create symbolic links
  121. to the top-level application directory (when the discovered shared library's parent directory structure
  122. is preserved). When binary dependency analysis discovers a shared library, it matches its *source path*
  123. against all symlink suppression patterns (using `pathlib.PurePath.match`) to determine whether to create
  124. a symbolic link to top-level application directory or not.
  125. :return: expanded list of binaries and then dependencies.
  126. """
  127. # Extra library search paths (used on Windows to resolve DLL paths).
  128. extra_libdirs = []
  129. if compat.is_win:
  130. # Always search `sys.base_prefix`, and search it first. This ensures that we resolve the correct version of
  131. # `python3X.dll` and `python3.dll` (a PEP-0384 stable ABI stub that forwards symbols to the fully versioned
  132. # `python3X.dll`), regardless of other python installations that might be present in the PATH.
  133. extra_libdirs.append(compat.base_prefix)
  134. # When using python built from source, `sys.base_prefix` does not point to the directory that contains python
  135. # executable, `python3X.dll`, and `python3.dll`. To accommodate such case, also add the directory in which
  136. # python executable is located to the extra search paths. On the off-chance that this is a combination of venv
  137. # and python built from source, prefer `sys._base_executable` over `sys.executable`.
  138. extra_libdirs.append(os.path.dirname(getattr(sys, '_base_executable', sys.executable)))
  139. # If `pywin32` is installed, resolve the path to the `pywin32_system32` directory. Most `pywin32` extensions
  140. # reference the `pywintypes3X.dll` in there. Based on resolved `pywin32_system32` directory, also add other
  141. # `pywin32` directory, in case extensions in different directories reference each other (the ones in the same
  142. # directory should already be resolvable due to binary dependency analysis passing the analyzed binary's
  143. # location to the `get_imports` function). This allows us to avoid searching all paths in `sys.path`, which
  144. # may lead to other corner-case issues (e.g., #5560).
  145. pywin32_system32_dir = None
  146. try:
  147. # Look up the directory by treating it as a namespace package.
  148. _, pywin32_system32_dir = get_package_paths('pywin32_system32')
  149. except Exception:
  150. pass
  151. if pywin32_system32_dir:
  152. pywin32_base_dir = os.path.dirname(pywin32_system32_dir)
  153. extra_libdirs += [
  154. pywin32_system32_dir, # .../pywin32_system32
  155. # based on pywin32.pth
  156. os.path.join(pywin32_base_dir, 'win32'), # .../win32
  157. os.path.join(pywin32_base_dir, 'win32', 'lib'), # .../win32/lib
  158. os.path.join(pywin32_base_dir, 'Pythonwin'), # .../Pythonwin
  159. ]
  160. # On Windows, packages' initialization code might register additional DLL search paths, either by modifying the
  161. # `PATH` environment variable, or by calling `os.add_dll_directory`. Therefore, we import all collected packages,
  162. # and track changes made to the environment.
  163. if compat.is_win:
  164. # Helper functions to be executed in isolated environment.
  165. def setup(suppressed_imports):
  166. """
  167. Prepare environment for change tracking
  168. """
  169. import os
  170. import sys
  171. os._added_dll_directories = []
  172. os._original_path_env = os.environ.get('PATH', '')
  173. _original_add_dll_directory = os.add_dll_directory
  174. def _pyi_add_dll_directory(path):
  175. os._added_dll_directories.append(path)
  176. return _original_add_dll_directory(path)
  177. os.add_dll_directory = _pyi_add_dll_directory
  178. # Suppress import of specified packages
  179. for name in suppressed_imports:
  180. sys.modules[name] = None
  181. def import_library(package):
  182. """
  183. Import collected package to set up environment.
  184. """
  185. try:
  186. __import__(package)
  187. except Exception:
  188. pass
  189. def process_search_paths():
  190. """
  191. Obtain lists of added search paths.
  192. """
  193. import os
  194. # `os.add_dll_directory` might be called with a `pathlib.Path`, which cannot be marhsalled out of the helper
  195. # process. So explicitly convert all entries to strings.
  196. dll_directories = [str(path) for path in os._added_dll_directories]
  197. orig_path = set(os._original_path_env.split(os.pathsep))
  198. modified_path = os.environ.get('PATH', '').split(os.pathsep)
  199. path_additions = [path for path in modified_path if path and path not in orig_path]
  200. return dll_directories, path_additions
  201. # Pre-process the list of packages to import.
  202. # Check for Qt bindings packages, and put them at the front of the packages list. This ensures that they are
  203. # always imported first, which should prevent packages that support multiple bindings (`qtypy`, `pyqtgraph`,
  204. # `matplotlib`, etc.) from trying to auto-select bindings.
  205. _QT_BINDINGS = ('PySide2', 'PyQt5', 'PySide6', 'PyQt6')
  206. qt_packages = []
  207. other_packages = []
  208. for package in import_packages:
  209. if package.startswith(_QT_BINDINGS):
  210. qt_packages.append(package)
  211. else:
  212. other_packages.append(package)
  213. import_packages = qt_packages + other_packages
  214. # Just in case, explicitly suppress imports of Qt bindings that we are *not* collecting - if multiple bindings
  215. # are available and some were excluded from our analysis, a package imported here might still try to import an
  216. # excluded bindings package (and succeed at doing so).
  217. suppressed_imports = [package for package in _QT_BINDINGS if package not in qt_packages]
  218. # If we suppressed PySide2 or PySide6, we must also suppress their corresponding shiboken package
  219. if "PySide2" in suppressed_imports:
  220. suppressed_imports += ["shiboken2"]
  221. if "PySide6" in suppressed_imports:
  222. suppressed_imports += ["shiboken6"]
  223. # Suppress import of `pyqtgraph.canvas`, which is known to crash python interpreter. See #7452 and #8322, as
  224. # well as https://github.com/pyqtgraph/pyqtgraph/issues/2838.
  225. suppressed_imports += ['pyqtgraph.canvas']
  226. # PySimpleGUI 5.x displays a "first-run" dialog when imported for the first time, which blocks the loop below.
  227. # This is a problem for building on CI, where the dialog cannot be closed, and where PySimpleGUI runs "for the
  228. # first time" every time. See #8396.
  229. suppressed_imports += ['PySimpleGUI']
  230. # Processing in isolated environment.
  231. with isolated.Python() as child:
  232. child.call(setup, suppressed_imports)
  233. for package in import_packages:
  234. try:
  235. child.call(import_library, package)
  236. except isolated.SubprocessDiedError as e:
  237. # Re-raise as `isolated.SubprocessDiedError` again, to trigger error-handling codepath in
  238. # `isolated.Python.__exit__()`.
  239. raise isolated.SubprocessDiedError(
  240. f"Isolated subprocess crashed while importing package {package!r}! "
  241. f"Package import list: {import_packages!r}"
  242. ) from e
  243. added_dll_directories, added_path_directories = child.call(process_search_paths)
  244. # Process extra search paths...
  245. logger.info("Extra DLL search directories (AddDllDirectory): %r", added_dll_directories)
  246. extra_libdirs += added_dll_directories
  247. logger.info("Extra DLL search directories (PATH): %r", added_path_directories)
  248. extra_libdirs += added_path_directories
  249. # Deduplicate search paths
  250. # NOTE: `list(set(extra_libdirs))` does not preserve the order of search paths (which matters here), so we need to
  251. # de-duplicate using `list(dict.fromkeys(extra_libdirs).keys())` instead.
  252. extra_libdirs = list(dict.fromkeys(extra_libdirs).keys())
  253. # Search for dependencies of the given binaries
  254. return bindepend.binary_dependency_analysis(
  255. binaries,
  256. search_paths=extra_libdirs,
  257. symlink_suppression_patterns=symlink_suppression_patterns,
  258. )
  259. class _ModuleCollectionMode(enum.IntFlag):
  260. """
  261. Module collection mode flags.
  262. """
  263. PYZ = enum.auto() # Collect byte-compiled .pyc into PYZ archive
  264. PYC = enum.auto() # Collect byte-compiled .pyc as external data file
  265. PY = enum.auto() # Collect source .py file as external data file
  266. _MODULE_COLLECTION_MODES = {
  267. "pyz": _ModuleCollectionMode.PYZ,
  268. "pyc": _ModuleCollectionMode.PYC,
  269. "py": _ModuleCollectionMode.PY,
  270. "pyz+py": _ModuleCollectionMode.PYZ | _ModuleCollectionMode.PY,
  271. "py+pyz": _ModuleCollectionMode.PYZ | _ModuleCollectionMode.PY,
  272. }
  273. def _get_module_collection_mode(mode_dict, name, noarchive=False):
  274. """
  275. Determine the module/package collection mode for the given module name, based on the provided collection
  276. mode settings dictionary.
  277. """
  278. # Default mode: collect into PYZ, unless noarchive is enabled. In that case, collect as pyc.
  279. mode_flags = _ModuleCollectionMode.PYC if noarchive else _ModuleCollectionMode.PYZ
  280. # If we have no collection mode settings, end here and now.
  281. if not mode_dict:
  282. return mode_flags
  283. # Search the parent modules/packages in top-down fashion, and take the last given setting. This ensures that
  284. # a setting given for the top-level package is recursively propagated to all its subpackages and submodules,
  285. # but also allows individual sub-modules to override the setting again.
  286. mode = 'pyz'
  287. name_parts = name.split('.')
  288. for i in range(len(name_parts)):
  289. modlevel = ".".join(name_parts[:i + 1])
  290. modlevel_mode = mode_dict.get(modlevel, None)
  291. if modlevel_mode is not None:
  292. mode = modlevel_mode
  293. # Convert mode string to _ModuleCollectionMode flags
  294. try:
  295. mode_flags = _MODULE_COLLECTION_MODES[mode]
  296. except KeyError:
  297. raise ValueError(f"Unknown module collection mode for {name!r}: {mode!r}!")
  298. # noarchive flag being set means that we need to change _ModuleCollectionMode.PYZ into _ModuleCollectionMode.PYC
  299. if noarchive and _ModuleCollectionMode.PYZ in mode_flags:
  300. mode_flags ^= _ModuleCollectionMode.PYZ
  301. mode_flags |= _ModuleCollectionMode.PYC
  302. return mode_flags
  303. class Analysis(Target):
  304. """
  305. Class that performs analysis of the user's main Python scripts.
  306. An Analysis contains multiple TOC (Table of Contents) lists, accessed as attributes of the analysis object.
  307. scripts
  308. The scripts you gave Analysis as input, with any runtime hook scripts prepended.
  309. pure
  310. The pure Python modules.
  311. binaries
  312. The extension modules and their dependencies.
  313. datas
  314. Data files collected from packages.
  315. zipfiles
  316. Deprecated - always empty.
  317. zipped_data
  318. Deprecated - always empty.
  319. """
  320. _old_scripts = {
  321. absnormpath(os.path.join(HOMEPATH, "support", "_mountzlib.py")),
  322. absnormpath(os.path.join(HOMEPATH, "support", "useUnicode.py")),
  323. absnormpath(os.path.join(HOMEPATH, "support", "useTK.py")),
  324. absnormpath(os.path.join(HOMEPATH, "support", "unpackTK.py")),
  325. absnormpath(os.path.join(HOMEPATH, "support", "removeTK.py"))
  326. }
  327. def __init__(
  328. self,
  329. scripts,
  330. pathex=None,
  331. binaries=None,
  332. datas=None,
  333. hiddenimports=None,
  334. hookspath=None,
  335. hooksconfig=None,
  336. excludes=None,
  337. runtime_hooks=None,
  338. cipher=None,
  339. win_no_prefer_redirects=False,
  340. win_private_assemblies=False,
  341. noarchive=False,
  342. module_collection_mode=None,
  343. optimize=-1,
  344. **_kwargs,
  345. ):
  346. """
  347. scripts
  348. A list of scripts specified as file names.
  349. pathex
  350. An optional list of paths to be searched before sys.path.
  351. binaries
  352. An optional list of additional binaries (dlls, etc.) to include.
  353. datas
  354. An optional list of additional data files to include.
  355. hiddenimport
  356. An optional list of additional (hidden) modules to include.
  357. hookspath
  358. An optional list of additional paths to search for hooks. (hook-modules).
  359. hooksconfig
  360. An optional dict of config settings for hooks. (hook-modules).
  361. excludes
  362. An optional list of module or package names (their Python names, not path names) that will be
  363. ignored (as though they were not found).
  364. runtime_hooks
  365. An optional list of scripts to use as users' runtime hooks. Specified as file names.
  366. cipher
  367. Deprecated. Raises an error if not None.
  368. win_no_prefer_redirects
  369. Deprecated. Raises an error if not False.
  370. win_private_assemblies
  371. Deprecated. Raises an error if not False.
  372. noarchive
  373. If True, do not place source files in a archive, but keep them as individual files.
  374. module_collection_mode
  375. An optional dict of package/module names and collection mode strings. Valid collection mode strings:
  376. 'pyz' (default), 'pyc', 'py', 'pyz+py' (or 'py+pyz')
  377. optimize
  378. Optimization level for collected bytecode. If not specified or set to -1, it is set to the value of
  379. `sys.flags.optimize` of the running build process.
  380. """
  381. if cipher is not None:
  382. from PyInstaller.exceptions import RemovedCipherFeatureError
  383. raise RemovedCipherFeatureError(
  384. "Please remove the 'cipher' arguments to PYZ() and Analysis() in your spec file."
  385. )
  386. if win_no_prefer_redirects:
  387. from PyInstaller.exceptions import RemovedWinSideBySideSupportError
  388. raise RemovedWinSideBySideSupportError(
  389. "Please remove the 'win_no_prefer_redirects' argument to Analysis() in your spec file."
  390. )
  391. if win_private_assemblies:
  392. from PyInstaller.exceptions import RemovedWinSideBySideSupportError
  393. raise RemovedWinSideBySideSupportError(
  394. "Please remove the 'win_private_assemblies' argument to Analysis() in your spec file."
  395. )
  396. super().__init__()
  397. from PyInstaller.config import CONF
  398. self.inputs = []
  399. spec_dir = os.path.dirname(CONF['spec'])
  400. for script in scripts:
  401. # If path is relative, it is relative to the location of .spec file.
  402. if not os.path.isabs(script):
  403. script = os.path.join(spec_dir, script)
  404. if absnormpath(script) in self._old_scripts:
  405. logger.warning('Ignoring obsolete auto-added script %s', script)
  406. continue
  407. # Normalize script path.
  408. script = os.path.normpath(script)
  409. if not os.path.exists(script):
  410. raise SystemExit("ERROR: script '%s' not found" % script)
  411. self.inputs.append(script)
  412. # Django hook requires this variable to find the script manage.py.
  413. CONF['main_script'] = self.inputs[0]
  414. site_packages_pathex = []
  415. for path in (pathex or []):
  416. if pathlib.Path(path).name == "site-packages":
  417. site_packages_pathex.append(str(path))
  418. if site_packages_pathex:
  419. logger.log(
  420. logging.DEPRECATION, "Foreign Python environment's site-packages paths added to --paths/pathex:\n%s\n"
  421. "This is ALWAYS the wrong thing to do. If your environment's site-packages is not in PyInstaller's "
  422. "module search path then you are running PyInstaller from a different environment to the one your "
  423. "packages are in. Run print(sys.prefix) without PyInstaller to get the environment you should be using "
  424. "then install and run PyInstaller from that environment instead of this one. This warning will become "
  425. "an error in PyInstaller 7.0.", pprint.pformat(site_packages_pathex)
  426. )
  427. self.pathex = self._extend_pathex(pathex, self.inputs)
  428. # Set global config variable 'pathex' to make it available for PyInstaller.utils.hooks and import hooks. Path
  429. # extensions for module search.
  430. CONF['pathex'] = self.pathex
  431. # Extend sys.path so PyInstaller could find all necessary modules.
  432. sys.path.extend(self.pathex)
  433. logger.info('Module search paths (PYTHONPATH):\n' + pprint.pformat(sys.path))
  434. self.hiddenimports = hiddenimports or []
  435. # Include hidden imports passed via CONF['hiddenimports']; these might be populated if user has a wrapper script
  436. # that calls `build_main.main()` with custom `pyi_config` dictionary that contains `hiddenimports`.
  437. self.hiddenimports.extend(CONF.get('hiddenimports', []))
  438. for modnm in self.hiddenimports:
  439. if re.search(r"[\\/]", modnm):
  440. raise SystemExit(
  441. f"ERROR: Invalid hiddenimport '{modnm}'. Hidden imports should be importable module names – not "
  442. "file paths. i.e. use --hiddenimport=foo.bar instead of --hiddenimport=.../site-packages/foo/bar.py"
  443. )
  444. self.hookspath = []
  445. # Prepend directories in `hookspath` (`--additional-hooks-dir`) to take precedence over those from the entry
  446. # points. Expand starting tilde into user's home directory, as a work-around for tilde not being expanded by
  447. # shell when using `--additional-hooks-dir=~/path/abc` instead of `--additional-hooks-dir ~/path/abc` (or when
  448. # the path argument is quoted).
  449. if hookspath:
  450. self.hookspath.extend([(os.path.expanduser(path), HOOK_PRIORITY_USER_HOOKS) for path in hookspath])
  451. # Add hook directories from PyInstaller entry points.
  452. self.hookspath += discover_hook_directories()
  453. self.hooksconfig = {}
  454. if hooksconfig:
  455. self.hooksconfig.update(hooksconfig)
  456. # Custom runtime hook files that should be included and started before any existing PyInstaller runtime hooks.
  457. self.custom_runtime_hooks = runtime_hooks or []
  458. self._input_binaries = []
  459. self._input_datas = []
  460. self.excludes = excludes or []
  461. self.scripts = []
  462. self.pure = []
  463. self.binaries = []
  464. self.zipfiles = []
  465. self.zipped_data = []
  466. self.datas = []
  467. self.dependencies = []
  468. self._python_version = sys.version
  469. self.noarchive = noarchive
  470. self.module_collection_mode = module_collection_mode or {}
  471. self.optimize = sys.flags.optimize if optimize in {-1, None} else optimize
  472. self._modules_outside_pyz = []
  473. # Validate the optimization level to avoid errors later on...
  474. if self.optimize not in {0, 1, 2}:
  475. raise ValueError(f"Unsupported bytecode optimization level: {self.optimize!r}")
  476. # Expand the `binaries` and `datas` lists specified in the .spec file, and ensure that the lists are normalized
  477. # and sorted before guts comparison.
  478. #
  479. # While we use these lists to initialize `Analysis.binaries` and `Analysis.datas`, at this point, we need to
  480. # store them in separate variables, which undergo *full* guts comparison (`_check_guts_toc`) as opposed to
  481. # just mtime-based comparison (`_check_guts_toc_mtime`). Changes to these initial list *must* trigger a rebuild
  482. # (and due to the way things work, a re-analysis), otherwise user might end up with a cached build that fails to
  483. # reflect the changes.
  484. if binaries:
  485. logger.info("Appending 'binaries' from .spec")
  486. self._input_binaries = [(dest_name, src_name, 'BINARY')
  487. for dest_name, src_name in format_binaries_and_datas(binaries, workingdir=spec_dir)]
  488. self._input_binaries = sorted(normalize_toc(self._input_binaries))
  489. if datas:
  490. logger.info("Appending 'datas' from .spec")
  491. self._input_datas = [(dest_name, src_name, 'DATA')
  492. for dest_name, src_name in format_binaries_and_datas(datas, workingdir=spec_dir)]
  493. self._input_datas = sorted(normalize_toc(self._input_datas))
  494. self.__postinit__()
  495. _GUTS = ( # input parameters
  496. ('inputs', _check_guts_eq), # parameter `scripts`
  497. ('pathex', _check_guts_eq),
  498. ('hiddenimports', _check_guts_eq),
  499. ('hookspath', _check_guts_eq),
  500. ('hooksconfig', _check_guts_eq),
  501. ('excludes', _check_guts_eq),
  502. ('custom_runtime_hooks', _check_guts_eq),
  503. ('noarchive', _check_guts_eq),
  504. ('module_collection_mode', _check_guts_eq),
  505. ('optimize', _check_guts_eq),
  506. ('_input_binaries', _check_guts_toc),
  507. ('_input_datas', _check_guts_toc),
  508. # calculated/analysed values
  509. ('_python_version', _check_guts_eq),
  510. ('scripts', _check_guts_toc_mtime),
  511. ('pure', _check_guts_toc_mtime),
  512. ('binaries', _check_guts_toc_mtime),
  513. ('zipfiles', _check_guts_toc_mtime),
  514. ('zipped_data', None), # TODO check this, too
  515. ('datas', _check_guts_toc_mtime),
  516. # TODO: Need to add "dependencies"?
  517. ('_modules_outside_pyz', _check_guts_toc_mtime),
  518. )
  519. def _extend_pathex(self, spec_pathex, scripts):
  520. """
  521. Normalize additional paths where PyInstaller will look for modules and add paths with scripts to the list of
  522. paths.
  523. :param spec_pathex: Additional paths defined defined in .spec file.
  524. :param scripts: Scripts to create executable from.
  525. :return: list of updated paths
  526. """
  527. # Based on main supplied script - add top-level modules directory to PYTHONPATH.
  528. # Sometimes the main app script is not top-level module but submodule like 'mymodule.mainscript.py'.
  529. # In that case PyInstaller will not be able find modules in the directory containing 'mymodule'.
  530. # Add this directory to PYTHONPATH so PyInstaller could find it.
  531. pathex = []
  532. # Add scripts paths first.
  533. for script in scripts:
  534. logger.debug('script: %s' % script)
  535. script_toplevel_dir = get_path_to_toplevel_modules(script)
  536. if script_toplevel_dir:
  537. pathex.append(script_toplevel_dir)
  538. # Append paths from .spec.
  539. if spec_pathex is not None:
  540. pathex.extend(spec_pathex)
  541. # Normalize paths in pathex and make them absolute.
  542. return list(dict.fromkeys(absnormpath(p) for p in pathex))
  543. def _check_guts(self, data, last_build):
  544. if Target._check_guts(self, data, last_build):
  545. return True
  546. for filename in self.inputs:
  547. if mtime(filename) > last_build:
  548. logger.info("Building because %s changed", filename)
  549. return True
  550. # Now we know that none of the input parameters and none of the input files has changed. So take the values
  551. # that were calculated / analyzed in the last run and store them in `self`. These TOC lists should already
  552. # be normalized.
  553. self.scripts = data['scripts']
  554. self.pure = data['pure']
  555. self.binaries = data['binaries']
  556. self.zipfiles = data['zipfiles']
  557. self.zipped_data = data['zipped_data']
  558. self.datas = data['datas']
  559. return False
  560. def assemble(self):
  561. """
  562. This method is the MAIN method for finding all necessary files to be bundled.
  563. """
  564. from PyInstaller.config import CONF
  565. # Search for python shared library, which we need to collect into frozen application. Do this as the very
  566. # first step, to minimize the amount of processing when the shared library cannot be found.
  567. logger.info('Looking for Python shared library...')
  568. python_lib = bindepend.get_python_library_path() # Raises PythonLibraryNotFoundError
  569. logger.info('Using Python shared library: %s', python_lib)
  570. logger.info("Running Analysis %s", self.tocbasename)
  571. logger.info("Target bytecode optimization level: %d", self.optimize)
  572. for m in self.excludes:
  573. logger.debug("Excluding module '%s'" % m)
  574. self.graph = initialize_modgraph(excludes=self.excludes, user_hook_dirs=self.hookspath)
  575. # Initialize `binaries` and `datas` with `_input_binaries` and `_input_datas`. Make sure to copy the lists
  576. # to prevent modifications of original lists, which we need to store in original form for guts comparison.
  577. self.datas = [entry for entry in self._input_datas]
  578. self.binaries = [entry for entry in self._input_binaries]
  579. # Expand sys.path of module graph. The attribute is the set of paths to use for imports: sys.path, plus our
  580. # loader, plus other paths from e.g. --path option).
  581. self.graph.path = self.pathex + self.graph.path
  582. # Scan for legacy namespace packages.
  583. self.graph.scan_legacy_namespace_packages()
  584. # Add python shared library to `binaries`.
  585. if is_darwin and osxutils.is_framework_bundle_lib(python_lib):
  586. # If python library is located in macOS .framework bundle, collect the bundle, and create symbolic link to
  587. # top-level directory.
  588. src_path = pathlib.PurePath(python_lib)
  589. dst_path = pathlib.PurePath(src_path.relative_to(src_path.parent.parent.parent.parent))
  590. self.binaries.append((str(dst_path), str(src_path), 'BINARY'))
  591. self.binaries.append((os.path.basename(python_lib), str(dst_path), 'SYMLINK'))
  592. else:
  593. self.binaries.append((os.path.basename(python_lib), python_lib, 'BINARY'))
  594. # -- Module graph. --
  595. #
  596. # Construct the module graph of import relationships between modules required by this user's application. For
  597. # each entry point (top-level user-defined Python script), all imports originating from this entry point are
  598. # recursively parsed into a subgraph of the module graph. This subgraph is then connected to this graph's root
  599. # node, ensuring imported module nodes will be reachable from the root node -- which is is (arbitrarily) chosen
  600. # to be the first entry point's node.
  601. # List of graph nodes corresponding to program scripts.
  602. program_scripts = []
  603. # Assume that if the script does not exist, Modulegraph will raise error. Save the graph nodes of each in
  604. # sequence.
  605. for script in self.inputs:
  606. logger.info("Analyzing %s", script)
  607. program_scripts.append(self.graph.add_script(script))
  608. # Analyze the script's hidden imports (named on the command line)
  609. self.graph.add_hiddenimports(self.hiddenimports)
  610. # -- Post-graph hooks. --
  611. self.graph.process_post_graph_hooks(self)
  612. # Update 'binaries' and 'datas' TOC lists with entries collected from hooks.
  613. self.binaries += self.graph.make_hook_binaries_toc()
  614. self.datas += self.graph.make_hook_datas_toc()
  615. # We do not support zipped eggs anymore (PyInstaller v6.0), so `zipped_data` and `zipfiles` are always empty.
  616. self.zipped_data = []
  617. self.zipfiles = []
  618. # -- Automatic binary vs. data reclassification. --
  619. #
  620. # At this point, `binaries` and `datas` contain TOC entries supplied by user via input arguments, and by hooks
  621. # that were ran during the analysis. Neither source can be fully trusted regarding the DATA vs BINARY
  622. # classification (no thanks to our hookutils not being 100% reliable, either!). Therefore, inspect the files and
  623. # automatically reclassify them as necessary.
  624. #
  625. # The proper classification is important especially for collected binaries - to ensure that they undergo binary
  626. # dependency analysis and platform-specific binary processing. On macOS, the .app bundle generation code also
  627. # depends on files to be properly classified.
  628. #
  629. # For entries added to `binaries` and `datas` after this point, we trust their typecodes due to the nature of
  630. # their origin.
  631. combined_toc = normalize_toc(self.datas + self.binaries)
  632. logger.info('Performing binary vs. data reclassification (%d entries)', len(combined_toc))
  633. self.datas = []
  634. self.binaries = []
  635. for dest_name, src_name, typecode in combined_toc:
  636. # Returns 'BINARY' or 'DATA', or None if file cannot be classified.
  637. detected_typecode = bindepend.classify_binary_vs_data(src_name)
  638. if detected_typecode is not None:
  639. if detected_typecode != typecode:
  640. logger.debug(
  641. "Reclassifying collected file %r from %s to %s...", src_name, typecode, detected_typecode
  642. )
  643. typecode = detected_typecode
  644. # Put back into corresponding TOC list.
  645. if typecode in {'BINARY', 'EXTENSION'}:
  646. self.binaries.append((dest_name, src_name, typecode))
  647. else:
  648. self.datas.append((dest_name, src_name, typecode))
  649. # -- Look for dlls that are imported by Python 'ctypes' module. --
  650. # First get code objects of all modules that import 'ctypes'.
  651. logger.info('Looking for ctypes DLLs')
  652. # dict like: {'module1': code_obj, 'module2': code_obj}
  653. ctypes_code_objs = self.graph.get_code_using("ctypes")
  654. for name, co in ctypes_code_objs.items():
  655. # Get dlls that might be needed by ctypes.
  656. logger.debug('Scanning %s for ctypes-based references to shared libraries', name)
  657. try:
  658. ctypes_binaries = scan_code_for_ctypes(co)
  659. # As this scan happens after automatic binary-vs-data classification, we need to validate the binaries
  660. # ourselves, just in case.
  661. for dest_name, src_name, typecode in set(ctypes_binaries):
  662. # Allow for `None` in case re-classification is not supported on the given platform.
  663. if bindepend.classify_binary_vs_data(src_name) not in (None, 'BINARY'):
  664. logger.warning("Ignoring %s found via ctypes - not a valid binary!", src_name)
  665. continue
  666. self.binaries.append((dest_name, src_name, typecode))
  667. except Exception as ex:
  668. raise RuntimeError(f"Failed to scan the module '{name}'. This is a bug. Please report it.") from ex
  669. self.datas.extend((dest, source, "DATA")
  670. for (dest, source) in format_binaries_and_datas(self.graph.metadata_required()))
  671. # Analyze run-time hooks.
  672. rhtook_scripts = self.graph.analyze_runtime_hooks(self.custom_runtime_hooks)
  673. # -- Extract the nodes of the graph as TOCs for further processing. --
  674. # Initialize the scripts list: run-time hooks (custom ones, followed by regular ones), followed by program
  675. # script(s).
  676. # We do not optimize bytecode of run-time hooks.
  677. rthook_toc = self.graph.nodes_to_toc(rhtook_scripts)
  678. # Override the typecode of program script(s) to include bytecode optimization level.
  679. program_toc = self.graph.nodes_to_toc(program_scripts)
  680. optim_typecode = {0: 'PYSOURCE', 1: 'PYSOURCE-1', 2: 'PYSOURCE-2'}[self.optimize]
  681. program_toc = [(name, src_path, optim_typecode) for name, src_path, typecode in program_toc]
  682. self.scripts = rthook_toc + program_toc
  683. self.scripts = normalize_toc(self.scripts) # Should not really contain duplicates, but just in case...
  684. # Extend the binaries list with all the Extensions modulegraph has found.
  685. self.binaries += self.graph.make_binaries_toc()
  686. # Convert extension module names into full filenames, and append suffix. Ensure that extensions that come from
  687. # the lib-dynload are collected into _MEIPASS/python3.x/lib-dynload instead of directly into _MEIPASS.
  688. for idx, (dest, source, typecode) in enumerate(self.binaries):
  689. if typecode != 'EXTENSION':
  690. continue
  691. dest = destination_name_for_extension(dest, source, typecode)
  692. self.binaries[idx] = (dest, source, typecode)
  693. # Perform initial normalization of `datas` and `binaries`
  694. self.datas = normalize_toc(self.datas)
  695. self.binaries = normalize_toc(self.binaries)
  696. # Post-process GLib schemas
  697. self.datas = compile_glib_schema_files(self.datas, os.path.join(CONF['workpath'], "_pyi_gschema_compilation"))
  698. self.datas = normalize_toc(self.datas)
  699. # Process the pure-python modules list. Depending on the collection mode, these entries end up either in "pure"
  700. # list for collection into the PYZ archive, or in the "datas" list for collection as external data files.
  701. assert len(self.pure) == 0
  702. pure_pymodules_toc = self.graph.make_pure_toc()
  703. # Merge package collection mode settings from .spec file. These are applied last, so they override the
  704. # settings previously applied by hooks.
  705. self.graph._module_collection_mode.update(self.module_collection_mode)
  706. logger.debug("Module collection settings: %r", self.graph._module_collection_mode)
  707. # If target bytecode optimization level matches the run-time bytecode optimization level (i.e., of the running
  708. # build process), we can re-use the modulegraph's code-object cache.
  709. if self.optimize == sys.flags.optimize:
  710. logger.debug(
  711. "Target optimization level %d matches run-time optimization level %d - using modulegraph's code-object "
  712. "cache.",
  713. self.optimize,
  714. sys.flags.optimize,
  715. )
  716. code_cache = self.graph.get_code_objects()
  717. else:
  718. logger.debug(
  719. "Target optimization level %d differs from run-time optimization level %d - ignoring modulegraph's "
  720. "code-object cache.",
  721. self.optimize,
  722. sys.flags.optimize,
  723. )
  724. code_cache = None
  725. # Construct a set for look-up of modules that should end up in base_library.zip. The list of corresponding
  726. # modulegraph nodes is stored in `PyiModuleGraph._base_modules` (see `PyiModuleGraph._analyze_base_modules`).
  727. base_modules = set(node.identifier for node in self.graph._base_modules)
  728. base_modules_toc = []
  729. pycs_dir = os.path.join(CONF['workpath'], 'localpycs')
  730. optim_level = self.optimize # We could extend this with per-module settings, similar to `collect_mode`.
  731. for name, src_path, typecode in pure_pymodules_toc:
  732. assert typecode == 'PYMODULE'
  733. collect_mode = _get_module_collection_mode(self.graph._module_collection_mode, name, self.noarchive)
  734. # Collect byte-compiled .pyc into PYZ archive or base_library.zip. Embed optimization level into typecode.
  735. in_pyz = False
  736. if _ModuleCollectionMode.PYZ in collect_mode:
  737. optim_typecode = {0: 'PYMODULE', 1: 'PYMODULE-1', 2: 'PYMODULE-2'}[optim_level]
  738. toc_entry = (name, src_path, optim_typecode)
  739. if name in base_modules:
  740. base_modules_toc.append(toc_entry)
  741. else:
  742. self.pure.append(toc_entry)
  743. in_pyz = True
  744. # If module is not collected into PYZ archive (and is consequently not tracked in the `self.pure` TOC list),
  745. # add it to the `self._modules_outside_pyz` TOC list, in order to be able to detect modifications in those
  746. # modules.
  747. if not in_pyz:
  748. self._modules_outside_pyz.append((name, src_path, typecode))
  749. # Pure namespace packages have no source path, and cannot be collected as external data file.
  750. if src_path in (None, '-'):
  751. continue
  752. # Collect source .py file as external data file
  753. if _ModuleCollectionMode.PY in collect_mode:
  754. basename, ext = os.path.splitext(os.path.basename(src_path))
  755. # If the module is available only as a byte-compiled .pyc, we cannot collect its source.
  756. if ext.lower() == '.pyc':
  757. logger.warning(
  758. 'Cannot collect source .py file for module %r - module is available only as .pyc: %r',
  759. name,
  760. src_path,
  761. )
  762. continue
  763. dest_path = name.replace('.', os.sep)
  764. if basename == '__init__':
  765. dest_path += os.sep + '__init__' + ext
  766. else:
  767. dest_path += ext
  768. self.datas.append((dest_path, src_path, "DATA"))
  769. # Collect byte-compiled .pyc file as external data file
  770. if _ModuleCollectionMode.PYC in collect_mode:
  771. basename, ext = os.path.splitext(os.path.basename(src_path))
  772. dest_path = name.replace('.', os.sep)
  773. if basename == '__init__':
  774. dest_path += os.sep + '__init__'
  775. # Append the extension for the compiled result. In python 3.5 (PEP-488) .pyo files were replaced by
  776. # .opt-1.pyc and .opt-2.pyc. However, it seems that for bytecode-only module distribution, we always
  777. # need to use the .pyc extension.
  778. dest_path += '.pyc'
  779. # Compile - use optimization-level-specific sub-directory in local working directory.
  780. obj_path = compile_pymodule(
  781. name,
  782. src_path,
  783. workpath=os.path.join(pycs_dir, str(optim_level)),
  784. optimize=optim_level,
  785. code_cache=code_cache,
  786. )
  787. self.datas.append((dest_path, obj_path, "DATA"))
  788. # Construct base_library.zip, if applicable (the only scenario where it is not is if we are building with
  789. # noarchive mode). Always remove the file before the build.
  790. base_library_zip = os.path.join(CONF['workpath'], 'base_library.zip')
  791. if os.path.exists(base_library_zip):
  792. os.remove(base_library_zip)
  793. if base_modules_toc:
  794. logger.info('Creating %s...', os.path.basename(base_library_zip))
  795. create_base_library_zip(base_library_zip, base_modules_toc, code_cache)
  796. self.datas.append((os.path.basename(base_library_zip), base_library_zip, 'DATA')) # Bundle as data file.
  797. # Normalize list of pure-python modules (these will end up in PYZ archive, so use specific normalization).
  798. self.pure = normalize_pyz_toc(self.pure)
  799. # Associate the `pure` TOC list instance with code cache in the global `CONF`; this is used by `PYZ` writer
  800. # to obtain modules' code from cache instead
  801. #
  802. # (NOTE: back when `pure` was an instance of `TOC` class, the code object was passed by adding an attribute
  803. # to the `pure` itself; now that `pure` is plain `list`, we cannot do that anymore. But the association via
  804. # object ID should have the same semantics as the added attribute).
  805. from PyInstaller.config import CONF
  806. global_code_cache_map = CONF['code_cache']
  807. global_code_cache_map[id(self.pure)] = code_cache
  808. # Add remaining binary dependencies - analyze Python C-extensions and what DLLs they depend on.
  809. #
  810. # Up until this point, we did very best not to import the packages into the main process. However, a package
  811. # may set up additional library search paths during its import (e.g., by modifying PATH or calling the
  812. # add_dll_directory() function on Windows, or modifying LD_LIBRARY_PATH on Linux). In order to reliably
  813. # discover dynamic libraries, we therefore require an environment with all packages imported. We achieve that
  814. # by gathering list of all collected packages, and spawn an isolated process, in which we first import all
  815. # the packages from the list, and then perform search for dynamic libraries.
  816. logger.info('Looking for dynamic libraries')
  817. collected_packages = self.graph.get_collected_packages()
  818. self.binaries.extend(
  819. find_binary_dependencies(self.binaries, collected_packages, self.graph._bindepend_symlink_suppression)
  820. )
  821. # Apply work-around for (potential) binaries collected from `pywin32` package...
  822. if is_win:
  823. self.binaries = postprocess_binaries_toc_pywin32(self.binaries)
  824. # With anaconda, we need additional work-around...
  825. if is_conda:
  826. self.binaries = postprocess_binaries_toc_pywin32_anaconda(self.binaries)
  827. # On linux, check for HMAC files accompanying shared library files and, if available, collect them.
  828. # These are present on Fedora and RHEL, and are used in FIPS-enabled configurations to ensure shared
  829. # library's file integrity.
  830. if is_linux:
  831. for dest_name, src_name, typecode in self.binaries:
  832. if typecode not in {'BINARY', 'EXTENSION'}:
  833. continue # Skip symbolic links
  834. src_lib_path = pathlib.Path(src_name)
  835. # Check for .name.hmac file next to the shared library.
  836. src_hmac_path = src_lib_path.with_name(f".{src_lib_path.name}.hmac")
  837. if src_hmac_path.is_file():
  838. dest_hmac_path = pathlib.PurePath(dest_name).with_name(src_hmac_path.name)
  839. self.datas.append((str(dest_hmac_path), str(src_hmac_path), 'DATA'))
  840. # Alternatively, check the fipscheck directory: fipscheck/name.hmac
  841. src_hmac_path = src_lib_path.parent / "fipscheck" / f"{src_lib_path.name}.hmac"
  842. if src_hmac_path.is_file():
  843. dest_hmac_path = pathlib.PurePath("fipscheck") / src_hmac_path.name
  844. self.datas.append((str(dest_hmac_path), str(src_hmac_path), 'DATA'))
  845. # Similarly, look for .chk files that are used by NSS libraries.
  846. src_chk_path = src_lib_path.with_suffix(".chk")
  847. if src_chk_path.is_file():
  848. dest_chk_path = pathlib.PurePath(dest_name).with_name(src_chk_path.name)
  849. self.datas.append((str(dest_chk_path), str(src_chk_path), 'DATA'))
  850. # Final normalization of `datas` and `binaries`:
  851. # - normalize both TOCs together (to avoid having duplicates across the lists)
  852. # - process the combined normalized TOC for symlinks
  853. # - split back into `binaries` (BINARY, EXTENSION) and `datas` (everything else)
  854. combined_toc = normalize_toc(self.datas + self.binaries)
  855. combined_toc = toc_process_symbolic_links(combined_toc)
  856. # On macOS, look for binaries collected from .framework bundles, collect their Info.plist files, and fix the
  857. # structure to conform to code-signing requirements (i.e., Versions/Current symbolic link and symbolic links
  858. # for top-level directories).
  859. if is_darwin:
  860. combined_toc = osxutils.collect_files_from_framework_bundles(combined_toc)
  861. combined_toc = normalize_toc(combined_toc)
  862. self.datas = []
  863. self.binaries = []
  864. for entry in combined_toc:
  865. dest_name, src_name, typecode = entry
  866. if typecode in {'BINARY', 'EXTENSION'}:
  867. self.binaries.append(entry)
  868. else:
  869. self.datas.append(entry)
  870. # On macOS, the Finder app seems to litter visited directories with `.DS_Store` files. These cause issues with
  871. # codesigning when placed in mixed-content directories, where our .app bundle generator cross-links data files
  872. # from `Resources` to `Frameworks` tree, and the `codesign` utility explicitly forbids a `.DS_Store` file to be
  873. # a symbolic link.
  874. # But there is no reason for `.DS_Store` files to be collected in the first place, so filter them out.
  875. if is_darwin:
  876. self.datas = [(dest_name, src_name, typecode) for dest_name, src_name, typecode in self.datas
  877. if os.path.basename(src_name) != '.DS_Store']
  878. # Write warnings about missing modules.
  879. self._write_warnings()
  880. # Write debug information about the graph
  881. self._write_graph_debug()
  882. # On macOS, check the SDK version of the binaries to be collected, and warn when the SDK version is either
  883. # invalid or too low. Such binaries will likely refuse to be loaded when hardened runtime is enabled and
  884. # while we cannot do anything about it, we can at least warn the user about it.
  885. # See: https://developer.apple.com/forums/thread/132526
  886. if is_darwin:
  887. binaries_with_invalid_sdk = []
  888. for dest_name, src_name, typecode in self.binaries:
  889. try:
  890. sdk_version = osxutils.get_macos_sdk_version(src_name)
  891. except Exception:
  892. logger.warning("Failed to query macOS SDK version of %r!", src_name, exc_info=True)
  893. binaries_with_invalid_sdk.append((dest_name, src_name, "unavailable"))
  894. continue
  895. if sdk_version < (10, 9, 0):
  896. binaries_with_invalid_sdk.append((dest_name, src_name, sdk_version))
  897. if binaries_with_invalid_sdk:
  898. logger.warning("Found one or more binaries with invalid or incompatible macOS SDK version:")
  899. for dest_name, src_name, sdk_version in binaries_with_invalid_sdk:
  900. logger.warning(" * %r, collected as %r; version: %r", src_name, dest_name, sdk_version)
  901. logger.warning("These binaries will likely cause issues with code-signing and hardened runtime!")
  902. def _write_warnings(self):
  903. """
  904. Write warnings about missing modules. Get them from the graph and use the graph to figure out who tried to
  905. import them.
  906. """
  907. def dependency_description(name, dep_info):
  908. if not dep_info or dep_info == 'direct':
  909. imptype = 0
  910. else:
  911. imptype = (dep_info.conditional + 2 * dep_info.function + 4 * dep_info.tryexcept)
  912. return '%s (%s)' % (name, IMPORT_TYPES[imptype])
  913. from PyInstaller.config import CONF
  914. miss_toc = self.graph.make_missing_toc()
  915. with open(CONF['warnfile'], 'w', encoding='utf-8') as wf:
  916. wf.write(WARNFILE_HEADER)
  917. for (n, p, status) in miss_toc:
  918. importers = self.graph.get_importers(n)
  919. print(
  920. status,
  921. 'module named',
  922. n,
  923. '- imported by',
  924. ', '.join(dependency_description(name, data) for name, data in importers),
  925. file=wf
  926. )
  927. logger.info("Warnings written to %s", CONF['warnfile'])
  928. def _write_graph_debug(self):
  929. """
  930. Write a xref (in html) and with `--log-level DEBUG` a dot-drawing of the graph.
  931. """
  932. from PyInstaller.config import CONF
  933. with open(CONF['xref-file'], 'w', encoding='utf-8') as fh:
  934. self.graph.create_xref(fh)
  935. logger.info("Graph cross-reference written to %s", CONF['xref-file'])
  936. if logger.getEffectiveLevel() > logging.DEBUG:
  937. return
  938. # The `DOT language's <https://www.graphviz.org/doc/info/lang.html>`_ default character encoding (see the end
  939. # of the linked page) is UTF-8.
  940. with open(CONF['dot-file'], 'w', encoding='utf-8') as fh:
  941. self.graph.graphreport(fh)
  942. logger.info("Graph drawing written to %s", CONF['dot-file'])
  943. def exclude_system_libraries(self, list_of_exceptions=None):
  944. """
  945. This method may be optionally called from the spec file to exclude any system libraries from the list of
  946. binaries other than those containing the shell-style wildcards in list_of_exceptions. Those that match
  947. '*python*' or are stored under 'lib-dynload' are always treated as exceptions and not excluded.
  948. """
  949. self.binaries = [
  950. entry for entry in self.binaries if _should_include_system_binary(entry, list_of_exceptions or [])
  951. ]
  952. class ExecutableBuilder:
  953. """
  954. Class that constructs the executable.
  955. """
  956. # TODO wrap the 'main' and 'build' function into this class.
  957. def build(spec, distpath, workpath, clean_build):
  958. """
  959. Build the executable according to the created SPEC file.
  960. """
  961. from PyInstaller.config import CONF
  962. # Ensure starting tilde in distpath / workpath is expanded into user's home directory. This is to work around for
  963. # tilde not being expanded when using `--workpath=~/path/abc` instead of `--workpath ~/path/abc` (or when the path
  964. # argument is quoted). See https://github.com/pyinstaller/pyinstaller/issues/696
  965. distpath = os.path.abspath(os.path.expanduser(distpath))
  966. workpath = os.path.abspath(os.path.expanduser(workpath))
  967. CONF['spec'] = os.path.abspath(spec)
  968. CONF['specpath'], CONF['specnm'] = os.path.split(CONF['spec'])
  969. CONF['specnm'] = os.path.splitext(CONF['specnm'])[0]
  970. # Add 'specname' to workpath and distpath if they point to PyInstaller homepath.
  971. if os.path.dirname(distpath) == HOMEPATH:
  972. distpath = os.path.join(HOMEPATH, CONF['specnm'], os.path.basename(distpath))
  973. CONF['distpath'] = distpath
  974. if os.path.dirname(workpath) == HOMEPATH:
  975. workpath = os.path.join(HOMEPATH, CONF['specnm'], os.path.basename(workpath), CONF['specnm'])
  976. else:
  977. workpath = os.path.join(workpath, CONF['specnm'])
  978. CONF['workpath'] = workpath
  979. CONF['warnfile'] = os.path.join(workpath, 'warn-%s.txt' % CONF['specnm'])
  980. CONF['dot-file'] = os.path.join(workpath, 'graph-%s.dot' % CONF['specnm'])
  981. CONF['xref-file'] = os.path.join(workpath, 'xref-%s.html' % CONF['specnm'])
  982. CONF['code_cache'] = dict()
  983. # Clean PyInstaller cache (CONF['cachedir']) and temporary files (workpath) to be able start a clean build.
  984. if clean_build:
  985. logger.info('Removing temporary files and cleaning cache in %s', CONF['cachedir'])
  986. for pth in (CONF['cachedir'], workpath):
  987. if os.path.exists(pth):
  988. # Remove all files in 'pth'.
  989. for f in glob.glob(pth + '/*'):
  990. # Remove dirs recursively.
  991. if os.path.isdir(f):
  992. shutil.rmtree(f)
  993. else:
  994. os.remove(f)
  995. # Create DISTPATH and workpath if they does not exist.
  996. for pth in (CONF['distpath'], CONF['workpath']):
  997. os.makedirs(pth, exist_ok=True)
  998. # Construct NAMESPACE for running the Python code from .SPEC file.
  999. # NOTE: Passing NAMESPACE allows to avoid having global variables in this module and makes isolated environment for
  1000. # running tests.
  1001. # NOTE: Defining NAMESPACE allows to map any class to a apecific name for .SPEC.
  1002. # FIXME: Some symbols might be missing. Add them if there are some failures.
  1003. # TODO: What from this .spec API is deprecated and could be removed?
  1004. spec_namespace = {
  1005. # Set of global variables that can be used while processing .spec file. Some of them act as configuration
  1006. # options.
  1007. 'DISTPATH': CONF['distpath'],
  1008. 'HOMEPATH': HOMEPATH,
  1009. 'SPEC': CONF['spec'],
  1010. 'specnm': CONF['specnm'],
  1011. 'SPECPATH': CONF['specpath'],
  1012. 'WARNFILE': CONF['warnfile'],
  1013. 'workpath': CONF['workpath'],
  1014. # PyInstaller classes for .spec.
  1015. 'TOC': TOC, # Kept for backward compatibility even though `TOC` class is deprecated.
  1016. 'Analysis': Analysis,
  1017. 'BUNDLE': BUNDLE,
  1018. 'COLLECT': COLLECT,
  1019. 'EXE': EXE,
  1020. 'MERGE': MERGE,
  1021. 'PYZ': PYZ,
  1022. 'Tree': Tree,
  1023. 'Splash': Splash,
  1024. # Python modules available for .spec.
  1025. 'os': os,
  1026. }
  1027. # Execute the specfile. Read it as a binary file...
  1028. try:
  1029. with open(spec, 'rb') as f:
  1030. # ... then let Python determine the encoding, since ``compile`` accepts byte strings.
  1031. code = compile(f.read(), spec, 'exec')
  1032. except FileNotFoundError:
  1033. raise SystemExit(f'ERROR: Spec file "{spec}" not found!')
  1034. exec(code, spec_namespace)
  1035. logger.info("Build complete! The results are available in: %s", CONF['distpath'])
  1036. def __add_options(parser):
  1037. parser.add_argument(
  1038. "--distpath",
  1039. metavar="DIR",
  1040. default=DEFAULT_DISTPATH,
  1041. help="Where to put the bundled app (default: ./dist)",
  1042. )
  1043. parser.add_argument(
  1044. '--workpath',
  1045. default=DEFAULT_WORKPATH,
  1046. help="Where to put all the temporary work files, .log, .pyz and etc. (default: ./build)",
  1047. )
  1048. parser.add_argument(
  1049. '-y',
  1050. '--noconfirm',
  1051. action="store_true",
  1052. default=False,
  1053. help="Replace output directory (default: %s) without asking for confirmation" %
  1054. os.path.join('SPECPATH', 'dist', 'SPECNAME'),
  1055. )
  1056. parser.add_argument(
  1057. '--upx-dir',
  1058. default=None,
  1059. help="Path to UPX utility (default: search the execution path)",
  1060. )
  1061. parser.add_argument(
  1062. '--clean',
  1063. dest='clean_build',
  1064. action='store_true',
  1065. default=False,
  1066. help="Clean PyInstaller cache and remove temporary files before building.",
  1067. )
  1068. def main(
  1069. pyi_config,
  1070. specfile,
  1071. noconfirm=False,
  1072. distpath=DEFAULT_DISTPATH,
  1073. workpath=DEFAULT_WORKPATH,
  1074. upx_dir=None,
  1075. clean_build=False,
  1076. **kw
  1077. ):
  1078. from PyInstaller.config import CONF
  1079. CONF['noconfirm'] = noconfirm
  1080. # If configuration dict is supplied - skip configuration step.
  1081. if pyi_config is None:
  1082. import PyInstaller.configure as configure
  1083. CONF.update(configure.get_config(upx_dir=upx_dir))
  1084. else:
  1085. CONF.update(pyi_config)
  1086. CONF['ui_admin'] = kw.get('ui_admin', False)
  1087. CONF['ui_access'] = kw.get('ui_uiaccess', False)
  1088. build(specfile, distpath, workpath, clean_build)