utils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. # --- 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 pathlib
  19. import platform
  20. import shutil
  21. import struct
  22. import subprocess
  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_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. strict_arch_validation=False
  122. ):
  123. """
  124. Cache prevents preprocessing binary files again and again.
  125. 'dist_nm' Filename relative to dist directory. We need it on Mac to determine level of paths for @loader_path like
  126. '@loader_path/../../' for qt4 plugins.
  127. """
  128. from PyInstaller.config import CONF
  129. # On Mac OS, a cache is required anyway to keep the libraries with relative install names.
  130. # Caching on Mac OS does not work since we need to modify binary headers to use relative paths to dll dependencies
  131. # and starting with '@loader_path'.
  132. if not strip and not upx and not is_darwin and not is_win:
  133. return fnm
  134. if dist_nm is not None and ":" in dist_nm:
  135. # A file embedded in another PyInstaller build via multipackage.
  136. # No actual file exists to process.
  137. return fnm
  138. if strip:
  139. strip = True
  140. else:
  141. strip = False
  142. # Disable UPX on non-Windows. Using UPX (3.96) on modern Linux shared libraries (for example, the python3.x.so
  143. # shared library) seems to result in segmentation fault when they are dlopen'd. This happens in recent versions
  144. # of Fedora and Ubuntu linux, as well as in Alpine containers. On Mac OS, UPX (3.96) fails with
  145. # UnknownExecutableFormatException on most .dylibs (and interferes with code signature on other occasions). And
  146. # even when it would succeed, compressed libraries cannot be (re)signed due to failed strict validation.
  147. upx = upx and (is_win or is_cygwin)
  148. # Match against provided UPX exclude patterns.
  149. upx_exclude = upx_exclude or []
  150. if upx:
  151. fnm_path = pathlib.PurePath(fnm)
  152. for upx_exclude_entry in upx_exclude:
  153. # pathlib.PurePath.match() matches from right to left, and supports * wildcard, but does not support the
  154. # "**" syntax for directory recursion. Case sensitivity follows the OS default.
  155. if fnm_path.match(upx_exclude_entry):
  156. logger.info("Disabling UPX for %s due to match in exclude pattern: %s", fnm, upx_exclude_entry)
  157. upx = False
  158. break
  159. # Load cache index.
  160. # Make cachedir per Python major/minor version.
  161. # This allows parallel building of executables with different Python versions as one user.
  162. pyver = 'py%d%s' % (sys.version_info[0], sys.version_info[1])
  163. arch = platform.architecture()[0]
  164. cachedir = os.path.join(CONF['cachedir'], 'bincache%d%d_%s_%s' % (strip, upx, pyver, arch))
  165. if target_arch:
  166. cachedir = os.path.join(cachedir, target_arch)
  167. if is_darwin:
  168. # Separate by codesign identity
  169. if codesign_identity:
  170. # Compute hex digest of codesign identity string to prevent issues with invalid characters.
  171. csi_hash = hashlib.sha256(codesign_identity.encode('utf-8'))
  172. cachedir = os.path.join(cachedir, csi_hash.hexdigest())
  173. else:
  174. cachedir = os.path.join(cachedir, 'adhoc') # ad-hoc signing
  175. # Separate by entitlements
  176. if entitlements_file:
  177. # Compute hex digest of entitlements file contents
  178. with open(entitlements_file, 'rb') as fp:
  179. ef_hash = hashlib.sha256(fp.read())
  180. cachedir = os.path.join(cachedir, ef_hash.hexdigest())
  181. else:
  182. cachedir = os.path.join(cachedir, 'no-entitlements')
  183. if not os.path.exists(cachedir):
  184. os.makedirs(cachedir)
  185. cacheindexfn = os.path.join(cachedir, "index.dat")
  186. if os.path.exists(cacheindexfn):
  187. try:
  188. cache_index = misc.load_py_data_struct(cacheindexfn)
  189. except Exception:
  190. # Tell the user they may want to fix their cache... However, do not delete it for them; if it keeps getting
  191. # corrupted, we will never find out.
  192. logger.warning("PyInstaller bincache may be corrupted; use pyinstaller --clean to fix it.")
  193. raise
  194. else:
  195. cache_index = {}
  196. # Verify that the file we are looking for is present in the cache. Use the dist_mn if given to avoid different
  197. # extension modules sharing the same basename get corrupted.
  198. if dist_nm:
  199. basenm = os.path.normcase(dist_nm)
  200. else:
  201. basenm = os.path.normcase(os.path.basename(fnm))
  202. # Binding redirects should be taken into account to see if the file needs to be reprocessed. The redirects may
  203. # change if the versions of dependent manifests change due to system updates.
  204. redirects = CONF.get('binding_redirects', [])
  205. digest = cacheDigest(fnm, redirects)
  206. cachedfile = os.path.join(cachedir, basenm)
  207. cmd = None
  208. if basenm in cache_index:
  209. if digest != cache_index[basenm]:
  210. os.remove(cachedfile)
  211. else:
  212. return cachedfile
  213. # Optionally change manifest and its dependencies to private assemblies.
  214. if fnm.lower().endswith(".manifest") and (is_win or is_cygwin):
  215. manifest = winmanifest.Manifest()
  216. manifest.filename = fnm
  217. with open(fnm, "rb") as f:
  218. manifest.parse_string(f.read())
  219. if CONF.get('win_private_assemblies', False):
  220. if manifest.publicKeyToken:
  221. logger.info("Changing %s into private assembly", os.path.basename(fnm))
  222. manifest.publicKeyToken = None
  223. for dep in manifest.dependentAssemblies:
  224. # Exclude common-controls which is not bundled
  225. if dep.name != "Microsoft.Windows.Common-Controls":
  226. dep.publicKeyToken = None
  227. applyRedirects(manifest, redirects)
  228. manifest.writeprettyxml(cachedfile)
  229. return cachedfile
  230. if upx:
  231. if strip:
  232. fnm = checkCache(
  233. fnm,
  234. strip=True,
  235. upx=False,
  236. dist_nm=dist_nm,
  237. target_arch=target_arch,
  238. codesign_identity=codesign_identity,
  239. entitlements_file=entitlements_file,
  240. strict_arch_validation=strict_arch_validation,
  241. )
  242. # We need to avoid using UPX with Windows DLLs that have Control Flow Guard enabled, as it breaks them.
  243. if (is_win or is_cygwin) and versioninfo.pefile_check_control_flow_guard(fnm):
  244. logger.info('Disabling UPX for %s due to CFG!', fnm)
  245. elif misc.is_file_qt_plugin(fnm):
  246. logger.info('Disabling UPX for %s due to it being a Qt plugin!', fnm)
  247. else:
  248. bestopt = "--best"
  249. # FIXME: Linux builds of UPX do not seem to contain LZMA (they assert out).
  250. # A better configure-time check is due.
  251. if CONF["hasUPX"] >= (3,) and os.name == "nt":
  252. bestopt = "--lzma"
  253. upx_executable = "upx"
  254. if CONF.get('upx_dir'):
  255. upx_executable = os.path.join(CONF['upx_dir'], upx_executable)
  256. cmd = [upx_executable, bestopt, "-q", cachedfile]
  257. else:
  258. if strip:
  259. strip_options = []
  260. if is_darwin:
  261. # The default strip behavior breaks some shared libraries under Mac OS.
  262. strip_options = ["-S"] # -S = strip only debug symbols.
  263. cmd = ["strip"] + strip_options + [cachedfile]
  264. if not os.path.exists(os.path.dirname(cachedfile)):
  265. os.makedirs(os.path.dirname(cachedfile))
  266. # There are known some issues with 'shutil.copy2' on Mac OS 10.11 with copying st_flags. Issue #1650.
  267. # 'shutil.copy' copies also permission bits and it should be sufficient for PyInstaller's purposes.
  268. shutil.copy(fnm, cachedfile)
  269. # TODO: find out if this is still necessary when no longer using shutil.copy2()
  270. if hasattr(os, 'chflags'):
  271. # Some libraries on FreeBSD have immunable flag (libthr.so.3, for example). If this flag is preserved,
  272. # os.chmod() fails with: OSError: [Errno 1] Operation not permitted.
  273. try:
  274. os.chflags(cachedfile, 0)
  275. except OSError:
  276. pass
  277. os.chmod(cachedfile, 0o755)
  278. if os.path.splitext(fnm.lower())[1] in (".pyd", ".dll") and (is_win or is_cygwin):
  279. # When shared assemblies are bundled into the app, they may optionally be changed into private assemblies.
  280. try:
  281. res = winmanifest.GetManifestResources(os.path.abspath(cachedfile))
  282. except winresource.pywintypes.error as e:
  283. if e.args[0] == winresource.ERROR_BAD_EXE_FORMAT:
  284. # Not a win32 PE file
  285. pass
  286. else:
  287. logger.error(os.path.abspath(cachedfile))
  288. raise
  289. else:
  290. if winmanifest.RT_MANIFEST in res and len(res[winmanifest.RT_MANIFEST]):
  291. for name in res[winmanifest.RT_MANIFEST]:
  292. for language in res[winmanifest.RT_MANIFEST][name]:
  293. try:
  294. manifest = winmanifest.Manifest()
  295. manifest.filename = ":".join([
  296. cachedfile, str(winmanifest.RT_MANIFEST),
  297. str(name), str(language)
  298. ])
  299. manifest.parse_string(res[winmanifest.RT_MANIFEST][name][language], False)
  300. except Exception:
  301. logger.error("Cannot parse manifest resource %s, =%s", name, language)
  302. logger.error("From file %s", cachedfile, exc_info=1)
  303. else:
  304. # optionally change manifest to private assembly
  305. private = CONF.get('win_private_assemblies', False)
  306. if private:
  307. if manifest.publicKeyToken:
  308. logger.info("Changing %s into a private assembly", os.path.basename(fnm))
  309. manifest.publicKeyToken = None
  310. # Change dep to private assembly
  311. for dep in manifest.dependentAssemblies:
  312. # Exclude common-controls which is not bundled
  313. if dep.name != "Microsoft.Windows.Common-Controls":
  314. dep.publicKeyToken = None
  315. redirecting = applyRedirects(manifest, redirects)
  316. if redirecting or private:
  317. try:
  318. manifest.update_resources(os.path.abspath(cachedfile), [name], [language])
  319. except Exception:
  320. logger.error(os.path.abspath(cachedfile))
  321. raise
  322. if cmd:
  323. logger.info("Executing - " + "".join(cmd))
  324. subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  325. # update cache index
  326. cache_index[basenm] = digest
  327. misc.save_py_data_struct(cacheindexfn, cache_index)
  328. # On Mac OS we need relative paths to dll dependencies starting with @executable_path. While modifying
  329. # the headers invalidates existing signatures, we avoid removing them in order to speed things up (and
  330. # to avoid potential bugs in the codesign utility, like the one reported on Mac OS 10.13 in #6167).
  331. # The forced re-signing at the end should take care of the invalidated signatures.
  332. if is_darwin:
  333. try:
  334. osxutils.binary_to_target_arch(cachedfile, target_arch, display_name=fnm)
  335. #osxutils.remove_signature_from_binary(cachedfile) # Disabled as per comment above.
  336. dylib.mac_set_relative_dylib_deps(cachedfile, dist_nm)
  337. osxutils.sign_binary(cachedfile, codesign_identity, entitlements_file)
  338. except osxutils.InvalidBinaryError:
  339. # Raised by osxutils.binary_to_target_arch when the given file is not a valid macOS binary (for example,
  340. # a linux .so file; see issue #6327). The error prevents any further processing, so just ignore it.
  341. pass
  342. except osxutils.IncompatibleBinaryArchError:
  343. # Raised by osxutils.binary_to_target_arch when the given file does not contain (all) required arch slices.
  344. # Depending on the strict validation mode, re-raise or swallow the error.
  345. #
  346. # Strict validation should be enabled only for binaries where the architecture *must* match the target one,
  347. # i.e., the extension modules. Everything else is pretty much a gray area, for example:
  348. # * a universal2 extension may have its x86_64 and arm64 slices linked against distinct single-arch/thin
  349. # shared libraries
  350. # * a collected executable that is launched by python code via a subprocess can be x86_64-only, even though
  351. # the actual python code is running on M1 in native arm64 mode.
  352. if strict_arch_validation:
  353. raise
  354. logger.debug("File %s failed optional architecture validation - collecting as-is!", fnm)
  355. return cachedfile
  356. def cacheDigest(fnm, redirects):
  357. hasher = hashlib.md5()
  358. with open(fnm, "rb") as f:
  359. for chunk in iter(lambda: f.read(16 * 1024), b""):
  360. hasher.update(chunk)
  361. if redirects:
  362. redirects = str(redirects).encode('utf-8')
  363. hasher.update(redirects)
  364. digest = bytearray(hasher.digest())
  365. return digest
  366. def _check_path_overlap(path):
  367. """
  368. Check that path does not overlap with WORKPATH or SPECPATH (i.e., WORKPATH and SPECPATH may not start with path,
  369. which could be caused by a faulty hand-edited specfile).
  370. Raise SystemExit if there is overlap, return True otherwise
  371. """
  372. from PyInstaller.config import CONF
  373. specerr = 0
  374. if CONF['workpath'].startswith(path):
  375. logger.error('Specfile error: The output path "%s" contains WORKPATH (%s)', path, CONF['workpath'])
  376. specerr += 1
  377. if CONF['specpath'].startswith(path):
  378. logger.error('Specfile error: The output path "%s" contains SPECPATH (%s)', path, CONF['specpath'])
  379. specerr += 1
  380. if specerr:
  381. raise SystemExit(
  382. 'Error: Please edit/recreate the specfile (%s) and set a different output name (e.g. "dist").' %
  383. CONF['spec']
  384. )
  385. return True
  386. def _make_clean_directory(path):
  387. """
  388. Create a clean directory from the given directory name.
  389. """
  390. if _check_path_overlap(path):
  391. if os.path.isdir(path) or os.path.isfile(path):
  392. try:
  393. os.remove(path)
  394. except OSError:
  395. _rmtree(path)
  396. os.makedirs(path, exist_ok=True)
  397. def _rmtree(path):
  398. """
  399. Remove directory and all its contents, but only after user confirmation, or if the -y option is set.
  400. """
  401. from PyInstaller.config import CONF
  402. if CONF['noconfirm']:
  403. choice = 'y'
  404. elif sys.stdout.isatty():
  405. choice = compat.stdin_input(
  406. 'WARNING: The output directory "%s" and ALL ITS CONTENTS will be REMOVED! Continue? (y/N)' % path
  407. )
  408. else:
  409. raise SystemExit(
  410. 'Error: The output directory "%s" is not empty. Please remove all its contents or use the -y option (remove'
  411. ' output directory without confirmation).' % path
  412. )
  413. if choice.strip().lower() == 'y':
  414. if not CONF['noconfirm']:
  415. print("On your own risk, you can use the option `--noconfirm` to get rid of this question.")
  416. logger.info('Removing dir %s', path)
  417. shutil.rmtree(path)
  418. else:
  419. raise SystemExit('User aborted')
  420. # TODO Refactor to prohibit empty target directories. As the docstring below documents, this function currently permits
  421. # the second item of each 2-tuple in "hook.datas" to be the empty string, in which case the target directory defaults to
  422. # the source directory's basename. However, this functionality is very fragile and hence bad. Instead:
  423. #
  424. # * An exception should be raised if such item is empty.
  425. # * All hooks currently passing the empty string for such item (e.g.,
  426. # "hooks/hook-babel.py", "hooks/hook-matplotlib.py") should be refactored
  427. # to instead pass such basename.
  428. def format_binaries_and_datas(binaries_or_datas, workingdir=None):
  429. """
  430. Convert the passed list of hook-style 2-tuples into a returned set of `TOC`-style 2-tuples.
  431. Elements of the passed list are 2-tuples `(source_dir_or_glob, target_dir)`.
  432. Elements of the returned set are 2-tuples `(target_file, source_file)`.
  433. For backwards compatibility, the order of elements in the former tuples are the reverse of the order of elements in
  434. the latter tuples!
  435. Parameters
  436. ----------
  437. binaries_or_datas : list
  438. List of hook-style 2-tuples (e.g., the top-level `binaries` and `datas` attributes defined by hooks) whose:
  439. * The first element is either:
  440. * A glob matching only the absolute or relative paths of source non-Python data files.
  441. * The absolute or relative path of a source directory containing only source non-Python data files.
  442. * The second element is the relative path of the target directory into which these source files will be
  443. recursively copied.
  444. If the optional `workingdir` parameter is passed, source paths may be either absolute or relative; else, source
  445. paths _must_ be absolute.
  446. workingdir : str
  447. Optional absolute path of the directory to which all relative source paths in the `binaries_or_datas`
  448. parameter will be prepended by (and hence converted into absolute paths) _or_ `None` if these paths are to be
  449. preserved as relative. Defaults to `None`.
  450. Returns
  451. ----------
  452. set
  453. Set of `TOC`-style 2-tuples whose:
  454. * First element is the absolute or relative path of a target file.
  455. * Second element is the absolute or relative path of the corresponding source file to be copied to this target
  456. file.
  457. """
  458. toc_datas = set()
  459. for src_root_path_or_glob, trg_root_dir in binaries_or_datas:
  460. if not trg_root_dir:
  461. raise SystemExit(
  462. "Empty DEST not allowed when adding binary and data files. Maybe you want to used %r.\nCaused by %r." %
  463. (os.curdir, src_root_path_or_glob)
  464. )
  465. # Convert relative to absolute paths if required.
  466. if workingdir and not os.path.isabs(src_root_path_or_glob):
  467. src_root_path_or_glob = os.path.join(workingdir, src_root_path_or_glob)
  468. # Normalize paths.
  469. src_root_path_or_glob = os.path.normpath(src_root_path_or_glob)
  470. if os.path.isfile(src_root_path_or_glob):
  471. src_root_paths = [src_root_path_or_glob]
  472. else:
  473. # List of the absolute paths of all source paths matching the current glob.
  474. src_root_paths = glob.glob(src_root_path_or_glob)
  475. if not src_root_paths:
  476. msg = 'Unable to find "%s" when adding binary and data files.' % src_root_path_or_glob
  477. # on Debian/Ubuntu, missing pyconfig.h files can be fixed with installing python-dev
  478. if src_root_path_or_glob.endswith("pyconfig.h"):
  479. msg += """This means your Python installation does not come with proper shared library files.
  480. This usually happens due to missing development package, or unsuitable build parameters of the Python installation.
  481. * On Debian/Ubuntu, you need to install Python development packages:
  482. * apt-get install python3-dev
  483. * apt-get install python-dev
  484. * If you are building Python by yourself, rebuild with `--enable-shared` (or, `--enable-framework` on macOS).
  485. """
  486. raise SystemExit(msg)
  487. for src_root_path in src_root_paths:
  488. if os.path.isfile(src_root_path):
  489. # Normalizing the result to remove redundant relative paths (e.g., removing "./" from "trg/./file").
  490. toc_datas.add((
  491. os.path.normpath(os.path.join(trg_root_dir, os.path.basename(src_root_path))),
  492. os.path.normpath(src_root_path),
  493. ))
  494. elif os.path.isdir(src_root_path):
  495. for src_dir, src_subdir_basenames, src_file_basenames in os.walk(src_root_path):
  496. # Ensure the current source directory is a subdirectory of the passed top-level source directory.
  497. # Since os.walk() does *NOT* follow symlinks by default, this should be the case. (But let's make
  498. # sure.)
  499. assert src_dir.startswith(src_root_path)
  500. # Relative path of the current target directory, obtained by:
  501. #
  502. # * Stripping the top-level source directory from the current source directory (e.g., removing
  503. # "/top" from "/top/dir").
  504. # * Normalizing the result to remove redundant relative paths (e.g., removing "./" from
  505. # "trg/./file").
  506. trg_dir = os.path.normpath(os.path.join(trg_root_dir, os.path.relpath(src_dir, src_root_path)))
  507. for src_file_basename in src_file_basenames:
  508. src_file = os.path.join(src_dir, src_file_basename)
  509. if os.path.isfile(src_file):
  510. # Normalize the result to remove redundant relative paths (e.g., removing "./" from
  511. # "trg/./file").
  512. toc_datas.add((
  513. os.path.normpath(os.path.join(trg_dir, src_file_basename)), os.path.normpath(src_file)
  514. ))
  515. return toc_datas
  516. def get_code_object(modname, filename):
  517. """
  518. Get the code-object for a module.
  519. This is a simplifed non-performant version which circumvents __pycache__.
  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. with open(filename, 'rb') as f:
  531. source = f.read()
  532. return compile(source, filename, 'exec')
  533. except SyntaxError as e:
  534. print("Syntax error in ", filename)
  535. print(e.args)
  536. raise
  537. def strip_paths_in_code(co, new_filename=None):
  538. # Paths to remove from filenames embedded in code objects
  539. replace_paths = sys.path + CONF['pathex']
  540. # Make sure paths end with os.sep and the longest paths are first
  541. replace_paths = sorted((os.path.join(f, '') for f in replace_paths), key=len, reverse=True)
  542. if new_filename is None:
  543. original_filename = os.path.normpath(co.co_filename)
  544. for f in replace_paths:
  545. if original_filename.startswith(f):
  546. new_filename = original_filename[len(f):]
  547. break
  548. else:
  549. return co
  550. code_func = type(co)
  551. consts = tuple(
  552. strip_paths_in_code(const_co, new_filename) if isinstance(const_co, code_func) else const_co
  553. for const_co in co.co_consts
  554. )
  555. if hasattr(co, 'replace'): # is_py38
  556. return co.replace(co_consts=consts, co_filename=new_filename)
  557. elif hasattr(co, 'co_kwonlyargcount'):
  558. # co_kwonlyargcount was added in some version of Python 3
  559. return code_func(
  560. co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, consts,
  561. co.co_names, co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars,
  562. co.co_cellvars
  563. )
  564. else:
  565. return code_func(
  566. co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, consts, co.co_names,
  567. co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars
  568. )
  569. def fake_pyc_timestamp(buf):
  570. """
  571. Reset the timestamp from a .pyc-file header to a fixed value.
  572. This enables deterministic builds without having to set pyinstaller source metadata (mtime) since that changes the
  573. pyc-file contents.
  574. _buf_ must at least contain the full pyc-file header.
  575. """
  576. assert buf[:4] == compat.BYTECODE_MAGIC, \
  577. "Expected pyc magic {}, got {}".format(compat.BYTECODE_MAGIC, buf[:4])
  578. start, end = 4, 8
  579. # See https://www.python.org/dev/peps/pep-0552/
  580. (flags,) = struct.unpack_from(">I", buf, 4)
  581. if flags & 1:
  582. # We are in the future and hash-based pyc-files are used, so
  583. # clear "check_source" flag, since there is no source.
  584. buf[4:8] = struct.pack(">I", flags ^ 2)
  585. return buf
  586. else:
  587. # No hash-based pyc-file, timestamp is the next field.
  588. start, end = 8, 12
  589. ts = b'pyi0' # So people know where this comes from
  590. return buf[:start] + ts + buf[end:]
  591. def _should_include_system_binary(binary_tuple, exceptions):
  592. """
  593. Return True if the given binary_tuple describes a system binary that should be included.
  594. Exclude all system library binaries other than those with "lib-dynload" in the destination or "python" in the
  595. source, except for those matching the patterns in the exceptions list. Intended to be used from the Analysis
  596. exclude_system_libraries method.
  597. """
  598. dest = binary_tuple[0]
  599. if dest.startswith('lib-dynload'):
  600. return True
  601. src = binary_tuple[1]
  602. if fnmatch.fnmatch(src, '*python*'):
  603. return True
  604. if not src.startswith('/lib') and not src.startswith('/usr/lib'):
  605. return True
  606. for exception in exceptions:
  607. if fnmatch.fnmatch(dest, exception):
  608. return True
  609. return False