analysis.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2022, 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 re
  34. import sys
  35. import traceback
  36. from collections import defaultdict
  37. from copy import deepcopy
  38. from PyInstaller import HOMEPATH, PACKAGEPATH, compat
  39. from PyInstaller import log as logging
  40. from PyInstaller.building.datastruct import TOC
  41. from PyInstaller.compat import (
  42. BAD_MODULE_TYPES, BINARY_MODULE_TYPES, MODULE_TYPES_TO_TOC_DICT, PURE_PYTHON_MODULE_TYPES, PY3_BASE_MODULES,
  43. VALID_MODULE_TYPES, importlib_load_source
  44. )
  45. from PyInstaller.depend import bytecode
  46. from PyInstaller.depend.imphook import AdditionalFilesCache, ModuleHookCache
  47. from PyInstaller.depend.imphookapi import (PreFindModulePathAPI, PreSafeImportModuleAPI)
  48. from PyInstaller.lib.modulegraph.find_modules import get_implies
  49. from PyInstaller.lib.modulegraph.modulegraph import ModuleGraph
  50. from PyInstaller.log import DEBUG, INFO, TRACE
  51. from PyInstaller.utils.hooks import collect_submodules, is_package
  52. logger = logging.getLogger(__name__)
  53. class PyiModuleGraph(ModuleGraph):
  54. """
  55. Directed graph whose nodes represent modules and edges represent dependencies between these modules.
  56. This high-level subclass wraps the lower-level `ModuleGraph` class with support for graph and runtime hooks.
  57. While each instance of `ModuleGraph` represents a set of disconnected trees, each instance of this class *only*
  58. represents a single connected tree whose root node is the Python script originally passed by the user on the
  59. command line. For that reason, while there may (and typically do) exist more than one `ModuleGraph` instance,
  60. there typically exists only a singleton instance of this class.
  61. Attributes
  62. ----------
  63. _hooks : ModuleHookCache
  64. Dictionary mapping the fully-qualified names of all modules with normal (post-graph) hooks to the absolute paths
  65. of such hooks. See the the `_find_module_path()` method for details.
  66. _hooks_pre_find_module_path : ModuleHookCache
  67. Dictionary mapping the fully-qualified names of all modules with pre-find module path hooks to the absolute
  68. paths of such hooks. See the the `_find_module_path()` method for details.
  69. _hooks_pre_safe_import_module : ModuleHookCache
  70. Dictionary mapping the fully-qualified names of all modules with pre-safe import module hooks to the absolute
  71. paths of such hooks. See the `_safe_import_module()` method for details.
  72. _user_hook_dirs : list
  73. List of the absolute paths of all directories containing user-defined hooks for the current application.
  74. _excludes : list
  75. List of module names to be excluded when searching for dependencies.
  76. _additional_files_cache : AdditionalFilesCache
  77. Cache of all external dependencies (e.g., binaries, datas) listed in hook scripts for imported modules.
  78. _base_modules: list
  79. Dependencies for `base_library.zip` (which remain the same for every executable).
  80. """
  81. # Note: these levels are completely arbitrary and may be adjusted if needed.
  82. LOG_LEVEL_MAPPING = {0: INFO, 1: DEBUG, 2: TRACE, 3: TRACE, 4: TRACE}
  83. def __init__(self, pyi_homepath, user_hook_dirs=(), excludes=(), **kwargs):
  84. super().__init__(excludes=excludes, **kwargs)
  85. # Homepath to the place where is PyInstaller located.
  86. self._homepath = pyi_homepath
  87. # modulegraph Node for the main python script that is analyzed by PyInstaller.
  88. self._top_script_node = None
  89. # Absolute paths of all user-defined hook directories.
  90. self._excludes = excludes
  91. self._reset(user_hook_dirs)
  92. self._analyze_base_modules()
  93. def _reset(self, user_hook_dirs):
  94. """
  95. Reset for another set of scripts. This is primary required for running the test-suite.
  96. """
  97. self._top_script_node = None
  98. self._additional_files_cache = AdditionalFilesCache()
  99. # Command line, Entry Point, and then builtin hook dirs.
  100. self._user_hook_dirs = [*user_hook_dirs, os.path.join(PACKAGEPATH, 'hooks')]
  101. # Hook-specific lookup tables. These need to reset when reusing cached PyiModuleGraph to avoid hooks to refer to
  102. # files or data from another test-case.
  103. logger.info('Caching module graph hooks...')
  104. self._hooks = self._cache_hooks("")
  105. self._hooks_pre_safe_import_module = self._cache_hooks('pre_safe_import_module')
  106. self._hooks_pre_find_module_path = self._cache_hooks('pre_find_module_path')
  107. # Search for run-time hooks in all hook directories.
  108. self._available_rthooks = defaultdict(list)
  109. for uhd in self._user_hook_dirs:
  110. uhd_path = os.path.abspath(os.path.join(uhd, 'rthooks.dat'))
  111. try:
  112. with open(uhd_path, 'r', encoding='utf-8') as f:
  113. rthooks = ast.literal_eval(f.read())
  114. except FileNotFoundError:
  115. # Ignore if this hook path doesn't have run-time hooks.
  116. continue
  117. except Exception as e:
  118. logger.error('Unable to read run-time hooks from %r: %s' % (uhd_path, e))
  119. continue
  120. self._merge_rthooks(rthooks, uhd, uhd_path)
  121. # Convert back to a standard dict.
  122. self._available_rthooks = dict(self._available_rthooks)
  123. def _merge_rthooks(self, rthooks, uhd, uhd_path):
  124. """
  125. The expected data structure for a run-time hook file is a Python dictionary of type ``Dict[str, List[str]]``,
  126. where the dictionary keys are module names and the sequence strings are Python file names.
  127. Check then merge this data structure, updating the file names to be absolute.
  128. """
  129. # Check that the root element is a dict.
  130. assert isinstance(rthooks, dict), 'The root element in %s must be a dict.' % uhd_path
  131. for module_name, python_file_name_list in rthooks.items():
  132. # Ensure the key is a string.
  133. assert isinstance(module_name, compat.string_types), \
  134. '%s must be a dict whose keys are strings; %s is not a string.' % (uhd_path, module_name)
  135. # Ensure the value is a list.
  136. assert isinstance(python_file_name_list, list), \
  137. 'The value of %s key %s must be a list.' % (uhd_path, module_name)
  138. if module_name in self._available_rthooks:
  139. logger.warning(
  140. 'Runtime hooks for %s have already been defined. Skipping the runtime hooks for %s that are '
  141. 'defined in %s.', module_name, module_name, os.path.join(uhd, 'rthooks')
  142. )
  143. # Skip this module
  144. continue
  145. # Merge this with existing run-time hooks.
  146. for python_file_name in python_file_name_list:
  147. # Ensure each item in the list is a string.
  148. assert isinstance(python_file_name, compat.string_types), \
  149. '%s key %s, item %r must be a string.' % (uhd_path, module_name, python_file_name)
  150. # Transform it into an absolute path.
  151. abs_path = os.path.join(uhd, 'rthooks', python_file_name)
  152. # Make sure this file exists.
  153. assert os.path.exists(abs_path), \
  154. 'In %s, key %s, the file %r expected to be located at %r does not exist.' % \
  155. (uhd_path, module_name, python_file_name, abs_path)
  156. # Merge it.
  157. self._available_rthooks[module_name].append(abs_path)
  158. @staticmethod
  159. def _findCaller(*args, **kwargs):
  160. # Used to add an additional stack-frame above logger.findCaller. findCaller expects the caller to be three
  161. # stack-frames above itself.
  162. return logger.findCaller(*args, **kwargs)
  163. def msg(self, level, s, *args):
  164. """
  165. Print a debug message with the given level.
  166. 1. Map the msg log level to a logger log level.
  167. 2. Generate the message format (the same format as ModuleGraph)
  168. 3. Find the caller, which findCaller expects three stack-frames above itself:
  169. [3] caller -> [2] msg (here) -> [1] _findCaller -> [0] logger.findCaller
  170. 4. Create a logRecord with the caller's information.
  171. 5. Handle the logRecord.
  172. """
  173. try:
  174. level = self.LOG_LEVEL_MAPPING[level]
  175. except KeyError:
  176. return
  177. if not logger.isEnabledFor(level):
  178. return
  179. msg = "%s %s" % (s, ' '.join(map(repr, args)))
  180. try:
  181. fn, lno, func, sinfo = self._findCaller()
  182. except ValueError: # pragma: no cover
  183. fn, lno, func, sinfo = "(unknown file)", 0, "(unknown function)", None
  184. record = logger.makeRecord(logger.name, level, fn, lno, msg, [], None, func, None, sinfo)
  185. logger.handle(record)
  186. # Set logging methods so that the stack is correctly detected.
  187. msgin = msg
  188. msgout = msg
  189. def _cache_hooks(self, hook_type):
  190. """
  191. Get a cache of all hooks of the passed type.
  192. The cache will include all official hooks defined by the PyInstaller codebase _and_ all unofficial hooks
  193. defined for the current application.
  194. Parameters
  195. ----------
  196. hook_type : str
  197. Type of hooks to be cached, equivalent to the basename of the subpackage of the `PyInstaller.hooks`
  198. package containing such hooks (e.g., `post_create_package` for post-create package hooks).
  199. """
  200. # Cache of this type of hooks.
  201. hook_dirs = []
  202. for user_hook_dir in self._user_hook_dirs:
  203. # Absolute path of the user-defined subdirectory of this hook type. If this directory exists, add it to the
  204. # list to be cached.
  205. user_hook_type_dir = os.path.join(user_hook_dir, hook_type)
  206. if os.path.isdir(user_hook_type_dir):
  207. hook_dirs.append(user_hook_type_dir)
  208. return ModuleHookCache(self, hook_dirs)
  209. def _analyze_base_modules(self):
  210. """
  211. Analyze dependencies of the the modules in base_library.zip.
  212. """
  213. logger.info('Analyzing base_library.zip ...')
  214. required_mods = []
  215. # Collect submodules from required modules in base_library.zip.
  216. for m in PY3_BASE_MODULES:
  217. if is_package(m):
  218. required_mods += collect_submodules(m)
  219. else:
  220. required_mods.append(m)
  221. # Initialize ModuleGraph.
  222. self._base_modules = [mod for req in required_mods for mod in self.import_hook(req)]
  223. def add_script(self, pathname, caller=None):
  224. """
  225. Wrap the parent's 'run_script' method and create graph from the first script in the analysis, and save its
  226. node to use as the "caller" node for all others. This gives a connected graph rather than a collection of
  227. unrelated trees.
  228. """
  229. if self._top_script_node is None:
  230. # Remember the node for the first script.
  231. try:
  232. self._top_script_node = super().add_script(pathname)
  233. except SyntaxError:
  234. print("\nSyntax error in", pathname, file=sys.stderr)
  235. formatted_lines = traceback.format_exc().splitlines(True)
  236. print(*formatted_lines[-4:], file=sys.stderr)
  237. sys.exit(1)
  238. # Create references from the top script to the base_modules in graph.
  239. for node in self._base_modules:
  240. self.add_edge(self._top_script_node, node)
  241. # Return top-level script node.
  242. return self._top_script_node
  243. else:
  244. if not caller:
  245. # Defaults to as any additional script is called from the top-level script.
  246. caller = self._top_script_node
  247. return super().add_script(pathname, caller=caller)
  248. def process_post_graph_hooks(self, analysis):
  249. """
  250. For each imported module, run this module's post-graph hooks if any.
  251. Parameters
  252. ----------
  253. analysis: build_main.Analysis
  254. The Analysis that calls the hooks
  255. """
  256. # For each iteration of the infinite "while" loop below:
  257. #
  258. # 1. All hook() functions defined in cached hooks for imported modules are called. This may result in new
  259. # modules being imported (e.g., as hidden imports) that were ignored earlier in the current iteration: if
  260. # this is the case, all hook() functions defined in cached hooks for these modules will be called by the next
  261. # iteration.
  262. # 2. All cached hooks whose hook() functions were called are removed from this cache. If this cache is empty, no
  263. # hook() functions will be called by the next iteration and this loop will be terminated.
  264. # 3. If no hook() functions were called, this loop is terminated.
  265. logger.info('Processing module hooks...')
  266. while True:
  267. # Set of the names of all imported modules whose post-graph hooks are run by this iteration, preventing the
  268. # next iteration from re- running these hooks. If still empty at the end of this iteration, no post-graph
  269. # hooks were run; thus, this loop will be terminated.
  270. hooked_module_names = set()
  271. # For each remaining hookable module and corresponding hooks...
  272. for module_name, module_hooks in self._hooks.items():
  273. # Graph node for this module if imported or "None" otherwise.
  274. module_node = self.find_node(module_name, create_nspkg=False)
  275. # If this module has not been imported, temporarily ignore it. This module is retained in the cache, as
  276. # a subsequently run post-graph hook could import this module as a hidden import.
  277. if module_node is None:
  278. continue
  279. # If this module is unimportable, permanently ignore it.
  280. if type(module_node).__name__ not in VALID_MODULE_TYPES:
  281. hooked_module_names.add(module_name)
  282. continue
  283. # For each hook script for this module...
  284. for module_hook in module_hooks:
  285. # Run this script's post-graph hook.
  286. module_hook.post_graph(analysis)
  287. # Cache all external dependencies listed by this script after running this hook, which could add
  288. # dependencies.
  289. self._additional_files_cache.add(module_name, module_hook.binaries, module_hook.datas)
  290. # Prevent this module's hooks from being run again.
  291. hooked_module_names.add(module_name)
  292. # Prevent all post-graph hooks run above from being run again by the next iteration.
  293. self._hooks.remove_modules(*hooked_module_names)
  294. # If no post-graph hooks were run, terminate iteration.
  295. if not hooked_module_names:
  296. break
  297. def _safe_import_module(self, module_basename, module_name, parent_package):
  298. """
  299. Create a new graph node for the module with the passed name under the parent package signified by the passed
  300. graph node.
  301. This method wraps the superclass method with support for pre-import module hooks. If such a hook exists for
  302. this module (e.g., a script `PyInstaller.hooks.hook-{module_name}` containing a function
  303. `pre_safe_import_module()`), that hook will be run _before_ the superclass method is called.
  304. Pre-Safe-Import-Hooks are performed just *prior* to importing the module. When running the hook, the modules
  305. parent package has already been imported and ti's `__path__` is set up. But the module is just about to be
  306. imported.
  307. See the superclass method for description of parameters and return value.
  308. """
  309. # If this module has pre-safe import module hooks, run these first.
  310. if module_name in self._hooks_pre_safe_import_module:
  311. # For the absolute path of each such hook...
  312. for hook in self._hooks_pre_safe_import_module[module_name]:
  313. # Dynamically import this hook as a fabricated module.
  314. logger.info('Processing pre-safe import module hook %s from %r.', module_name, hook.hook_filename)
  315. hook_module_name = 'PyInstaller_hooks_pre_safe_import_module_' + module_name.replace('.', '_')
  316. hook_module = importlib_load_source(hook_module_name, hook.hook_filename)
  317. # Object communicating changes made by this hook back to us.
  318. hook_api = PreSafeImportModuleAPI(
  319. module_graph=self,
  320. module_basename=module_basename,
  321. module_name=module_name,
  322. parent_package=parent_package,
  323. )
  324. # Run this hook, passed this object.
  325. if not hasattr(hook_module, 'pre_safe_import_module'):
  326. raise NameError('pre_safe_import_module() function not defined by hook %r.' % hook_module)
  327. hook_module.pre_safe_import_module(hook_api)
  328. # Respect method call changes requested by this hook.
  329. module_basename = hook_api.module_basename
  330. module_name = hook_api.module_name
  331. # Prevent subsequent calls from rerunning these hooks.
  332. del self._hooks_pre_safe_import_module[module_name]
  333. # Call the superclass method.
  334. return super()._safe_import_module(module_basename, module_name, parent_package)
  335. def _find_module_path(self, fullname, module_name, search_dirs):
  336. """
  337. Get a 3-tuple detailing the physical location of the module with the passed name if that module exists _or_
  338. raise `ImportError` otherwise.
  339. This method wraps the superclass method with support for pre-find module path hooks. If such a hook exists
  340. for this module (e.g., a script `PyInstaller.hooks.hook-{module_name}` containing a function
  341. `pre_find_module_path()`), that hook will be run _before_ the superclass method is called.
  342. See superclass method for parameter and return value descriptions.
  343. """
  344. # If this module has pre-find module path hooks, run these first.
  345. if fullname in self._hooks_pre_find_module_path:
  346. # For the absolute path of each such hook...
  347. for hook in self._hooks_pre_find_module_path[fullname]:
  348. # Dynamically import this hook as a fabricated module.
  349. logger.info('Processing pre-find module path hook %s from %r.', fullname, hook.hook_filename)
  350. hook_fullname = 'PyInstaller_hooks_pre_find_module_path_' + fullname.replace('.', '_')
  351. hook_module = importlib_load_source(hook_fullname, hook.hook_filename)
  352. # Object communicating changes made by this hook back to us.
  353. hook_api = PreFindModulePathAPI(
  354. module_graph=self,
  355. module_name=fullname,
  356. search_dirs=search_dirs,
  357. )
  358. # Run this hook, passed this object.
  359. if not hasattr(hook_module, 'pre_find_module_path'):
  360. raise NameError('pre_find_module_path() function not defined by hook %r.' % hook_module)
  361. hook_module.pre_find_module_path(hook_api)
  362. # Respect method call changes requested by this hook.
  363. search_dirs = hook_api.search_dirs
  364. # Prevent subsequent calls from rerunning these hooks.
  365. del self._hooks_pre_find_module_path[fullname]
  366. # Call the superclass method.
  367. return super()._find_module_path(fullname, module_name, search_dirs)
  368. def get_code_objects(self):
  369. """
  370. Get code objects from ModuleGraph for pure Python modules. This allows to avoid writing .pyc/pyo files to hdd
  371. at later stage.
  372. :return: Dict with module name and code object.
  373. """
  374. code_dict = {}
  375. mod_types = PURE_PYTHON_MODULE_TYPES
  376. for node in self.iter_graph(start=self._top_script_node):
  377. # TODO This is terrible. To allow subclassing, types should never be directly compared. Use isinstance()
  378. # instead, which is safer, simpler, and accepts sets. Most other calls to type() in the codebase should also
  379. # be refactored to call isinstance() instead.
  380. # get node type e.g. Script
  381. mg_type = type(node).__name__
  382. if mg_type in mod_types:
  383. if node.code:
  384. code_dict[node.identifier] = node.code
  385. return code_dict
  386. def _make_toc(self, typecode=None, existing_TOC=None):
  387. """
  388. Return the name, path and type of selected nodes as a TOC, or appended to a TOC. The selection is via a list
  389. of PyInstaller TOC typecodes. If that list is empty we return the complete flattened graph as a TOC with the
  390. ModuleGraph note types in place of typecodes -- meant for debugging only. Normally we return ModuleGraph
  391. nodes whose types map to the requested PyInstaller typecode(s) as indicated in the MODULE_TYPES_TO_TOC_DICT.
  392. We use the ModuleGraph (really, ObjectGraph) flatten() method to scan all the nodes. This is patterned after
  393. ModuleGraph.report().
  394. """
  395. # Construct regular expression for matching modules that should be excluded because they are bundled in
  396. # base_library.zip.
  397. #
  398. # This expression matches the base module name, optionally followed by a period and then any number of
  399. # characters. This matches the module name and the fully qualified names of any of its submodules.
  400. regex_str = '(' + '|'.join(PY3_BASE_MODULES) + r')(\.|$)'
  401. module_filter = re.compile(regex_str)
  402. result = existing_TOC or TOC()
  403. for node in self.iter_graph(start=self._top_script_node):
  404. # Skip modules that are in base_library.zip.
  405. if module_filter.match(node.identifier):
  406. continue
  407. entry = self._node_to_toc(node, typecode)
  408. if entry is not None:
  409. # TOC.append the data. This checks for a pre-existing name and skips it if it exists.
  410. result.append(entry)
  411. return result
  412. def make_pure_toc(self):
  413. """
  414. Return all pure Python modules formatted as TOC.
  415. """
  416. # PyInstaller should handle special module types without code object.
  417. return self._make_toc(PURE_PYTHON_MODULE_TYPES)
  418. def make_binaries_toc(self, existing_toc):
  419. """
  420. Return all binary Python modules formatted as TOC.
  421. """
  422. return self._make_toc(BINARY_MODULE_TYPES, existing_toc)
  423. def make_missing_toc(self):
  424. """
  425. Return all MISSING Python modules formatted as TOC.
  426. """
  427. return self._make_toc(BAD_MODULE_TYPES)
  428. @staticmethod
  429. def _node_to_toc(node, typecode=None):
  430. # TODO This is terrible. Everything in Python has a type. It is nonsensical to even speak of "nodes [that] are
  431. # not typed." How would that even occur? After all, even "None" has a type! (It is "NoneType", for the curious.)
  432. # Remove this, please.
  433. # Get node type, e.g., Script
  434. mg_type = type(node).__name__
  435. assert mg_type is not None
  436. if typecode and not (mg_type in typecode):
  437. # Type is not a to be selected one, skip this one
  438. return None
  439. # Extract the identifier and a path if any.
  440. if mg_type == 'Script':
  441. # for Script nodes only, identifier is a whole path
  442. (name, ext) = os.path.splitext(node.filename)
  443. name = os.path.basename(name)
  444. elif mg_type == 'ExtensionPackage':
  445. # Package with __init__ module being an extension module. This needs to end up as e.g. 'mypkg/__init__.so'.
  446. # Convert the packages name ('mypkg') into the module name ('mypkg.__init__') *here* to keep special cases
  447. # away elsewhere (where the module name is converted to a filename).
  448. name = node.identifier + ".__init__"
  449. else:
  450. name = node.identifier
  451. path = node.filename if node.filename is not None else ''
  452. # Ensure name is really 'str'. Module graph might return object type 'modulegraph.Alias' which inherits fromm
  453. # 'str'. But 'marshal.dumps()' function is able to marshal only 'str'. Otherwise on Windows PyInstaller might
  454. # fail with message like:
  455. # ValueError: unmarshallable object
  456. name = str(name)
  457. # Translate to the corresponding TOC typecode.
  458. toc_type = MODULE_TYPES_TO_TOC_DICT[mg_type]
  459. return name, path, toc_type
  460. def nodes_to_toc(self, node_list, existing_TOC=None):
  461. """
  462. Given a list of nodes, create a TOC representing those nodes. This is mainly used to initialize a TOC of
  463. scripts with the ones that are runtime hooks. The process is almost the same as _make_toc(), but the caller
  464. guarantees the nodes are valid, so minimal checking.
  465. """
  466. result = existing_TOC or TOC()
  467. for node in node_list:
  468. result.append(self._node_to_toc(node))
  469. return result
  470. # Return true if the named item is in the graph as a BuiltinModule node. The passed name is a basename.
  471. def is_a_builtin(self, name):
  472. node = self.find_node(name)
  473. if node is None:
  474. return False
  475. return type(node).__name__ == 'BuiltinModule'
  476. def get_importers(self, name):
  477. """
  478. List all modules importing the module with the passed name.
  479. Returns a list of (identifier, DependencyIinfo)-tuples. If the names module has not yet been imported, this
  480. method returns an empty list.
  481. Parameters
  482. ----------
  483. name : str
  484. Fully-qualified name of the module to be examined.
  485. Returns
  486. ----------
  487. list
  488. List of (fully-qualified names, DependencyIinfo)-tuples of all modules importing the module with the passed
  489. fully-qualified name.
  490. """
  491. def get_importer_edge_data(importer):
  492. edge = self.graph.edge_by_node(importer, name)
  493. # edge might be None in case an AliasModule was added.
  494. if edge is not None:
  495. return self.graph.edge_data(edge)
  496. node = self.find_node(name)
  497. if node is None:
  498. return []
  499. _, importers = self.get_edges(node)
  500. importers = (importer.identifier for importer in importers if importer is not None)
  501. return [(importer, get_importer_edge_data(importer)) for importer in importers]
  502. # TODO: create a class from this function.
  503. def analyze_runtime_hooks(self, custom_runhooks):
  504. """
  505. Analyze custom run-time hooks and run-time hooks implied by found modules.
  506. :return : list of Graph nodes.
  507. """
  508. rthooks_nodes = []
  509. logger.info('Analyzing run-time hooks ...')
  510. # Process custom runtime hooks (from --runtime-hook options). The runtime hooks are order dependent. First hooks
  511. # in the list are executed first. Put their graph nodes at the head of the priority_scripts list Pyinstaller
  512. # defined rthooks and thus they are executed first.
  513. if custom_runhooks:
  514. for hook_file in custom_runhooks:
  515. logger.info("Including custom run-time hook %r", hook_file)
  516. hook_file = os.path.abspath(hook_file)
  517. # Not using "try" here because the path is supposed to exist, if it does not, the raised error will
  518. # explain.
  519. rthooks_nodes.append(self.add_script(hook_file))
  520. # Find runtime hooks that are implied by packages already imported. Get a temporary TOC listing all the scripts
  521. # and packages graphed so far. Assuming that runtime hooks apply only to modules and packages.
  522. temp_toc = self._make_toc(VALID_MODULE_TYPES)
  523. for (mod_name, path, typecode) in temp_toc:
  524. # Look if there is any run-time hook for given module.
  525. if mod_name in self._available_rthooks:
  526. # There could be several run-time hooks for a module.
  527. for abs_path in self._available_rthooks[mod_name]:
  528. logger.info("Including run-time hook %r", abs_path)
  529. rthooks_nodes.append(self.add_script(abs_path))
  530. return rthooks_nodes
  531. def add_hiddenimports(self, module_list):
  532. """
  533. Add hidden imports that are either supplied as CLI option --hidden-import=MODULENAME or as dependencies from
  534. some PyInstaller features when enabled (e.g., crypto feature).
  535. """
  536. assert self._top_script_node is not None
  537. # Analyze the script's hidden imports (named on the command line).
  538. for modnm in module_list:
  539. node = self.find_node(modnm)
  540. if node is not None:
  541. logger.debug('Hidden import %r already found', modnm)
  542. else:
  543. logger.info("Analyzing hidden import %r", modnm)
  544. # ModuleGraph throws ImportError if import not found.
  545. try:
  546. nodes = self.import_hook(modnm)
  547. assert len(nodes) == 1
  548. node = nodes[0]
  549. except ImportError:
  550. logger.error("Hidden import %r not found", modnm)
  551. continue
  552. # Create references from the top script to the hidden import, even if found otherwise. Do not waste time
  553. # checking whether it is actually added by this (test-) script.
  554. self.add_edge(self._top_script_node, node)
  555. def get_code_using(self, module: str) -> dict:
  556. """
  557. Find modules that import a given **module**.
  558. """
  559. co_dict = {}
  560. pure_python_module_types = PURE_PYTHON_MODULE_TYPES | {
  561. 'Script',
  562. }
  563. node = self.find_node(module)
  564. if node:
  565. referrers = self.incoming(node)
  566. for r in referrers:
  567. # Under python 3.7 and earlier, if `module` is added to hidden imports, one of referrers ends up being
  568. # None, causing #3825. Work around it.
  569. if r is None:
  570. continue
  571. # Ensure that modulegraph objects have 'code' attribute.
  572. if type(r).__name__ not in pure_python_module_types:
  573. continue
  574. identifier = r.identifier
  575. if identifier == module or identifier.startswith(module + '.'):
  576. # Skip self references or references from `modules`'s own submodules.
  577. continue
  578. co_dict[r.identifier] = r.code
  579. return co_dict
  580. def metadata_required(self) -> set:
  581. """
  582. Collect metadata for all packages that appear to need it.
  583. """
  584. # List every function that we can think of which is known to require metadata.
  585. out = set()
  586. out |= self._metadata_from(
  587. "pkg_resources",
  588. ["get_distribution"], # Requires metadata for one distribution.
  589. ["require"], # Requires metadata for all dependencies.
  590. )
  591. # importlib.metadata is often `import ... as` aliased to importlib_metadata for compatibility with < py38.
  592. # Assume both are valid.
  593. for importlib_metadata in ["importlib.metadata", "importlib_metadata"]:
  594. out |= self._metadata_from(
  595. importlib_metadata,
  596. ["metadata", "distribution", "version", "files", "requires"],
  597. [],
  598. )
  599. return out
  600. def _metadata_from(self, package, methods=(), recursive_methods=()) -> set:
  601. """
  602. Collect metadata whose requirements are implied by given function names.
  603. Args:
  604. package:
  605. The module name that must be imported in a source file to trigger the search.
  606. methods:
  607. Function names from **package** which take a distribution name as an argument and imply that metadata
  608. is required for that distribution.
  609. recursive_methods:
  610. Like **methods** but also implies that a distribution's dependencies' metadata must be collected too.
  611. Returns:
  612. Required metadata in hook data ``(source, dest)`` format as returned by
  613. :func:`PyInstaller.utils.hooks.copy_metadata()`.
  614. Scan all source code to be included for usage of particular *key* functions which imply that that code will
  615. require metadata for some distribution (which may not be its own) at runtime. In the case of a match,
  616. collect the required metadata.
  617. """
  618. from pkg_resources import DistributionNotFound
  619. from PyInstaller.utils.hooks import copy_metadata
  620. # Generate sets of possible function names to search for.
  621. need_metadata = set()
  622. need_recursive_metadata = set()
  623. for method in methods:
  624. need_metadata.update(bytecode.any_alias(package + "." + method))
  625. for method in recursive_methods:
  626. need_recursive_metadata.update(bytecode.any_alias(package + "." + method))
  627. out = set()
  628. for name, code in self.get_code_using(package).items():
  629. for calls in bytecode.recursive_function_calls(code).values():
  630. for function_name, args in calls:
  631. # Only consider function calls taking one argument.
  632. if len(args) != 1:
  633. continue
  634. package = args[0]
  635. try:
  636. if function_name in need_metadata:
  637. out.update(copy_metadata(package))
  638. elif function_name in need_recursive_metadata:
  639. out.update(copy_metadata(package, recursive=True))
  640. except DistributionNotFound:
  641. # Currently, we opt to silently skip over missing metadata.
  642. continue
  643. return out
  644. def get_collected_packages(self) -> list:
  645. """
  646. Return the list of collected python packages.
  647. """
  648. return [
  649. node.identifier for node in self.iter_graph(start=self._top_script_node) if type(node).__name__ == 'Package'
  650. ]
  651. _cached_module_graph_ = None
  652. def initialize_modgraph(excludes=(), user_hook_dirs=()):
  653. """
  654. Create the cached module graph.
  655. This function might appear weird but is necessary for speeding up test runtime because it allows caching basic
  656. ModuleGraph object that gets created for 'base_library.zip'.
  657. Parameters
  658. ----------
  659. excludes : list
  660. List of the fully-qualified names of all modules to be "excluded" and hence _not_ frozen into the executable.
  661. user_hook_dirs : list
  662. List of the absolute paths of all directories containing user-defined hooks for the current application or
  663. `None` if no such directories were specified.
  664. Returns
  665. ----------
  666. PyiModuleGraph
  667. Module graph with core dependencies.
  668. """
  669. # Normalize parameters to ensure tuples and make comparison work.
  670. user_hook_dirs = user_hook_dirs or ()
  671. excludes = excludes or ()
  672. # If there is a graph cached with the same excludes, reuse it. See ``PyiModulegraph._reset()`` for what is
  673. # reset. This cache is used primarily to speed up the test-suite. Fixture `pyi_modgraph` calls this function with
  674. # empty excludes, creating a graph suitable for the huge majority of tests.
  675. global _cached_module_graph_
  676. if _cached_module_graph_ and _cached_module_graph_._excludes == excludes:
  677. logger.info('Reusing cached module dependency graph...')
  678. graph = deepcopy(_cached_module_graph_)
  679. graph._reset(user_hook_dirs)
  680. return graph
  681. logger.info('Initializing module dependency graph...')
  682. # Construct the initial module graph by analyzing all import statements.
  683. graph = PyiModuleGraph(
  684. HOMEPATH,
  685. excludes=excludes,
  686. # get_implies() are hidden imports known by modulgraph.
  687. implies=get_implies(),
  688. user_hook_dirs=user_hook_dirs,
  689. )
  690. if not _cached_module_graph_:
  691. # Only cache the first graph, see above for explanation.
  692. logger.info('Caching module dependency graph...')
  693. # cache a deep copy of the graph
  694. _cached_module_graph_ = deepcopy(graph)
  695. # Clear data which does not need to be copied from the cached graph since it will be reset by
  696. # ``PyiModulegraph._reset()`` anyway.
  697. _cached_module_graph_._hooks = None
  698. _cached_module_graph_._hooks_pre_safe_import_module = None
  699. _cached_module_graph_._hooks_pre_find_module_path = None
  700. return graph
  701. def get_bootstrap_modules():
  702. """
  703. Get TOC with the bootstrapping modules and their dependencies.
  704. :return: TOC with modules
  705. """
  706. # Import 'struct' modules to get real paths to module file names.
  707. mod_struct = __import__('struct')
  708. # Basic modules necessary for the bootstrap process.
  709. loader_mods = TOC()
  710. loaderpath = os.path.join(HOMEPATH, 'PyInstaller', 'loader')
  711. # On some platforms (Windows, Debian/Ubuntu) '_struct' and zlib modules are built-in modules (linked statically)
  712. # and thus does not have attribute __file__. 'struct' module is required for reading Python bytecode from
  713. # executable. 'zlib' is required to decompress this bytecode.
  714. for mod_name in ['_struct', 'zlib']:
  715. mod = __import__(mod_name) # C extension.
  716. if hasattr(mod, '__file__'):
  717. mod_file = os.path.abspath(mod.__file__)
  718. if os.path.basename(os.path.dirname(mod_file)) == 'lib-dynload':
  719. # Divert extensions originating from python's lib-dynload directory, to match behavior of #5604.
  720. mod_name = os.path.join('lib-dynload', mod_name)
  721. loader_mods.append((mod_name, mod_file, 'EXTENSION'))
  722. # NOTE:These modules should be kept simple without any complicated dependencies.
  723. loader_mods += [
  724. ('struct', os.path.abspath(mod_struct.__file__), 'PYMODULE'),
  725. ('pyimod01_os_path', os.path.join(loaderpath, 'pyimod01_os_path.pyc'), 'PYMODULE'),
  726. ('pyimod02_archive', os.path.join(loaderpath, 'pyimod02_archive.pyc'), 'PYMODULE'),
  727. ('pyimod03_importers', os.path.join(loaderpath, 'pyimod03_importers.pyc'), 'PYMODULE'),
  728. ('pyimod04_ctypes', os.path.join(loaderpath, 'pyimod04_ctypes.pyc'), 'PYMODULE'),
  729. ('pyiboot01_bootstrap', os.path.join(loaderpath, 'pyiboot01_bootstrap.py'), 'PYSOURCE'),
  730. ]
  731. return loader_mods