analysis.py 41 KB

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