utils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. # --- functions for checking guts ---
  12. # NOTE: by GUTS it is meant intermediate files and data structures that PyInstaller creates for bundling files and
  13. # creating final executable.
  14. import fnmatch
  15. import glob
  16. import hashlib
  17. import os
  18. import os.path
  19. import pkgutil
  20. import platform
  21. import shutil
  22. import struct
  23. import sys
  24. from PyInstaller import compat
  25. from PyInstaller import log as logging
  26. from PyInstaller.compat import (EXTENSION_SUFFIXES, is_cygwin, is_darwin, is_py37, is_win)
  27. from PyInstaller.config import CONF
  28. from PyInstaller.depend import dylib
  29. from PyInstaller.depend.bindepend import match_binding_redirect
  30. from PyInstaller.utils import misc
  31. if is_win or is_cygwin:
  32. from PyInstaller.utils.win32 import versioninfo, winmanifest, winresource
  33. if is_darwin:
  34. import PyInstaller.utils.osx as osxutils
  35. logger = logging.getLogger(__name__)
  36. # -- Helpers for checking guts.
  37. #
  38. # NOTE: by _GUTS it is meant intermediate files and data structures that PyInstaller creates for bundling files and
  39. # creating final executable.
  40. def _check_guts_eq(attr, old, new, _last_build):
  41. """
  42. Rebuild is required if values differ.
  43. """
  44. if old != new:
  45. logger.info("Building because %s changed", attr)
  46. return True
  47. return False
  48. def _check_guts_toc_mtime(_attr, old, _toc, last_build, pyc=0):
  49. """
  50. Rebuild is required if mtimes of files listed in old toc are newer than last_build.
  51. If pyc=1, check for .py files as well.
  52. Use this for calculated/analysed values read from cache.
  53. """
  54. for nm, fnm, typ in old:
  55. if misc.mtime(fnm) > last_build:
  56. logger.info("Building because %s changed", fnm)
  57. return True
  58. elif pyc and misc.mtime(fnm[:-1]) > last_build:
  59. logger.info("Building because %s changed", fnm[:-1])
  60. return True
  61. return False
  62. def _check_guts_toc(attr, old, toc, last_build, pyc=0):
  63. """
  64. Rebuild is required if either toc content changed or mtimes of files listed in old toc are newer than last_build.
  65. If pyc=1, check for .py files as well.
  66. Use this for input parameters.
  67. """
  68. return _check_guts_eq(attr, old, toc, last_build) or _check_guts_toc_mtime(attr, old, toc, last_build, pyc=pyc)
  69. def add_suffix_to_extension(inm, fnm, typ):
  70. """
  71. Take a TOC entry (inm, fnm, typ) and adjust the inm for EXTENSION or DEPENDENCY to include the full library suffix.
  72. """
  73. if typ == 'EXTENSION':
  74. if fnm.endswith(inm):
  75. # If inm completely fits into end of the fnm, it has already been processed.
  76. return inm, fnm, typ
  77. # Change the dotted name into a relative path. This places C extensions in the Python-standard location.
  78. inm = inm.replace('.', os.sep)
  79. # In some rare cases extension might already contain a suffix. Skip it in this case.
  80. if os.path.splitext(inm)[1] not in EXTENSION_SUFFIXES:
  81. # Determine the base name of the file.
  82. base_name = os.path.basename(inm)
  83. assert '.' not in base_name
  84. # Use this file's existing extension. For extensions such as ``libzmq.cp36-win_amd64.pyd``, we cannot use
  85. # ``os.path.splitext``, which would give only the ```.pyd`` part of the extension.
  86. inm = inm + os.path.basename(fnm)[len(base_name):]
  87. elif typ == 'DEPENDENCY':
  88. # Use the suffix from the filename.
  89. # TODO: verify what extensions are by DEPENDENCIES.
  90. binext = os.path.splitext(fnm)[1]
  91. if not os.path.splitext(inm)[1] == binext:
  92. inm = inm + binext
  93. return inm, fnm, typ
  94. def applyRedirects(manifest, redirects):
  95. """
  96. Apply the binding redirects specified by 'redirects' to the dependent assemblies of 'manifest'.
  97. :param manifest:
  98. :type manifest:
  99. :param redirects:
  100. :type redirects:
  101. :return:
  102. :rtype:
  103. """
  104. redirecting = False
  105. for binding in redirects:
  106. for dep in manifest.dependentAssemblies:
  107. if match_binding_redirect(dep, binding):
  108. logger.info("Redirecting %s version %s -> %s", binding.name, dep.version, binding.newVersion)
  109. dep.version = binding.newVersion
  110. redirecting = True
  111. return redirecting
  112. def checkCache(
  113. fnm,
  114. strip=False,
  115. upx=False,
  116. upx_exclude=None,
  117. dist_nm=None,
  118. target_arch=None,
  119. codesign_identity=None,
  120. entitlements_file=None
  121. ):
  122. """
  123. Cache prevents preprocessing binary files again and again.
  124. 'dist_nm' Filename relative to dist directory. We need it on Mac to determine level of paths for @loader_path like
  125. '@loader_path/../../' for qt4 plugins.
  126. """
  127. from PyInstaller.config import CONF
  128. # On Mac OS, a cache is required anyway to keep the libaries with relative install names.
  129. # Caching on Mac OS does not work since we need to modify binary headers to use relative paths to dll depencies and
  130. # starting with '@loader_path'.
  131. if not strip and not upx and not is_darwin and not is_win:
  132. return fnm
  133. if dist_nm is not None and ":" in dist_nm:
  134. # A file embedded in another PyInstaller build via multipackage.
  135. # No actual file exists to process.
  136. return fnm
  137. if strip:
  138. strip = True
  139. else:
  140. strip = False
  141. upx_exclude = upx_exclude or []
  142. upx = (upx and (is_win or is_cygwin) and os.path.normcase(os.path.basename(fnm)) not in upx_exclude)
  143. # Load cache index.
  144. # Make cachedir per Python major/minor version.
  145. # This allows parallel building of executables with different Python versions as one user.
  146. pyver = 'py%d%s' % (sys.version_info[0], sys.version_info[1])
  147. arch = platform.architecture()[0]
  148. cachedir = os.path.join(CONF['cachedir'], 'bincache%d%d_%s_%s' % (strip, upx, pyver, arch))
  149. if target_arch:
  150. cachedir = os.path.join(cachedir, target_arch)
  151. if is_darwin:
  152. # Separate by codesign identity
  153. if codesign_identity:
  154. # Compute hex digest of codesign identity string to prevent issues with invalid characters.
  155. csi_hash = hashlib.sha256(codesign_identity.encode('utf-8'))
  156. cachedir = os.path.join(cachedir, csi_hash.hexdigest())
  157. else:
  158. cachedir = os.path.join(cachedir, 'adhoc') # ad-hoc signing
  159. # Separate by entitlements
  160. if entitlements_file:
  161. # Compute hex digest of entitlements file contents
  162. with open(entitlements_file, 'rb') as fp:
  163. ef_hash = hashlib.sha256(fp.read())
  164. cachedir = os.path.join(cachedir, ef_hash.hexdigest())
  165. else:
  166. cachedir = os.path.join(cachedir, 'no-entitlements')
  167. if not os.path.exists(cachedir):
  168. os.makedirs(cachedir)
  169. cacheindexfn = os.path.join(cachedir, "index.dat")
  170. if os.path.exists(cacheindexfn):
  171. try:
  172. cache_index = misc.load_py_data_struct(cacheindexfn)
  173. except Exception:
  174. # Tell the user they may want to fix their cache... However, do not delete it for them; if it keeps getting
  175. # corrupted, we will never find out.
  176. logger.warning("PyInstaller bincache may be corrupted; use pyinstaller --clean to fix it.")
  177. raise
  178. else:
  179. cache_index = {}
  180. # Verify that the file we are looking for is present in the cache. Use the dist_mn if given to avoid different
  181. # extension modules sharing the same basename get corrupted.
  182. if dist_nm:
  183. basenm = os.path.normcase(dist_nm)
  184. else:
  185. basenm = os.path.normcase(os.path.basename(fnm))
  186. # Binding redirects should be taken into account to see if the file needs to be reprocessed. The redirects may
  187. # change if the versions of dependent manifests change due to system updates.
  188. redirects = CONF.get('binding_redirects', [])
  189. digest = cacheDigest(fnm, redirects)
  190. cachedfile = os.path.join(cachedir, basenm)
  191. cmd = None
  192. if basenm in cache_index:
  193. if digest != cache_index[basenm]:
  194. os.remove(cachedfile)
  195. else:
  196. return cachedfile
  197. # Optionally change manifest and its dependencies to private assemblies.
  198. if fnm.lower().endswith(".manifest") and (is_win or is_cygwin):
  199. manifest = winmanifest.Manifest()
  200. manifest.filename = fnm
  201. with open(fnm, "rb") as f:
  202. manifest.parse_string(f.read())
  203. if CONF.get('win_private_assemblies', False):
  204. if manifest.publicKeyToken:
  205. logger.info("Changing %s into private assembly", os.path.basename(fnm))
  206. manifest.publicKeyToken = None
  207. for dep in manifest.dependentAssemblies:
  208. # Exclude common-controls which is not bundled
  209. if dep.name != "Microsoft.Windows.Common-Controls":
  210. dep.publicKeyToken = None
  211. applyRedirects(manifest, redirects)
  212. manifest.writeprettyxml(cachedfile)
  213. return cachedfile
  214. if upx:
  215. if strip:
  216. fnm = checkCache(
  217. fnm,
  218. strip=True,
  219. upx=False,
  220. dist_nm=dist_nm,
  221. target_arch=target_arch,
  222. codesign_identity=codesign_identity,
  223. entitlements_file=entitlements_file
  224. )
  225. # We need to avoid using UPX with Windows DLLs that have Control Flow Guard enabled, as it breaks them.
  226. if (is_win or is_cygwin) and versioninfo.pefile_check_control_flow_guard(fnm):
  227. logger.info('Disabling UPX for %s due to CFG!', fnm)
  228. elif misc.is_file_qt_plugin(fnm):
  229. logger.info('Disabling UPX for %s due to it being a Qt plugin!', fnm)
  230. else:
  231. bestopt = "--best"
  232. # FIXME: Linux builds of UPX do not seem to contain LZMA (they assert out).
  233. # A better configure-time check is due.
  234. if CONF["hasUPX"] >= (3,) and os.name == "nt":
  235. bestopt = "--lzma"
  236. upx_executable = "upx"
  237. if CONF.get('upx_dir'):
  238. upx_executable = os.path.join(CONF['upx_dir'], upx_executable)
  239. cmd = [upx_executable, bestopt, "-q", cachedfile]
  240. else:
  241. if strip:
  242. strip_options = []
  243. if is_darwin:
  244. # The default strip behavior breaks some shared libraries under Mac OS.
  245. strip_options = ["-S"] # -S = strip only debug symbols.
  246. cmd = ["strip"] + strip_options + [cachedfile]
  247. if not os.path.exists(os.path.dirname(cachedfile)):
  248. os.makedirs(os.path.dirname(cachedfile))
  249. # There are known some issues with 'shutil.copy2' on Mac OS 10.11 with copying st_flags. Issue #1650.
  250. # 'shutil.copy' copies also permission bits and it should be sufficient for PyInstaller's purposes.
  251. shutil.copy(fnm, cachedfile)
  252. # TODO: find out if this is still necessary when no longer using shutil.copy2()
  253. if hasattr(os, 'chflags'):
  254. # Some libraries on FreeBSD have immunable flag (libthr.so.3, for example). If this flag is preserved,
  255. # os.chmod() fails with: OSError: [Errno 1] Operation not permitted.
  256. try:
  257. os.chflags(cachedfile, 0)
  258. except OSError:
  259. pass
  260. os.chmod(cachedfile, 0o755)
  261. if os.path.splitext(fnm.lower())[1] in (".pyd", ".dll") and (is_win or is_cygwin):
  262. # When shared assemblies are bundled into the app, they may optionally be changed into private assemblies.
  263. try:
  264. res = winmanifest.GetManifestResources(os.path.abspath(cachedfile))
  265. except winresource.pywintypes.error as e:
  266. if e.args[0] == winresource.ERROR_BAD_EXE_FORMAT:
  267. # Not a win32 PE file
  268. pass
  269. else:
  270. logger.error(os.path.abspath(cachedfile))
  271. raise
  272. else:
  273. if winmanifest.RT_MANIFEST in res and len(res[winmanifest.RT_MANIFEST]):
  274. for name in res[winmanifest.RT_MANIFEST]:
  275. for language in res[winmanifest.RT_MANIFEST][name]:
  276. try:
  277. manifest = winmanifest.Manifest()
  278. manifest.filename = ":".join([
  279. cachedfile, str(winmanifest.RT_MANIFEST),
  280. str(name), str(language)
  281. ])
  282. manifest.parse_string(res[winmanifest.RT_MANIFEST][name][language], False)
  283. except Exception:
  284. logger.error("Cannot parse manifest resource %s, =%s", name, language)
  285. logger.error("From file %s", cachedfile, exc_info=1)
  286. else:
  287. # optionally change manifest to private assembly
  288. private = CONF.get('win_private_assemblies', False)
  289. if private:
  290. if manifest.publicKeyToken:
  291. logger.info("Changing %s into a private assembly", os.path.basename(fnm))
  292. manifest.publicKeyToken = None
  293. # Change dep to private assembly
  294. for dep in manifest.dependentAssemblies:
  295. # Exclude common-controls which is not bundled
  296. if dep.name != "Microsoft.Windows.Common-Controls":
  297. dep.publicKeyToken = None
  298. redirecting = applyRedirects(manifest, redirects)
  299. if redirecting or private:
  300. try:
  301. manifest.update_resources(os.path.abspath(cachedfile), [name], [language])
  302. except Exception:
  303. logger.error(os.path.abspath(cachedfile))
  304. raise
  305. if cmd:
  306. logger.info("Executing - " + ' '.join(cmd))
  307. # terminates if execution fails
  308. compat.exec_command(*cmd)
  309. # update cache index
  310. cache_index[basenm] = digest
  311. misc.save_py_data_struct(cacheindexfn, cache_index)
  312. # On Mac OS we need relative paths to dll dependencies starting with @executable_path. While modifying
  313. # the headers invalidates existing signatures, we avoid removing them in order to speed things up (and
  314. # to avoid potential bugs in the codesign utility, like the one reported on Mac OS 10.13 in #6167).
  315. # The forced re-signing at the end should take care of the invalidated signatures.
  316. if is_darwin:
  317. try:
  318. osxutils.binary_to_target_arch(cachedfile, target_arch, display_name=fnm)
  319. #osxutils.remove_signature_from_binary(cachedfile) # Disabled as per comment above.
  320. dylib.mac_set_relative_dylib_deps(cachedfile, dist_nm)
  321. osxutils.sign_binary(cachedfile, codesign_identity, entitlements_file)
  322. except osxutils.InvalidBinaryError:
  323. # Raised by osxutils.binary_to_target_arch when the given file is not a valid macOS binary (for example,
  324. # a linux .so file; see issue #6327). The error prevents any further processing, so just ignore it.
  325. pass
  326. return cachedfile
  327. def cacheDigest(fnm, redirects):
  328. hasher = hashlib.md5()
  329. with open(fnm, "rb") as f:
  330. for chunk in iter(lambda: f.read(16 * 1024), b""):
  331. hasher.update(chunk)
  332. if redirects:
  333. redirects = str(redirects).encode('utf-8')
  334. hasher.update(redirects)
  335. digest = bytearray(hasher.digest())
  336. return digest
  337. def _check_path_overlap(path):
  338. """
  339. Check that path does not overlap with WORKPATH or SPECPATH (i.e., WORKPATH and SPECPATH may not start with path,
  340. which could be caused by a faulty hand-edited specfile).
  341. Raise SystemExit if there is overlap, return True otherwise
  342. """
  343. from PyInstaller.config import CONF
  344. specerr = 0
  345. if CONF['workpath'].startswith(path):
  346. logger.error('Specfile error: The output path "%s" contains WORKPATH (%s)', path, CONF['workpath'])
  347. specerr += 1
  348. if CONF['specpath'].startswith(path):
  349. logger.error('Specfile error: The output path "%s" contains SPECPATH (%s)', path, CONF['specpath'])
  350. specerr += 1
  351. if specerr:
  352. raise SystemExit(
  353. 'Error: Please edit/recreate the specfile (%s) and set a different output name (e.g. "dist").' %
  354. CONF['spec']
  355. )
  356. return True
  357. def _make_clean_directory(path):
  358. """
  359. Create a clean directory from the given directory name.
  360. """
  361. if _check_path_overlap(path):
  362. if os.path.isdir(path) or os.path.isfile(path):
  363. try:
  364. os.remove(path)
  365. except OSError:
  366. _rmtree(path)
  367. os.makedirs(path, exist_ok=True)
  368. def _rmtree(path):
  369. """
  370. Remove directory and all its contents, but only after user confirmation, or if the -y option is set.
  371. """
  372. from PyInstaller.config import CONF
  373. if CONF['noconfirm']:
  374. choice = 'y'
  375. elif sys.stdout.isatty():
  376. choice = compat.stdin_input(
  377. 'WARNING: The output directory "%s" and ALL ITS CONTENTS will be REMOVED! Continue? (y/N)' % path
  378. )
  379. else:
  380. raise SystemExit(
  381. 'Error: The output directory "%s" is not empty. Please remove all its contents or use the -y option (remove'
  382. ' output directory without confirmation).' % path
  383. )
  384. if choice.strip().lower() == 'y':
  385. if not CONF['noconfirm']:
  386. print("On your own risk, you can use the option `--noconfirm` to get rid of this question.")
  387. logger.info('Removing dir %s', path)
  388. shutil.rmtree(path)
  389. else:
  390. raise SystemExit('User aborted')
  391. # TODO Refactor to prohibit empty target directories. As the docstring below documents, this function currently permits
  392. # the second item of each 2-tuple in "hook.datas" to be the empty string, in which case the target directory defaults to
  393. # the source directory's basename. However, this functionality is very fragile and hence bad. Instead:
  394. #
  395. # * An exception should be raised if such item is empty.
  396. # * All hooks currently passing the empty string for such item (e.g.,
  397. # "hooks/hook-babel.py", "hooks/hook-matplotlib.py") should be refactored
  398. # to instead pass such basename.
  399. def format_binaries_and_datas(binaries_or_datas, workingdir=None):
  400. """
  401. Convert the passed list of hook-style 2-tuples into a returned set of `TOC`-style 2-tuples.
  402. Elements of the passed list are 2-tuples `(source_dir_or_glob, target_dir)`.
  403. Elements of the returned set are 2-tuples `(target_file, source_file)`.
  404. For backwards compatibility, the order of elements in the former tuples are the reverse of the order of elements in
  405. the latter tuples!
  406. Parameters
  407. ----------
  408. binaries_or_datas : list
  409. List of hook-style 2-tuples (e.g., the top-level `binaries` and `datas` attributes defined by hooks) whose:
  410. * The first element is either:
  411. * A glob matching only the absolute or relative paths of source non-Python data files.
  412. * The absolute or relative path of a source directory containing only source non-Python data files.
  413. * The second element ist he relative path of the target directory into which these source files will be
  414. recursively copied.
  415. If the optional `workingdir` parameter is passed, source paths may be either absolute or relative; else, source
  416. paths _must_ be absolute.
  417. workingdir : str
  418. Optional absolute path of the directory to which all relative source paths in the `binaries_or_datas`
  419. parameter will be prepended by (and hence converted into absolute paths) _or_ `None` if these paths are to be
  420. preserved as relative. Defaults to `None`.
  421. Returns
  422. ----------
  423. set
  424. Set of `TOC`-style 2-tuples whose:
  425. * First element is the absolute or relative path of a target file.
  426. * Second element is the absolute or relative path of the corresponding source file to be copied to this target
  427. file.
  428. """
  429. toc_datas = set()
  430. for src_root_path_or_glob, trg_root_dir in binaries_or_datas:
  431. if not trg_root_dir:
  432. raise SystemExit(
  433. "Empty DEST not allowed when adding binary and data files. Maybe you want to used %r.\nCaused by %r." %
  434. (os.curdir, src_root_path_or_glob)
  435. )
  436. # Convert relative to absolute paths if required.
  437. if workingdir and not os.path.isabs(src_root_path_or_glob):
  438. src_root_path_or_glob = os.path.join(workingdir, src_root_path_or_glob)
  439. # Normalize paths.
  440. src_root_path_or_glob = os.path.normpath(src_root_path_or_glob)
  441. if os.path.isfile(src_root_path_or_glob):
  442. src_root_paths = [src_root_path_or_glob]
  443. else:
  444. # List of the absolute paths of all source paths matching the current glob.
  445. src_root_paths = glob.glob(src_root_path_or_glob)
  446. if not src_root_paths:
  447. msg = 'Unable to find "%s" when adding binary and data files.' % src_root_path_or_glob
  448. # on Debian/Ubuntu, missing pyconfig.h files can be fixed with installing python-dev
  449. if src_root_path_or_glob.endswith("pyconfig.h"):
  450. msg += """This means your Python installation does not come with proper shared library files.
  451. This usually happens due to missing development package, or unsuitable build parameters of the Python installation.
  452. * On Debian/Ubuntu, you need to install Python development packages:
  453. * apt-get install python3-dev
  454. * apt-get install python-dev
  455. * If you are building Python by yourself, rebuild with `--enable-shared` (or, `--enable-framework` on macOS).
  456. """
  457. raise SystemExit(msg)
  458. for src_root_path in src_root_paths:
  459. if os.path.isfile(src_root_path):
  460. # Normalizing the result to remove redundant relative paths (e.g., removing "./" from "trg/./file").
  461. toc_datas.add((
  462. os.path.normpath(os.path.join(trg_root_dir, os.path.basename(src_root_path))),
  463. os.path.normpath(src_root_path),
  464. ))
  465. elif os.path.isdir(src_root_path):
  466. for src_dir, src_subdir_basenames, src_file_basenames in os.walk(src_root_path):
  467. # Ensure the current source directory is a subdirectory of the passed top-level source directory.
  468. # Since os.walk() does *NOT* follow symlinks by default, this should be the case. (But let's make
  469. # sure.)
  470. assert src_dir.startswith(src_root_path)
  471. # Relative path of the current target directory, obtained by:
  472. #
  473. # * Stripping the top-level source directory from the current source directory (e.g., removing
  474. # "/top" from "/top/dir").
  475. # * Normalizing the result to remove redundant relative paths (e.g., removing "./" from
  476. # "trg/./file").
  477. trg_dir = os.path.normpath(os.path.join(trg_root_dir, os.path.relpath(src_dir, src_root_path)))
  478. for src_file_basename in src_file_basenames:
  479. src_file = os.path.join(src_dir, src_file_basename)
  480. if os.path.isfile(src_file):
  481. # Normalize the result to remove redundant relative paths (e.g., removing "./" from
  482. # "trg/./file").
  483. toc_datas.add((
  484. os.path.normpath(os.path.join(trg_dir, src_file_basename)), os.path.normpath(src_file)
  485. ))
  486. return toc_datas
  487. def _load_code(modname, filename):
  488. path_item = os.path.dirname(filename)
  489. if os.path.basename(filename).startswith('__init__.py'):
  490. # this is a package
  491. path_item = os.path.dirname(path_item)
  492. if os.path.basename(path_item) == '__pycache__':
  493. path_item = os.path.dirname(path_item)
  494. importer = pkgutil.get_importer(path_item)
  495. package, _, modname = modname.rpartition('.')
  496. if hasattr(importer, 'find_loader'):
  497. loader, portions = importer.find_loader(modname)
  498. else:
  499. loader = importer.find_module(modname)
  500. logger.debug('Compiling %s', filename)
  501. if loader and hasattr(loader, 'get_code'):
  502. return loader.get_code(modname)
  503. else:
  504. # Just as ``python foo.bar`` will read and execute statements in ``foo.bar``, even though it lacks the ``.py``
  505. # extension, so ``pyinstaller foo.bar`` should also work. However, Python's import machinery doesn't load files
  506. # without a ``.py`` extension. So, use ``compile`` instead.
  507. #
  508. # On a side note, neither the Python 2 nor Python 3 calls to ``pkgutil`` and ``find_module`` above handle
  509. # modules ending in ``.pyw``, even though ``imp.find_module`` and ``import <name>`` both work. This code
  510. # supports ``.pyw`` files.
  511. # Open the source file in binary mode and allow the `compile()` call to detect the source encoding.
  512. with open(filename, 'rb') as f:
  513. source = f.read()
  514. return compile(source, filename, 'exec')
  515. def get_code_object(modname, filename):
  516. """
  517. Get the code-object for a module.
  518. This is a extra-simple version for compiling a module. It is not worth spending more effort here, as it is only
  519. used in the rare case if outXX-Analysis.toc exists, but outXX-PYZ.toc does not.
  520. """
  521. try:
  522. if filename in ('-', None):
  523. # This is a NamespacePackage, modulegraph marks them by using the filename '-'. (But wants to use None, so
  524. # check for None, too, to be forward-compatible.)
  525. logger.debug('Compiling namespace package %s', modname)
  526. txt = '#\n'
  527. return compile(txt, filename, 'exec')
  528. else:
  529. logger.debug('Compiling %s', filename)
  530. co = _load_code(modname, filename)
  531. if not co:
  532. raise ValueError("Module file %s is missing" % filename)
  533. return co
  534. except SyntaxError as e:
  535. print("Syntax error in ", filename)
  536. print(e.args)
  537. raise
  538. def strip_paths_in_code(co, new_filename=None):
  539. # Paths to remove from filenames embedded in code objects
  540. replace_paths = sys.path + CONF['pathex']
  541. # Make sure paths end with os.sep and the longest paths are first
  542. replace_paths = sorted((os.path.join(f, '') for f in replace_paths), key=len, reverse=True)
  543. if new_filename is None:
  544. original_filename = os.path.normpath(co.co_filename)
  545. for f in replace_paths:
  546. if original_filename.startswith(f):
  547. new_filename = original_filename[len(f):]
  548. break
  549. else:
  550. return co
  551. code_func = type(co)
  552. consts = tuple(
  553. strip_paths_in_code(const_co, new_filename) if isinstance(const_co, code_func) else const_co
  554. for const_co in co.co_consts
  555. )
  556. if hasattr(co, 'replace'): # is_py38
  557. return co.replace(co_consts=consts, co_filename=new_filename)
  558. elif hasattr(co, 'co_kwonlyargcount'):
  559. # co_kwonlyargcount was added in some version of Python 3
  560. return code_func(
  561. co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, consts,
  562. co.co_names, co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars,
  563. co.co_cellvars
  564. )
  565. else:
  566. return code_func(
  567. co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, consts, co.co_names,
  568. co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars
  569. )
  570. def fake_pyc_timestamp(buf):
  571. """
  572. Reset the timestamp from a .pyc-file header to a fixed value.
  573. This enables deterministic builds without having to set pyinstaller source metadata (mtime) since that changes the
  574. pyc-file contents.
  575. _buf_ must at least contain the full pyc-file header.
  576. """
  577. assert buf[:4] == compat.BYTECODE_MAGIC, \
  578. "Expected pyc magic {}, got {}".format(compat.BYTECODE_MAGIC, buf[:4])
  579. start, end = 4, 8
  580. if is_py37:
  581. # See https://www.python.org/dev/peps/pep-0552/
  582. (flags,) = struct.unpack_from(">I", buf, 4)
  583. if flags & 1:
  584. # We are in the future and hash-based pyc-files are used, so
  585. # clear "check_source" flag, since there is no source.
  586. buf[4:8] = struct.pack(">I", flags ^ 2)
  587. return buf
  588. else:
  589. # No hash-based pyc-file, timestamp is the next field.
  590. start, end = 8, 12
  591. ts = b'pyi0' # So people know where this comes from
  592. return buf[:start] + ts + buf[end:]
  593. def _should_include_system_binary(binary_tuple, exceptions):
  594. """
  595. Return True if the given binary_tuple describes a system binary that should be included.
  596. Exclude all system library binaries other than those with "lib-dynload" in the destination or "python" in the
  597. source, except for those matching the patterns in the exceptions list. Intended to be used from the Analysis
  598. exclude_system_libraries method.
  599. """
  600. dest = binary_tuple[0]
  601. if dest.startswith('lib-dynload'):
  602. return True
  603. src = binary_tuple[1]
  604. if fnmatch.fnmatch(src, '*python*'):
  605. return True
  606. if not src.startswith('/lib') and not src.startswith('/usr/lib'):
  607. return True
  608. for exception in exceptions:
  609. if fnmatch.fnmatch(dest, exception):
  610. return True
  611. return False