analysis.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. Define a modified ModuleGraph that can return its contents as a TOC and in other ways act like the old ImpTracker.
  13. TODO: This class, along with TOC and Tree, should be in a separate module.
  14. For reference, the ModuleGraph node types and their contents:
  15. nodetype identifier filename
  16. Script full path to .py full path to .py
  17. SourceModule basename full path to .py
  18. BuiltinModule basename None
  19. CompiledModule basename full path to .pyc
  20. Extension basename full path to .so
  21. MissingModule basename None
  22. Package basename full path to __init__.py
  23. packagepath is ['path to package']
  24. globalnames is set of global names __init__.py defines
  25. ExtensionPackage basename full path to __init__.{so,dll}
  26. packagepath is ['path to package']
  27. The main extension here over ModuleGraph is a method to extract nodes from the flattened graph and return them as a
  28. TOC, or added to a TOC. Other added methods look up nodes by identifier and return facts about them, replacing what
  29. the old ImpTracker list could do.
  30. """
  31. import ast
  32. import os
  33. import sys
  34. import traceback
  35. from collections import defaultdict
  36. from copy import deepcopy
  37. from PyInstaller import HOMEPATH, PACKAGEPATH
  38. from PyInstaller import log as logging
  39. from PyInstaller.building.utils import destination_name_for_extension
  40. from PyInstaller.compat import (
  41. BAD_MODULE_TYPES, BINARY_MODULE_TYPES, MODULE_TYPES_TO_TOC_DICT, PURE_PYTHON_MODULE_TYPES, PY3_BASE_MODULES,
  42. VALID_MODULE_TYPES, importlib_load_source, is_win
  43. )
  44. from PyInstaller.depend import bytecode
  45. from PyInstaller.depend.imphook import AdditionalFilesCache, ModuleHookCache
  46. from PyInstaller.depend.imphookapi import (PreFindModulePathAPI, PreSafeImportModuleAPI)
  47. from PyInstaller.lib.modulegraph.find_modules import get_implies
  48. from PyInstaller.lib.modulegraph.modulegraph import ModuleGraph, DEFAULT_IMPORT_LEVEL, ABSOLUTE_IMPORT_LEVEL, Package
  49. from PyInstaller.log import DEBUG, INFO, TRACE
  50. from PyInstaller.utils.hooks import collect_submodules, is_package
  51. logger = logging.getLogger(__name__)
  52. # Location-based hook priority constants
  53. HOOK_PRIORITY_BUILTIN_HOOKS = -2000 # Built-in hooks. Lowest priority.
  54. HOOK_PRIORITY_CONTRIBUTED_HOOKS = -1000 # Hooks from pyinstaller-hooks-contrib package.
  55. HOOK_PRIORITY_UPSTREAM_HOOKS = 0 # Hooks provided by packages themselves, via entry-points.
  56. HOOK_PRIORITY_USER_HOOKS = 1000 # User-supplied hooks (command-line / spec file). Highest priority.
  57. class PyiModuleGraph(ModuleGraph):
  58. """
  59. Directed graph whose nodes represent modules and edges represent dependencies between these modules.
  60. This high-level subclass wraps the lower-level `ModuleGraph` class with support for graph and runtime hooks.
  61. While each instance of `ModuleGraph` represents a set of disconnected trees, each instance of this class *only*
  62. represents a single connected tree whose root node is the Python script originally passed by the user on the
  63. command line. For that reason, while there may (and typically do) exist more than one `ModuleGraph` instance,
  64. there typically exists only a singleton instance of this class.
  65. Attributes
  66. ----------
  67. _hooks : ModuleHookCache
  68. Dictionary mapping the fully-qualified names of all modules with normal (post-graph) hooks to the absolute paths
  69. of such hooks. See the the `_find_module_path()` method for details.
  70. _hooks_pre_find_module_path : ModuleHookCache
  71. Dictionary mapping the fully-qualified names of all modules with pre-find module path hooks to the absolute
  72. paths of such hooks. See the the `_find_module_path()` method for details.
  73. _hooks_pre_safe_import_module : ModuleHookCache
  74. Dictionary mapping the fully-qualified names of all modules with pre-safe import module hooks to the absolute
  75. paths of such hooks. See the `_safe_import_module()` method for details.
  76. _user_hook_dirs : list
  77. List of the absolute paths of all directories containing user-defined hooks for the current application.
  78. _excludes : list
  79. List of module names to be excluded when searching for dependencies.
  80. _additional_files_cache : AdditionalFilesCache
  81. Cache of all external dependencies (e.g., binaries, datas) listed in hook scripts for imported modules.
  82. _module_collection_mode : dict
  83. A dictionary of module/package collection mode settings set by hook scripts for their modules.
  84. _bindepend_symlink_suppression : set
  85. A set of paths or path patterns corresponding to shared libraries for which binary dependency analysis should
  86. not create symbolic links into top-level application directory.
  87. _base_modules: list
  88. Dependencies for `base_library.zip` (which remain the same for every executable).
  89. """
  90. # Note: these levels are completely arbitrary and may be adjusted if needed.
  91. LOG_LEVEL_MAPPING = {0: INFO, 1: DEBUG, 2: TRACE, 3: TRACE, 4: TRACE}
  92. def __init__(self, pyi_homepath, user_hook_dirs=(), excludes=(), **kwargs):
  93. super().__init__(excludes=excludes, **kwargs)
  94. # Homepath to the place where is PyInstaller located.
  95. self._homepath = pyi_homepath
  96. # modulegraph Node for the main python script that is analyzed by PyInstaller.
  97. self._top_script_node = None
  98. # Absolute paths of all user-defined hook directories.
  99. self._excludes = excludes
  100. self._reset(user_hook_dirs)
  101. self._analyze_base_modules()
  102. def _reset(self, user_hook_dirs):
  103. """
  104. Reset for another set of scripts. This is primary required for running the test-suite.
  105. """
  106. self._top_script_node = None
  107. self._additional_files_cache = AdditionalFilesCache()
  108. self._module_collection_mode = dict()
  109. self._bindepend_symlink_suppression = set()
  110. # Hook sources: user-supplied (command-line / spec file), entry-point (upstream hooks, contributed hooks), and
  111. # built-in hooks. The order does not really matter anymore, because each entry is now a (location, priority)
  112. # tuple, and order is determined from assigned priority (which may also be overridden by hooks themselves).
  113. self._user_hook_dirs = [
  114. *user_hook_dirs,
  115. (os.path.join(PACKAGEPATH, 'hooks'), HOOK_PRIORITY_BUILTIN_HOOKS),
  116. ]
  117. # Hook-specific lookup tables. These need to reset when reusing cached PyiModuleGraph to avoid hooks to refer to
  118. # files or data from another test-case.
  119. logger.info('Initializing module graph hook caches...')
  120. self._hooks = self._cache_hooks("")
  121. self._hooks_pre_safe_import_module = self._cache_hooks('pre_safe_import_module')
  122. self._hooks_pre_find_module_path = self._cache_hooks('pre_find_module_path')
  123. # Search for run-time hooks in all hook directories.
  124. self._available_rthooks = defaultdict(list)
  125. for uhd, _ in self._user_hook_dirs:
  126. uhd_path = os.path.abspath(os.path.join(uhd, 'rthooks.dat'))
  127. try:
  128. with open(uhd_path, 'r', encoding='utf-8') as f:
  129. rthooks = ast.literal_eval(f.read())
  130. except FileNotFoundError:
  131. # Ignore if this hook path doesn't have run-time hooks.
  132. continue
  133. except Exception as e:
  134. logger.error('Unable to read run-time hooks from %r: %s' % (uhd_path, e))
  135. continue
  136. self._merge_rthooks(rthooks, uhd, uhd_path)
  137. # Convert back to a standard dict.
  138. self._available_rthooks = dict(self._available_rthooks)
  139. def _merge_rthooks(self, rthooks, uhd, uhd_path):
  140. """
  141. The expected data structure for a run-time hook file is a Python dictionary of type ``Dict[str, List[str]]``,
  142. where the dictionary keys are module names and the sequence strings are Python file names.
  143. Check then merge this data structure, updating the file names to be absolute.
  144. """
  145. # Check that the root element is a dict.
  146. assert isinstance(rthooks, dict), 'The root element in %s must be a dict.' % uhd_path
  147. for module_name, python_file_name_list in rthooks.items():
  148. # Ensure the key is a string.
  149. assert isinstance(module_name, str), \
  150. '%s must be a dict whose keys are strings; %s is not a string.' % (uhd_path, module_name)
  151. # Ensure the value is a list.
  152. assert isinstance(python_file_name_list, list), \
  153. 'The value of %s key %s must be a list.' % (uhd_path, module_name)
  154. if module_name in self._available_rthooks:
  155. logger.warning(
  156. 'Runtime hooks for %s have already been defined. Skipping the runtime hooks for %s that are '
  157. 'defined in %s.', module_name, module_name, os.path.join(uhd, 'rthooks')
  158. )
  159. # Skip this module
  160. continue
  161. # Merge this with existing run-time hooks.
  162. for python_file_name in python_file_name_list:
  163. # Ensure each item in the list is a string.
  164. assert isinstance(python_file_name, str), \
  165. '%s key %s, item %r must be a string.' % (uhd_path, module_name, python_file_name)
  166. # Transform it into an absolute path.
  167. abs_path = os.path.join(uhd, 'rthooks', python_file_name)
  168. # Make sure this file exists.
  169. assert os.path.exists(abs_path), \
  170. 'In %s, key %s, the file %r expected to be located at %r does not exist.' % \
  171. (uhd_path, module_name, python_file_name, abs_path)
  172. # Merge it.
  173. self._available_rthooks[module_name].append(abs_path)
  174. @staticmethod
  175. def _findCaller(*args, **kwargs):
  176. # Used to add an additional stack-frame above logger.findCaller. findCaller expects the caller to be three
  177. # stack-frames above itself.
  178. return logger.findCaller(*args, **kwargs)
  179. def msg(self, level, s, *args):
  180. """
  181. Print a debug message with the given level.
  182. 1. Map the msg log level to a logger log level.
  183. 2. Generate the message format (the same format as ModuleGraph)
  184. 3. Find the caller, which findCaller expects three stack-frames above itself:
  185. [3] caller -> [2] msg (here) -> [1] _findCaller -> [0] logger.findCaller
  186. 4. Create a logRecord with the caller's information.
  187. 5. Handle the logRecord.
  188. """
  189. try:
  190. level = self.LOG_LEVEL_MAPPING[level]
  191. except KeyError:
  192. return
  193. if not logger.isEnabledFor(level):
  194. return
  195. msg = "%s %s" % (s, ' '.join(map(repr, args)))
  196. try:
  197. fn, lno, func, sinfo = self._findCaller()
  198. except ValueError: # pragma: no cover
  199. fn, lno, func, sinfo = "(unknown file)", 0, "(unknown function)", None
  200. record = logger.makeRecord(logger.name, level, fn, lno, msg, [], None, func, None, sinfo)
  201. logger.handle(record)
  202. # Set logging methods so that the stack is correctly detected.
  203. msgin = msg
  204. msgout = msg
  205. def _cache_hooks(self, hook_type):
  206. """
  207. Create a cache of all hooks of the specified type.
  208. The cache will include all official hooks defined by the PyInstaller codebase _and_ all unofficial hooks
  209. defined for the current application.
  210. Parameters
  211. ----------
  212. hook_type : str
  213. Type of hooks to be cached, equivalent to the basename of the subpackage of the `PyInstaller.hooks`
  214. package containing such hooks (e.g., empty string for standard hooks, `pre_safe_import_module` for
  215. pre-safe-import-module hooks, `pre_find_module_path` for pre-find-module-path hooks).
  216. """
  217. # Cache of this type of hooks.
  218. hook_dirs = []
  219. for user_hook_dir, priority in self._user_hook_dirs:
  220. # Absolute path of the user-defined subdirectory of this hook type. If this directory exists, add it to the
  221. # list to be cached.
  222. user_hook_type_dir = os.path.join(user_hook_dir, hook_type)
  223. if os.path.isdir(user_hook_type_dir):
  224. hook_dirs.append((user_hook_type_dir, priority))
  225. return ModuleHookCache(self, hook_dirs)
  226. def _analyze_base_modules(self):
  227. """
  228. Analyze dependencies of the the modules in base_library.zip.
  229. """
  230. logger.info('Analyzing modules for base_library.zip ...')
  231. required_mods = []
  232. # Collect submodules from required modules in base_library.zip.
  233. for m in PY3_BASE_MODULES:
  234. if is_package(m):
  235. required_mods += collect_submodules(m)
  236. else:
  237. required_mods.append(m)
  238. # Initialize ModuleGraph.
  239. self._base_modules = [mod for req in required_mods for mod in self.import_hook(req)]
  240. def add_script(self, pathname, caller=None):
  241. """
  242. Wrap the parent's 'run_script' method and create graph from the first script in the analysis, and save its
  243. node to use as the "caller" node for all others. This gives a connected graph rather than a collection of
  244. unrelated trees.
  245. """
  246. if self._top_script_node is None:
  247. # Remember the node for the first script.
  248. try:
  249. self._top_script_node = super().add_script(pathname)
  250. except SyntaxError:
  251. print("\nSyntax error in", pathname, file=sys.stderr)
  252. formatted_lines = traceback.format_exc().splitlines(True)
  253. print(*formatted_lines[-4:], file=sys.stderr)
  254. sys.exit(1)
  255. # Create references from the top script to the base_modules in graph.
  256. for node in self._base_modules:
  257. self.add_edge(self._top_script_node, node)
  258. # Return top-level script node.
  259. return self._top_script_node
  260. else:
  261. if not caller:
  262. # Defaults to as any additional script is called from the top-level script.
  263. caller = self._top_script_node
  264. return super().add_script(pathname, caller=caller)
  265. def process_post_graph_hooks(self, analysis):
  266. """
  267. For each imported module, run this module's post-graph hooks if any.
  268. Parameters
  269. ----------
  270. analysis: build_main.Analysis
  271. The Analysis that calls the hooks
  272. """
  273. # For each iteration of the infinite "while" loop below:
  274. #
  275. # 1. All hook() functions defined in cached hooks for imported modules are called. This may result in new
  276. # modules being imported (e.g., as hidden imports) that were ignored earlier in the current iteration: if
  277. # this is the case, all hook() functions defined in cached hooks for these modules will be called by the next
  278. # iteration.
  279. # 2. All cached hooks whose hook() functions were called are removed from this cache. If this cache is empty, no
  280. # hook() functions will be called by the next iteration and this loop will be terminated.
  281. # 3. If no hook() functions were called, this loop is terminated.
  282. logger.info('Processing module hooks (post-graph stage)...')
  283. while True:
  284. # Set of the names of all imported modules whose post-graph hooks are run by this iteration, preventing the
  285. # next iteration from re- running these hooks. If still empty at the end of this iteration, no post-graph
  286. # hooks were run; thus, this loop will be terminated.
  287. hooked_module_names = set()
  288. # For each remaining hookable module and corresponding hooks...
  289. for module_name, module_hook in self._hooks.items():
  290. # Graph node for this module if imported or "None" otherwise.
  291. module_node = self.find_node(module_name, create_nspkg=False)
  292. # If this module has not been imported, temporarily ignore it. This module is retained in the cache, as
  293. # a subsequently run post-graph hook could import this module as a hidden import.
  294. if module_node is None:
  295. continue
  296. # If this module is unimportable, permanently ignore it.
  297. if type(module_node).__name__ not in VALID_MODULE_TYPES:
  298. hooked_module_names.add(module_name)
  299. continue
  300. # Run this script's post-graph hook.
  301. module_hook.post_graph(analysis)
  302. # Cache all external dependencies listed by this script after running this hook, which could add
  303. # dependencies.
  304. self._additional_files_cache.add(module_name, module_hook.binaries, module_hook.datas)
  305. # Update package collection mode settings.
  306. self._module_collection_mode.update(module_hook.module_collection_mode)
  307. # Update symbolic link suppression patterns for binary dependency analysis.
  308. self._bindepend_symlink_suppression.update(module_hook.bindepend_symlink_suppression)
  309. # Prevent this module's hooks from being run again.
  310. hooked_module_names.add(module_name)
  311. # Prevent all post-graph hooks run above from being run again by the next iteration.
  312. self._hooks.remove_modules(*hooked_module_names)
  313. # If no post-graph hooks were run, terminate iteration.
  314. if not hooked_module_names:
  315. break
  316. def _find_all_excluded_imports(self, module_name):
  317. """
  318. Collect excludedimports from the hooks of the specified module and all its parents.
  319. """
  320. excluded_imports = set()
  321. while module_name:
  322. # Gather excluded imports from hook belonging to the module.
  323. module_hook = self._hooks.get(module_name, None)
  324. if module_hook:
  325. excluded_imports.update(module_hook.excludedimports)
  326. # Change module name to the module's parent name
  327. module_name = module_name.rpartition('.')[0]
  328. return excluded_imports
  329. def _safe_import_hook(
  330. self, target_module_partname, source_module, target_attr_names, level=DEFAULT_IMPORT_LEVEL, edge_attr=None
  331. ):
  332. if source_module is not None:
  333. # Gather all excluded imports for the referring modules, as well as its parents.
  334. # For example, we want the excluded imports specified by hook for PIL to be also applied when the referring
  335. # module is its submodule, PIL.Image.
  336. excluded_imports = self._find_all_excluded_imports(source_module.identifier)
  337. # Apply extra processing only if we have any excluded-imports rules
  338. if excluded_imports:
  339. # Resolve the base module name. Level can be ABSOLUTE_IMPORT_LEVEL (= 0) for absolute imports, or an
  340. # integer indicating the relative level. We do not use equality comparison just in case we ever happen
  341. # to get ABSOLUTE_OR_RELATIVE_IMPORT_LEVEL (-1), which is a remnant of python2 days.
  342. if level > ABSOLUTE_IMPORT_LEVEL:
  343. if isinstance(source_module, Package):
  344. # Package
  345. base_module_name = source_module.identifier
  346. else:
  347. # Module in a package; base name must be the parent package name!
  348. base_module_name = '.'.join(source_module.identifier.split('.')[:-1])
  349. # Adjust the base module name based on level
  350. if level > 1:
  351. base_module_name = '.'.join(base_module_name.split('.')[:-(level - 1)])
  352. if target_module_partname:
  353. base_module_name += '.' + target_module_partname
  354. else:
  355. base_module_name = target_module_partname
  356. def _exclude_module(module_name, excluded_imports, referrer_name):
  357. """
  358. Helper for checking whether given module should be excluded.
  359. Returns the name of exclusion rule if module should be excluded, None otherwise.
  360. """
  361. module_name_parts = module_name.split('.')
  362. for excluded_import in excluded_imports:
  363. excluded_import_parts = excluded_import.split('.')
  364. match = module_name_parts[:len(excluded_import_parts)] == excluded_import_parts
  365. if match:
  366. # Check if the referrer is (was!) subject to the same rule. Because if it was and was
  367. # analyzed anyway, some other import chain must have overrode the exclusion, and we should
  368. # waive it here. A package hook might exclude a part (a subpackage) of the said package to
  369. # prevent its collection when there are no external references; but when they are (for
  370. # example, user explicitly imports the said subpackage in their program), we must let the
  371. # subpackage import its submodules.
  372. referrer_name_parts = referrer_name.split('.')
  373. referrer_match = referrer_name_parts[:len(excluded_import_parts)] == excluded_import_parts
  374. if referrer_match:
  375. logger.debug(
  376. "Deactivating suppression rule %r for module %r because it also applies to the "
  377. "referrer (%r)...", excluded_import, module_name, referrer_name
  378. )
  379. continue
  380. return excluded_import
  381. return None
  382. # First, check if base module name is to be excluded.
  383. # This covers both basic `import a` and `import a.b.c`, as well as `from d import e, f` where base
  384. # module `d` is excluded.
  385. excluded_import_rule = _exclude_module(
  386. base_module_name,
  387. excluded_imports,
  388. source_module.identifier,
  389. )
  390. if excluded_import_rule:
  391. logger.debug(
  392. "Suppressing import of %r from module %r due to excluded import %r specified in a hook for %r "
  393. "(or its parent package(s)).", base_module_name, source_module.identifier, excluded_import_rule,
  394. source_module.identifier
  395. )
  396. return []
  397. # If we have target attribute names, check each of them, and remove excluded ones from the
  398. # `target_attr_names` list.
  399. if target_attr_names:
  400. filtered_target_attr_names = []
  401. for target_attr_name in target_attr_names:
  402. submodule_name = base_module_name + '.' + target_attr_name
  403. excluded_import_rule = _exclude_module(
  404. submodule_name,
  405. excluded_imports,
  406. source_module.identifier,
  407. )
  408. if excluded_import_rule:
  409. logger.debug(
  410. "Suppressing import of %r from module %r due to excluded import %r specified in a hook "
  411. "for %r (or its parent package(s)).", submodule_name, source_module.identifier,
  412. excluded_import_rule, source_module.identifier
  413. )
  414. else:
  415. filtered_target_attr_names.append(target_attr_name)
  416. # Swap with filtered target attribute names list; if no elements remain after the filtering, pass
  417. # None...
  418. target_attr_names = filtered_target_attr_names or None
  419. ret_modules = super()._safe_import_hook(
  420. target_module_partname, source_module, target_attr_names, level, edge_attr
  421. )
  422. # Ensure that hooks are pre-loaded for returned module(s), in an attempt to ensure that hooks are called in the
  423. # order of imports. The hooks are cached, so there should be no downsides to pre-loading hooks early (as opposed
  424. # to loading them in post-graph analysis). When modules are imported from other modules, the hooks for those
  425. # referring (source) modules and their parent package(s) are loaded by the exclusion mechanism that takes place
  426. # before the above `super()._safe_import_hook` call. The code below attempts to complement that, but for the
  427. # referred (target) modules and their parent package(s).
  428. for ret_module in ret_modules:
  429. if type(ret_module).__name__ not in VALID_MODULE_TYPES:
  430. continue
  431. # (Ab)use the `_find_all_excluded_imports` helper to load all hooks for the given module and its parent
  432. # package(s).
  433. self._find_all_excluded_imports(ret_module.identifier)
  434. return ret_modules
  435. def _safe_import_module(self, module_basename, module_name, parent_package):
  436. """
  437. Create a new graph node for the module with the passed name under the parent package signified by the passed
  438. graph node.
  439. This method wraps the superclass method with support for pre-import module hooks. If such a hook exists for
  440. this module (e.g., a script `PyInstaller.hooks.hook-{module_name}` containing a function
  441. `pre_safe_import_module()`), that hook will be run _before_ the superclass method is called.
  442. Pre-Safe-Import-Hooks are performed just *prior* to importing the module. When running the hook, the modules
  443. parent package has already been imported and ti's `__path__` is set up. But the module is just about to be
  444. imported.
  445. See the superclass method for description of parameters and return value.
  446. """
  447. # If this module has a pre-safe import module hook, run it. Make sure to remove it first, to prevent subsequent
  448. # calls from running it again.
  449. hook = self._hooks_pre_safe_import_module.pop(module_name, None)
  450. if hook is not None:
  451. # Dynamically import this hook as a fabricated module.
  452. hook_path, hook_basename = os.path.split(hook.hook_filename)
  453. logger.info('Processing pre-safe-import-module hook %r from %r', hook_basename, hook_path)
  454. hook_module_name = 'PyInstaller_hooks_pre_safe_import_module_' + module_name.replace('.', '_')
  455. hook_module = importlib_load_source(hook_module_name, hook.hook_filename)
  456. # Object communicating changes made by this hook back to us.
  457. hook_api = PreSafeImportModuleAPI(
  458. module_graph=self,
  459. module_basename=module_basename,
  460. module_name=module_name,
  461. parent_package=parent_package,
  462. )
  463. # Run this hook, passed this object.
  464. if not hasattr(hook_module, 'pre_safe_import_module'):
  465. raise NameError('pre_safe_import_module() function not defined by hook %r.' % hook_module)
  466. hook_module.pre_safe_import_module(hook_api)
  467. # Respect method call changes requested by this hook.
  468. module_basename = hook_api.module_basename
  469. module_name = hook_api.module_name
  470. # Call the superclass method.
  471. return super()._safe_import_module(module_basename, module_name, parent_package)
  472. def _find_module_path(self, fullname, module_name, search_dirs):
  473. """
  474. Get a 3-tuple detailing the physical location of the module with the passed name if that module exists _or_
  475. raise `ImportError` otherwise.
  476. This method wraps the superclass method with support for pre-find module path hooks. If such a hook exists
  477. for this module (e.g., a script `PyInstaller.hooks.hook-{module_name}` containing a function
  478. `pre_find_module_path()`), that hook will be run _before_ the superclass method is called.
  479. See superclass method for parameter and return value descriptions.
  480. """
  481. # If this module has a pre-find module path hook, run it. Make sure to remove it first, to prevent subsequent
  482. # calls from running it again.
  483. hook = self._hooks_pre_find_module_path.pop(fullname, None)
  484. if hook is not None:
  485. # Dynamically import this hook as a fabricated module.
  486. hook_path, hook_basename = os.path.split(hook.hook_filename)
  487. logger.info('Processing pre-find-module-path hook %r from %r', hook_basename, hook_path)
  488. hook_fullname = 'PyInstaller_hooks_pre_find_module_path_' + fullname.replace('.', '_')
  489. hook_module = importlib_load_source(hook_fullname, hook.hook_filename)
  490. # Object communicating changes made by this hook back to us.
  491. hook_api = PreFindModulePathAPI(
  492. module_graph=self,
  493. module_name=fullname,
  494. search_dirs=search_dirs,
  495. )
  496. # Run this hook, passed this object.
  497. if not hasattr(hook_module, 'pre_find_module_path'):
  498. raise NameError('pre_find_module_path() function not defined by hook %r.' % hook_module)
  499. hook_module.pre_find_module_path(hook_api)
  500. # Respect search-directory changes requested by this hook.
  501. search_dirs = hook_api.search_dirs
  502. # Call the superclass method.
  503. return super()._find_module_path(fullname, module_name, search_dirs)
  504. def get_code_objects(self):
  505. """
  506. Get code objects from ModuleGraph for pure Python modules. This allows to avoid writing .pyc/pyo files to hdd
  507. at later stage.
  508. :return: Dict with module name and code object.
  509. """
  510. code_dict = {}
  511. mod_types = PURE_PYTHON_MODULE_TYPES
  512. for node in self.iter_graph(start=self._top_script_node):
  513. # TODO This is terrible. To allow subclassing, types should never be directly compared. Use isinstance()
  514. # instead, which is safer, simpler, and accepts sets. Most other calls to type() in the codebase should also
  515. # be refactored to call isinstance() instead.
  516. # get node type e.g. Script
  517. mg_type = type(node).__name__
  518. if mg_type in mod_types:
  519. if node.code:
  520. code_dict[node.identifier] = node.code
  521. return code_dict
  522. def _make_toc(self, typecode=None):
  523. """
  524. Return the name, path and type of selected nodes as a TOC. The selection is determined by the given list
  525. of PyInstaller TOC typecodes. If that list is empty we return the complete flattened graph as a TOC with the
  526. ModuleGraph note types in place of typecodes -- meant for debugging only. Normally we return ModuleGraph
  527. nodes whose types map to the requested PyInstaller typecode(s) as indicated in the MODULE_TYPES_TO_TOC_DICT.
  528. We use the ModuleGraph (really, ObjectGraph) flatten() method to scan all the nodes. This is patterned after
  529. ModuleGraph.report().
  530. """
  531. toc = list()
  532. for node in self.iter_graph(start=self._top_script_node):
  533. entry = self._node_to_toc(node, typecode)
  534. # Append the entry. We do not check for duplicates here; the TOC normalization is left to caller.
  535. # However, as entries are obtained from modulegraph, there should not be any duplicates at this stage.
  536. if entry is not None:
  537. toc.append(entry)
  538. return toc
  539. def make_pure_toc(self):
  540. """
  541. Return all pure Python modules formatted as TOC.
  542. """
  543. # PyInstaller should handle special module types without code object.
  544. return self._make_toc(PURE_PYTHON_MODULE_TYPES)
  545. def make_binaries_toc(self):
  546. """
  547. Return all binary Python modules formatted as TOC.
  548. """
  549. return self._make_toc(BINARY_MODULE_TYPES)
  550. def make_missing_toc(self):
  551. """
  552. Return all MISSING Python modules formatted as TOC.
  553. """
  554. return self._make_toc(BAD_MODULE_TYPES)
  555. @staticmethod
  556. def _node_to_toc(node, typecode=None):
  557. # TODO This is terrible. Everything in Python has a type. It is nonsensical to even speak of "nodes [that] are
  558. # not typed." How would that even occur? After all, even "None" has a type! (It is "NoneType", for the curious.)
  559. # Remove this, please.
  560. # Get node type, e.g., Script
  561. mg_type = type(node).__name__
  562. assert mg_type is not None
  563. if typecode and mg_type not in typecode:
  564. # Type is not a to be selected one, skip this one
  565. return None
  566. # Extract the identifier and a path if any.
  567. if mg_type == 'Script':
  568. # for Script nodes only, identifier is a whole path
  569. (name, ext) = os.path.splitext(node.filename)
  570. name = os.path.basename(name)
  571. elif mg_type == 'ExtensionPackage':
  572. # Package with __init__ module being an extension module. This needs to end up as e.g. 'mypkg/__init__.so'.
  573. # Convert the packages name ('mypkg') into the module name ('mypkg.__init__') *here* to keep special cases
  574. # away elsewhere (where the module name is converted to a filename).
  575. name = node.identifier + ".__init__"
  576. else:
  577. name = node.identifier
  578. path = node.filename if node.filename is not None else ''
  579. # Ensure name is really 'str'. Module graph might return object type 'modulegraph.Alias' which inherits fromm
  580. # 'str'. But 'marshal.dumps()' function is able to marshal only 'str'. Otherwise on Windows PyInstaller might
  581. # fail with message like:
  582. # ValueError: unmarshallable object
  583. name = str(name)
  584. # Translate to the corresponding TOC typecode.
  585. toc_type = MODULE_TYPES_TO_TOC_DICT[mg_type]
  586. return name, path, toc_type
  587. def nodes_to_toc(self, nodes):
  588. """
  589. Given a list of nodes, create a TOC representing those nodes. This is mainly used to initialize a TOC of
  590. scripts with the ones that are runtime hooks. The process is almost the same as _make_toc(), but the caller
  591. guarantees the nodes are valid, so minimal checking.
  592. """
  593. return [self._node_to_toc(node) for node in nodes]
  594. # Return true if the named item is in the graph as a BuiltinModule node. The passed name is a basename.
  595. def is_a_builtin(self, name):
  596. node = self.find_node(name)
  597. if node is None:
  598. return False
  599. return type(node).__name__ == 'BuiltinModule'
  600. def get_importers(self, name):
  601. """
  602. List all modules importing the module with the passed name.
  603. Returns a list of (identifier, DependencyIinfo)-tuples. If the names module has not yet been imported, this
  604. method returns an empty list.
  605. Parameters
  606. ----------
  607. name : str
  608. Fully-qualified name of the module to be examined.
  609. Returns
  610. ----------
  611. list
  612. List of (fully-qualified names, DependencyIinfo)-tuples of all modules importing the module with the passed
  613. fully-qualified name.
  614. """
  615. def get_importer_edge_data(importer):
  616. edge = self.graph.edge_by_node(importer, name)
  617. # edge might be None in case an AliasModule was added.
  618. if edge is not None:
  619. return self.graph.edge_data(edge)
  620. node = self.find_node(name)
  621. if node is None:
  622. return []
  623. _, importers = self.get_edges(node)
  624. importers = (importer.identifier for importer in importers if importer is not None)
  625. return [(importer, get_importer_edge_data(importer)) for importer in importers]
  626. # TODO: create a class from this function.
  627. def analyze_runtime_hooks(self, custom_runhooks):
  628. """
  629. Analyze custom run-time hooks and run-time hooks implied by found modules.
  630. :return : list of Graph nodes.
  631. """
  632. rthooks_nodes = []
  633. logger.info('Analyzing run-time hooks ...')
  634. # Process custom runtime hooks (from --runtime-hook options). The runtime hooks are order dependent. First hooks
  635. # in the list are executed first. Put their graph nodes at the head of the priority_scripts list Pyinstaller
  636. # defined rthooks and thus they are executed first.
  637. if custom_runhooks:
  638. for hook_file in custom_runhooks:
  639. logger.info("Including custom run-time hook %r", hook_file)
  640. hook_file = os.path.abspath(hook_file)
  641. # Not using "try" here because the path is supposed to exist, if it does not, the raised error will
  642. # explain.
  643. rthooks_nodes.append(self.add_script(hook_file))
  644. # Find runtime hooks that are implied by packages already imported. Get a temporary TOC listing all the scripts
  645. # and packages graphed so far. Assuming that runtime hooks apply only to modules and packages.
  646. temp_toc = self._make_toc(VALID_MODULE_TYPES)
  647. for (mod_name, path, typecode) in temp_toc:
  648. # Look if there is any run-time hook for given module.
  649. if mod_name in self._available_rthooks:
  650. # There could be several run-time hooks for a module.
  651. for abs_path in self._available_rthooks[mod_name]:
  652. hook_path, hook_basename = os.path.split(abs_path)
  653. logger.info("Including run-time hook %r from %r", hook_basename, hook_path)
  654. rthooks_nodes.append(self.add_script(abs_path))
  655. return rthooks_nodes
  656. def add_hiddenimports(self, module_list):
  657. """
  658. Add hidden imports that are either supplied as CLI option --hidden-import=MODULENAME or as dependencies from
  659. some PyInstaller features when enabled (e.g., crypto feature).
  660. """
  661. assert self._top_script_node is not None
  662. # Analyze the script's hidden imports (named on the command line).
  663. for modnm in module_list:
  664. node = self.find_node(modnm)
  665. if node is not None:
  666. logger.debug('Hidden import %r already found', modnm)
  667. else:
  668. logger.info("Analyzing hidden import %r", modnm)
  669. # ModuleGraph throws ImportError if import not found.
  670. try:
  671. nodes = self.import_hook(modnm)
  672. assert len(nodes) == 1
  673. node = nodes[0]
  674. except ImportError:
  675. logger.error("Hidden import %r not found", modnm)
  676. continue
  677. # Create references from the top script to the hidden import, even if found otherwise. Do not waste time
  678. # checking whether it is actually added by this (test-) script.
  679. self.add_edge(self._top_script_node, node)
  680. def get_code_using(self, module: str) -> dict:
  681. """
  682. Find modules that import a given **module**.
  683. """
  684. co_dict = {}
  685. pure_python_module_types = PURE_PYTHON_MODULE_TYPES | {
  686. 'Script',
  687. }
  688. node = self.find_node(module)
  689. if node:
  690. referrers = self.incoming(node)
  691. for r in referrers:
  692. # Under python 3.7 and earlier, if `module` is added to hidden imports, one of referrers ends up being
  693. # None, causing #3825. Work around it.
  694. if r is None:
  695. continue
  696. # Ensure that modulegraph objects have 'code' attribute.
  697. if type(r).__name__ not in pure_python_module_types:
  698. continue
  699. identifier = r.identifier
  700. if identifier == module or identifier.startswith(module + '.'):
  701. # Skip self references or references from `modules`'s own submodules.
  702. continue
  703. # The code object may be None if referrer ends up shadowed by eponymous directory that ends up treated
  704. # as a namespace package. See #6873 for an example.
  705. if r.code is None:
  706. continue
  707. co_dict[r.identifier] = r.code
  708. return co_dict
  709. def metadata_required(self) -> set:
  710. """
  711. Collect metadata for all packages that appear to need it.
  712. """
  713. # List every function that we can think of which is known to require metadata.
  714. out = set()
  715. out |= self._metadata_from(
  716. "pkg_resources",
  717. ["get_distribution"], # Requires metadata for one distribution.
  718. ["require"], # Requires metadata for all dependencies.
  719. )
  720. # importlib.metadata is often `import ... as` aliased to importlib_metadata for compatibility with < py38.
  721. # Assume both are valid.
  722. for importlib_metadata in ["importlib.metadata", "importlib_metadata"]:
  723. out |= self._metadata_from(
  724. importlib_metadata,
  725. ["metadata", "distribution", "version", "files", "requires"],
  726. [],
  727. )
  728. return out
  729. def _metadata_from(self, package, methods=(), recursive_methods=()) -> set:
  730. """
  731. Collect metadata whose requirements are implied by given function names.
  732. Args:
  733. package:
  734. The module name that must be imported in a source file to trigger the search.
  735. methods:
  736. Function names from **package** which take a distribution name as an argument and imply that metadata
  737. is required for that distribution.
  738. recursive_methods:
  739. Like **methods** but also implies that a distribution's dependencies' metadata must be collected too.
  740. Returns:
  741. Required metadata in hook data ``(source, dest)`` format as returned by
  742. :func:`PyInstaller.utils.hooks.copy_metadata()`.
  743. Scan all source code to be included for usage of particular *key* functions which imply that that code will
  744. require metadata for some distribution (which may not be its own) at runtime. In the case of a match,
  745. collect the required metadata.
  746. """
  747. from PyInstaller.utils.hooks import copy_metadata
  748. from PyInstaller.compat import importlib_metadata
  749. # Generate sets of possible function names to search for.
  750. need_metadata = set()
  751. need_recursive_metadata = set()
  752. for method in methods:
  753. need_metadata.update(bytecode.any_alias(package + "." + method))
  754. for method in recursive_methods:
  755. need_recursive_metadata.update(bytecode.any_alias(package + "." + method))
  756. out = set()
  757. for name, code in self.get_code_using(package).items():
  758. for calls in bytecode.recursive_function_calls(code).values():
  759. for function_name, args in calls:
  760. # Only consider function calls taking one argument.
  761. if len(args) != 1:
  762. continue
  763. package = args[0]
  764. try:
  765. if function_name in need_metadata:
  766. out.update(copy_metadata(package))
  767. elif function_name in need_recursive_metadata:
  768. out.update(copy_metadata(package, recursive=True))
  769. except importlib_metadata.PackageNotFoundError:
  770. # Currently, we opt to silently skip over missing metadata.
  771. continue
  772. return out
  773. def get_collected_packages(self) -> list:
  774. """
  775. Return the list of collected python packages.
  776. """
  777. # `node.identifier` might be an instance of `modulegraph.Alias`, hence explicit conversion to `str`.
  778. return [
  779. str(node.identifier) for node in self.iter_graph(start=self._top_script_node)
  780. if type(node).__name__ == 'Package'
  781. ]
  782. def make_hook_binaries_toc(self) -> list:
  783. """
  784. Return the TOC list of binaries collected by hooks."
  785. """
  786. toc = []
  787. for node in self.iter_graph(start=self._top_script_node):
  788. module_name = str(node.identifier)
  789. for dest_name, src_name in self._additional_files_cache.binaries(module_name):
  790. toc.append((dest_name, src_name, 'BINARY'))
  791. return toc
  792. def make_hook_datas_toc(self) -> list:
  793. """
  794. Return the TOC list of data files collected by hooks."
  795. """
  796. toc = []
  797. for node in self.iter_graph(start=self._top_script_node):
  798. module_name = str(node.identifier)
  799. for dest_name, src_name in self._additional_files_cache.datas(module_name):
  800. toc.append((dest_name, src_name, 'DATA'))
  801. return toc
  802. _cached_module_graph_ = None
  803. def initialize_modgraph(excludes=(), user_hook_dirs=()):
  804. """
  805. Create the cached module graph.
  806. This function might appear weird but is necessary for speeding up test runtime because it allows caching basic
  807. ModuleGraph object that gets created for 'base_library.zip'.
  808. Parameters
  809. ----------
  810. excludes : list
  811. List of the fully-qualified names of all modules to be "excluded" and hence _not_ frozen into the executable.
  812. user_hook_dirs : list
  813. List of the absolute paths of all directories containing user-defined hooks for the current application or
  814. `None` if no such directories were specified.
  815. Returns
  816. ----------
  817. PyiModuleGraph
  818. Module graph with core dependencies.
  819. """
  820. # Normalize parameters to ensure tuples and make comparison work.
  821. user_hook_dirs = user_hook_dirs or ()
  822. excludes = excludes or ()
  823. # Ensure that __main__ is always excluded from the modulegraph, to prevent accidentally pulling PyInstaller itself
  824. # into the modulegraph. This seems to happen on Windows, because modulegraph is able to resolve `__main__` as
  825. # `.../PyInstaller.exe/__main__.py` and analyze it. The `__main__` has a different meaning during analysis compared
  826. # to the program run-time, when it refers to the program's entry-point (which would always be part of the
  827. # modulegraph anyway, by virtue of being the starting point of the analysis).
  828. if "__main__" not in excludes:
  829. excludes += ("__main__",)
  830. # If there is a graph cached with the same excludes, reuse it. See ``PyiModulegraph._reset()`` for what is
  831. # reset. This cache is used primarily to speed up the test-suite. Fixture `pyi_modgraph` calls this function with
  832. # empty excludes, creating a graph suitable for the huge majority of tests.
  833. global _cached_module_graph_
  834. if _cached_module_graph_ and _cached_module_graph_._excludes == excludes:
  835. logger.info('Reusing cached module dependency graph...')
  836. graph = deepcopy(_cached_module_graph_)
  837. graph._reset(user_hook_dirs)
  838. return graph
  839. logger.info('Initializing module dependency graph...')
  840. # Construct the initial module graph by analyzing all import statements.
  841. graph = PyiModuleGraph(
  842. HOMEPATH,
  843. excludes=excludes,
  844. # get_implies() are hidden imports known by modulgraph.
  845. implies=get_implies(),
  846. user_hook_dirs=user_hook_dirs,
  847. )
  848. if not _cached_module_graph_:
  849. # Only cache the first graph, see above for explanation.
  850. logger.info('Caching module dependency graph...')
  851. # cache a deep copy of the graph
  852. _cached_module_graph_ = deepcopy(graph)
  853. # Clear data which does not need to be copied from the cached graph since it will be reset by
  854. # ``PyiModulegraph._reset()`` anyway.
  855. _cached_module_graph_._hooks = None
  856. _cached_module_graph_._hooks_pre_safe_import_module = None
  857. _cached_module_graph_._hooks_pre_find_module_path = None
  858. return graph
  859. def get_bootstrap_modules():
  860. """
  861. Get TOC with the bootstrapping modules and their dependencies.
  862. :return: TOC with modules
  863. """
  864. # Import 'struct' modules to get real paths to module file names.
  865. mod_struct = __import__('struct')
  866. # Basic modules necessary for the bootstrap process.
  867. loader_mods = list()
  868. loaderpath = os.path.join(HOMEPATH, 'PyInstaller', 'loader')
  869. # On some platforms (Windows, Debian/Ubuntu) '_struct' and zlib modules are built-in modules (linked statically)
  870. # and thus does not have attribute __file__. 'struct' module is required for reading Python bytecode from
  871. # executable. 'zlib' is required to decompress this bytecode.
  872. for mod_name in ['_struct', 'zlib']:
  873. mod = __import__(mod_name) # C extension.
  874. if hasattr(mod, '__file__'):
  875. mod_file = os.path.abspath(mod.__file__)
  876. # Resolve full destination name for extension, diverting it into python3.x/lib-dynload directory if
  877. # necessary (to match behavior for extension collection introduced in #5604).
  878. mod_dest = destination_name_for_extension(mod_name, mod_file, 'EXTENSION')
  879. loader_mods.append((mod_dest, mod_file, 'EXTENSION'))
  880. loader_mods.append(('struct', os.path.abspath(mod_struct.__file__), 'PYMODULE'))
  881. # Loader/bootstrap modules.
  882. # NOTE: These modules should be kept simple without any complicated dependencies.
  883. loader_mods += [
  884. ('pyimod01_archive', os.path.join(loaderpath, 'pyimod01_archive.py'), 'PYMODULE'),
  885. ('pyimod02_importers', os.path.join(loaderpath, 'pyimod02_importers.py'), 'PYMODULE'),
  886. ('pyimod03_ctypes', os.path.join(loaderpath, 'pyimod03_ctypes.py'), 'PYMODULE'),
  887. ]
  888. if is_win:
  889. loader_mods.append(('pyimod04_pywin32', os.path.join(loaderpath, 'pyimod04_pywin32.py'), 'PYMODULE'))
  890. # The bootstrap script
  891. loader_mods.append(('pyiboot01_bootstrap', os.path.join(loaderpath, 'pyiboot01_bootstrap.py'), 'PYSOURCE'))
  892. return loader_mods