api.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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. This module contains classes that are available for the .spec files.
  13. Spec file is generated by PyInstaller. The generated code from .spec file
  14. is a way how PyInstaller does the dependency analysis and creates executable.
  15. """
  16. import os
  17. import shutil
  18. import tempfile
  19. import pprint
  20. from operator import itemgetter
  21. from PyInstaller import HOMEPATH, PLATFORM
  22. from PyInstaller.archive.writers import ZlibArchiveWriter, CArchiveWriter
  23. from PyInstaller.building.utils import _check_guts_toc, \
  24. add_suffix_to_extension, \
  25. checkCache, strip_paths_in_code, get_code_object, \
  26. _make_clean_directory
  27. from PyInstaller.compat import is_win, is_darwin, is_linux, is_cygwin, \
  28. exec_command_all, is_64bits
  29. from PyInstaller.depend import bindepend
  30. from PyInstaller.depend.analysis import get_bootstrap_modules
  31. from PyInstaller.depend.utils import is_path_to_egg
  32. from PyInstaller.building.datastruct import TOC, Target, _check_guts_eq
  33. from PyInstaller.utils import misc
  34. from PyInstaller import log as logging
  35. logger = logging.getLogger(__name__)
  36. if is_win:
  37. from PyInstaller.utils.win32 import winmanifest, icon, versioninfo, winresource
  38. class PYZ(Target):
  39. """
  40. Creates a ZlibArchive that contains all pure Python modules.
  41. """
  42. typ = 'PYZ'
  43. def __init__(self, *tocs, **kwargs):
  44. """
  45. tocs
  46. One or more TOCs (Tables of Contents), normally an
  47. Analysis.pure.
  48. If this TOC has an attribute `_code_cache`, this is
  49. expected to be a dict of module code objects from
  50. ModuleGraph.
  51. kwargs
  52. Possible keywork arguments:
  53. name
  54. A filename for the .pyz. Normally not needed, as the generated
  55. name will do fine.
  56. cipher
  57. The block cipher that will be used to encrypt Python bytecode.
  58. """
  59. from PyInstaller.config import CONF
  60. Target.__init__(self)
  61. name = kwargs.get('name', None)
  62. cipher = kwargs.get('cipher', None)
  63. self.toc = TOC()
  64. # If available, use code objects directly from ModuleGraph to
  65. # speed up PyInstaller.
  66. self.code_dict = {}
  67. for t in tocs:
  68. self.toc.extend(t)
  69. self.code_dict.update(getattr(t, '_code_cache', {}))
  70. self.name = name
  71. if name is None:
  72. self.name = os.path.splitext(self.tocfilename)[0] + '.pyz'
  73. # PyInstaller bootstrapping modules.
  74. self.dependencies = get_bootstrap_modules()
  75. # Bundle the crypto key.
  76. self.cipher = cipher
  77. if cipher:
  78. key_file = ('pyimod00_crypto_key',
  79. os.path.join(CONF['workpath'], 'pyimod00_crypto_key.pyc'),
  80. 'PYMODULE')
  81. # Insert the key as the first module in the list. The key module contains
  82. # just variables and does not depend on other modules.
  83. self.dependencies.insert(0, key_file)
  84. # Compile the top-level modules so that they end up in the CArchive and can be
  85. # imported by the bootstrap script.
  86. self.dependencies = misc.compile_py_files(self.dependencies, CONF['workpath'])
  87. self.__postinit__()
  88. _GUTS = (# input parameters
  89. ('name', _check_guts_eq),
  90. ('toc', _check_guts_toc), # todo: pyc=1
  91. # no calculated/analysed values
  92. )
  93. def _check_guts(self, data, last_build):
  94. if Target._check_guts(self, data, last_build):
  95. return True
  96. return False
  97. def assemble(self):
  98. logger.info("Building PYZ (ZlibArchive) %s", self.name)
  99. # Do not bundle PyInstaller bootstrap modules into PYZ archive.
  100. toc = self.toc - self.dependencies
  101. for entry in toc[:]:
  102. if not entry[0] in self.code_dict and entry[2] == 'PYMODULE':
  103. # For some reason the code-object, modulegraph created
  104. # is not available. Recreate it
  105. try:
  106. self.code_dict[entry[0]] = get_code_object(entry[0], entry[1])
  107. except SyntaxError:
  108. # Exclude the module in case this is code meant for a newer Python version.
  109. toc.remove(entry)
  110. # sort content alphabetically to support reproducible builds
  111. toc.sort()
  112. # Remove leading parts of paths in code objects
  113. self.code_dict = {
  114. key: strip_paths_in_code(code)
  115. for key, code in self.code_dict.items()
  116. }
  117. pyz = ZlibArchiveWriter(self.name, toc, code_dict=self.code_dict, cipher=self.cipher)
  118. logger.info("Building PYZ (ZlibArchive) %s completed successfully.",
  119. self.name)
  120. class PKG(Target):
  121. """
  122. Creates a CArchive. CArchive is the data structure that is embedded
  123. into the executable. This data structure allows to include various
  124. read-only data in a sigle-file deployment.
  125. """
  126. typ = 'PKG'
  127. xformdict = {'PYMODULE': 'm',
  128. 'PYSOURCE': 's',
  129. 'EXTENSION': 'b',
  130. 'PYZ': 'z',
  131. 'PKG': 'a',
  132. 'DATA': 'x',
  133. 'BINARY': 'b',
  134. 'ZIPFILE': 'Z',
  135. 'EXECUTABLE': 'b',
  136. 'DEPENDENCY': 'd',
  137. 'SPLASH': 'l'}
  138. def __init__(self, toc, name=None, cdict=None, exclude_binaries=0,
  139. strip_binaries=False, upx_binaries=False, upx_exclude=None,
  140. target_arch=None, codesign_identity=None,
  141. entitlements_file=None):
  142. """
  143. toc
  144. A TOC (Table of Contents)
  145. name
  146. An optional filename for the PKG.
  147. cdict
  148. Dictionary that specifies compression by typecode. For Example,
  149. PYZ is left uncompressed so that it can be accessed inside the
  150. PKG. The default uses sensible values. If zlib is not available,
  151. no compression is used.
  152. exclude_binaries
  153. If True, EXTENSIONs and BINARYs will be left out of the PKG,
  154. and forwarded to its container (usually a COLLECT).
  155. strip_binaries
  156. If True, use 'strip' command to reduce the size of binary files.
  157. upx_binaries
  158. """
  159. Target.__init__(self)
  160. self.toc = toc
  161. self.cdict = cdict
  162. self.name = name
  163. if name is None:
  164. self.name = os.path.splitext(self.tocfilename)[0] + '.pkg'
  165. self.exclude_binaries = exclude_binaries
  166. self.strip_binaries = strip_binaries
  167. self.upx_binaries = upx_binaries
  168. self.upx_exclude = upx_exclude or []
  169. self.target_arch = target_arch
  170. self.codesign_identity = codesign_identity
  171. self.entitlements_file = entitlements_file
  172. # This dict tells PyInstaller what items embedded in the executable should
  173. # be compressed.
  174. if self.cdict is None:
  175. self.cdict = {'EXTENSION': COMPRESSED,
  176. 'DATA': COMPRESSED,
  177. 'BINARY': COMPRESSED,
  178. 'EXECUTABLE': COMPRESSED,
  179. 'PYSOURCE': COMPRESSED,
  180. 'PYMODULE': COMPRESSED,
  181. 'SPLASH': COMPRESSED,
  182. # Do not compress PYZ as a whole. Single modules are
  183. # compressed when creating PYZ archive.
  184. 'PYZ': UNCOMPRESSED}
  185. self.__postinit__()
  186. _GUTS = (# input parameters
  187. ('name', _check_guts_eq),
  188. ('cdict', _check_guts_eq),
  189. ('toc', _check_guts_toc), # list unchanged and no newer files
  190. ('exclude_binaries', _check_guts_eq),
  191. ('strip_binaries', _check_guts_eq),
  192. ('upx_binaries', _check_guts_eq),
  193. ('upx_exclude', _check_guts_eq),
  194. ('target_arch', _check_guts_eq),
  195. ('codesign_identity', _check_guts_eq),
  196. ('entitlements_file', _check_guts_eq),
  197. # no calculated/analysed values
  198. )
  199. def _check_guts(self, data, last_build):
  200. if Target._check_guts(self, data, last_build):
  201. return True
  202. return False
  203. def assemble(self):
  204. logger.info("Building PKG (CArchive) %s", os.path.basename(self.name))
  205. trash = []
  206. mytoc = []
  207. srctoc = []
  208. seenInms = {}
  209. seenFnms = {}
  210. seenFnms_typ = {}
  211. # 'inm' - relative filename inside a CArchive
  212. # 'fnm' - absolute filename as it is on the file system.
  213. for inm, fnm, typ in self.toc:
  214. # Adjust name for extensions, if applicable
  215. inm, fnm, typ = add_suffix_to_extension(inm, fnm, typ)
  216. # Ensure filename 'fnm' is not None or empty string. Otherwise
  217. # it will fail in case of 'typ' being type OPTION.
  218. if fnm and not os.path.isfile(fnm) and is_path_to_egg(fnm):
  219. # file is contained within python egg, it is added with the egg
  220. continue
  221. if typ in ('BINARY', 'EXTENSION', 'DEPENDENCY'):
  222. if self.exclude_binaries and typ == 'EXTENSION':
  223. self.dependencies.append((inm, fnm, typ))
  224. elif not self.exclude_binaries or typ == 'DEPENDENCY':
  225. if typ == 'BINARY':
  226. # Avoid importing the same binary extension twice. This might
  227. # happen if they come from different sources (eg. once from
  228. # binary dependence, and once from direct import).
  229. if inm in seenInms:
  230. logger.warning('Two binaries added with the same internal name.')
  231. logger.warning(pprint.pformat((inm, fnm, typ)))
  232. logger.warning('was placed previously at')
  233. logger.warning(pprint.pformat((inm, seenInms[inm], seenFnms_typ[seenInms[inm]])))
  234. logger.warning('Skipping %s.' % fnm)
  235. continue
  236. # Warn if the same binary extension was included
  237. # with multiple internal names
  238. if fnm in seenFnms:
  239. logger.warning('One binary added with two internal names.')
  240. logger.warning(pprint.pformat((inm, fnm, typ)))
  241. logger.warning('was placed previously at')
  242. logger.warning(pprint.pformat((seenFnms[fnm], fnm, seenFnms_typ[fnm])))
  243. seenInms[inm] = fnm
  244. seenFnms[fnm] = inm
  245. seenFnms_typ[fnm] = typ
  246. fnm = checkCache(fnm, strip=self.strip_binaries,
  247. upx=self.upx_binaries,
  248. upx_exclude=self.upx_exclude,
  249. dist_nm=inm,
  250. target_arch=self.target_arch,
  251. codesign_identity=self.codesign_identity,
  252. entitlements_file=self.entitlements_file)
  253. mytoc.append((inm, fnm, self.cdict.get(typ, 0),
  254. self.xformdict.get(typ, 'b')))
  255. elif typ == 'OPTION':
  256. mytoc.append((inm, '', 0, 'o'))
  257. elif typ in ('PYSOURCE', 'PYMODULE'):
  258. # collect sourcefiles and module in a toc of it's own
  259. # which will not be sorted.
  260. srctoc.append((inm, fnm, self.cdict[typ], self.xformdict[typ]))
  261. else:
  262. mytoc.append((inm, fnm, self.cdict.get(typ, 0), self.xformdict.get(typ, 'b')))
  263. # Bootloader has to know the name of Python library. Pass python libname to CArchive.
  264. pylib_name = os.path.basename(bindepend.get_python_library_path())
  265. # Sort content alphabetically by type and name to support
  266. # reproducible builds.
  267. mytoc.sort(key=itemgetter(3, 0))
  268. # Do *not* sort modules and scripts, as their order is important.
  269. # TODO: Think about having all modules first and then all scripts.
  270. archive = CArchiveWriter(self.name, srctoc + mytoc,
  271. pylib_name=pylib_name)
  272. for item in trash:
  273. os.remove(item)
  274. logger.info("Building PKG (CArchive) %s completed successfully.",
  275. os.path.basename(self.name))
  276. class EXE(Target):
  277. """
  278. Creates the final executable of the frozen app.
  279. This bundles all necessary files together.
  280. """
  281. typ = 'EXECUTABLE'
  282. def __init__(self, *args, **kwargs):
  283. """
  284. args
  285. One or more arguments that are either TOCs Targets.
  286. kwargs
  287. Possible keywork arguments:
  288. bootloader_ignore_signals
  289. Non-Windows only. If True, the bootloader process will ignore
  290. all ignorable signals. If False (default), it will forward
  291. all signals to the child process. Useful in situations where
  292. e.g. a supervisor process signals both the bootloader and
  293. child (e.g. via a process group) to avoid signalling the
  294. child twice.
  295. console
  296. On Windows or OSX governs whether to use the console executable
  297. or the windowed executable. Always True on Linux/Unix (always
  298. console executable - it does not matter there).
  299. disable_windowed_traceback
  300. Disable traceback dump of unhandled exception in windowed
  301. (noconsole) mode (Windows and macOS only), and instead display
  302. a message that this feature is disabled.
  303. debug
  304. Setting to True gives you progress mesages from the executable
  305. (for console=False there will be annoying MessageBoxes on Windows).
  306. name
  307. The filename for the executable. On Windows suffix '.exe' is
  308. appended.
  309. exclude_binaries
  310. Forwarded to the PKG the EXE builds.
  311. icon
  312. Windows or OSX only. icon='myicon.ico' to use an icon file or
  313. icon='notepad.exe,0' to grab an icon resource.
  314. Defaults to use PyInstaller's console or windowed icon.
  315. icon=`NONE` to not add any icon.
  316. version
  317. Windows only. version='myversion.txt'. Use grab_version.py to get
  318. a version resource from an executable and then edit the output to
  319. create your own. (The syntax of version resources is so arcane
  320. that I wouldn't attempt to write one from scratch).
  321. uac_admin
  322. Windows only. Setting to True creates a Manifest with will request
  323. elevation upon application restart
  324. uac_uiaccess
  325. Windows only. Setting to True allows an elevated application to
  326. work with Remote Desktop
  327. target_arch
  328. macOS only. Used to explicitly specify the target architecture;
  329. either single-arch ('x86_64' or 'arm64') or 'universal2'. Used
  330. in checks that the collected binaries contain the requires arch
  331. slice(s) and/or to convert fat binaries into thin ones as
  332. necessary. If not specified (default), a single-arch build
  333. corresponding to running architecture is assumed.
  334. codesign_identity
  335. macOS only. Use the provided identity to sign collected
  336. binaries and the generated executable. If signing identity is
  337. not provided, ad-hoc signing is performed.
  338. entitlements_file
  339. macOS only. Optional path to entitlements file to use with
  340. code signing of collected binaries (--entitlements option
  341. to codesign utility).
  342. """
  343. from PyInstaller.config import CONF
  344. Target.__init__(self)
  345. # Available options for EXE in .spec files.
  346. self.exclude_binaries = kwargs.get('exclude_binaries', False)
  347. self.bootloader_ignore_signals = kwargs.get(
  348. 'bootloader_ignore_signals', False)
  349. self.console = kwargs.get('console', True)
  350. self.disable_windowed_traceback = kwargs.get(
  351. 'disable_windowed_traceback', False)
  352. self.debug = kwargs.get('debug', False)
  353. self.name = kwargs.get('name', None)
  354. self.icon = kwargs.get('icon', None)
  355. self.versrsrc = kwargs.get('version', None)
  356. self.manifest = kwargs.get('manifest', None)
  357. self.resources = kwargs.get('resources', [])
  358. self.strip = kwargs.get('strip', False)
  359. self.upx_exclude = kwargs.get("upx_exclude", [])
  360. self.runtime_tmpdir = kwargs.get('runtime_tmpdir', None)
  361. # If ``append_pkg`` is false, the archive will not be appended
  362. # to the exe, but copied beside it.
  363. self.append_pkg = kwargs.get('append_pkg', True)
  364. # On Windows allows the exe to request admin privileges.
  365. self.uac_admin = kwargs.get('uac_admin', False)
  366. self.uac_uiaccess = kwargs.get('uac_uiaccess', False)
  367. # Target architecture (macOS only)
  368. self.target_arch = kwargs.get('target_arch', None)
  369. if is_darwin:
  370. if self.target_arch is None:
  371. import platform
  372. self.target_arch = platform.machine()
  373. else:
  374. assert self.target_arch in {'x86_64', 'arm64', 'universal2'}, \
  375. f"Unsupported target arch: {self.target_arch}"
  376. logger.info("EXE target arch: %s", self.target_arch)
  377. else:
  378. self.target_arch = None # explicitly disable
  379. # Code signing identity (macOS only)
  380. self.codesign_identity = kwargs.get('codesign_identity', None)
  381. if is_darwin:
  382. logger.info("Code signing identity: %s", self.codesign_identity)
  383. else:
  384. self.codesign_identity = None # explicitly disable
  385. # Code signing entitlements
  386. self.entitlements_file = kwargs.get('entitlements_file', None)
  387. if CONF['hasUPX']:
  388. self.upx = kwargs.get('upx', False)
  389. else:
  390. self.upx = False
  391. # Old .spec format included in 'name' the path where to put created
  392. # app. New format includes only exename.
  393. #
  394. # Ignore fullpath in the 'name' and prepend DISTPATH or WORKPATH.
  395. # DISTPATH - onefile
  396. # WORKPATH - onedir
  397. if self.exclude_binaries:
  398. # onedir mode - create executable in WORKPATH.
  399. self.name = os.path.join(CONF['workpath'], os.path.basename(self.name))
  400. else:
  401. # onefile mode - create executable in DISTPATH.
  402. self.name = os.path.join(CONF['distpath'], os.path.basename(self.name))
  403. # Old .spec format included on Windows in 'name' .exe suffix.
  404. if is_win or is_cygwin:
  405. # Append .exe suffix if it is not already there.
  406. if not self.name.endswith('.exe'):
  407. self.name += '.exe'
  408. base_name = os.path.splitext(os.path.basename(self.name))[0]
  409. else:
  410. base_name = os.path.basename(self.name)
  411. self.pkgname = base_name + '.pkg'
  412. self.toc = TOC()
  413. for arg in args:
  414. if isinstance(arg, TOC):
  415. self.toc.extend(arg)
  416. elif isinstance(arg, Target):
  417. self.toc.append((os.path.basename(arg.name), arg.name, arg.typ))
  418. self.toc.extend(arg.dependencies)
  419. else:
  420. self.toc.extend(arg)
  421. if self.runtime_tmpdir is not None:
  422. self.toc.append(("pyi-runtime-tmpdir " + self.runtime_tmpdir, "", "OPTION"))
  423. if self.bootloader_ignore_signals:
  424. # no value; presence means "true"
  425. self.toc.append(("pyi-bootloader-ignore-signals", "", "OPTION"))
  426. if self.disable_windowed_traceback:
  427. # no value; presence means "true"
  428. self.toc.append(("pyi-disable-windowed-traceback", "", "OPTION"))
  429. if is_win:
  430. if not self.icon:
  431. # --icon not specified; use default from bootloader folder
  432. if self.console:
  433. icon = 'icon-console.ico'
  434. else:
  435. icon = 'icon-windowed.ico'
  436. self.icon = os.path.join(
  437. os.path.dirname(os.path.dirname(__file__)),
  438. 'bootloader', 'images', icon)
  439. filename = os.path.join(CONF['workpath'], CONF['specnm'] + ".exe.manifest")
  440. self.manifest = winmanifest.create_manifest(filename, self.manifest,
  441. self.console, self.uac_admin, self.uac_uiaccess)
  442. manifest_filename = os.path.basename(self.name) + ".manifest"
  443. self.toc.append((manifest_filename, filename, 'BINARY'))
  444. if not self.exclude_binaries:
  445. # Onefile mode: manifest file is explicitly loaded.
  446. # Store name of manifest file as bootloader option. Allows
  447. # the exe to be renamed.
  448. self.toc.append(("pyi-windows-manifest-filename " + manifest_filename,
  449. "", "OPTION"))
  450. if self.versrsrc:
  451. if (not isinstance(self.versrsrc, versioninfo.VSVersionInfo)
  452. and not os.path.isabs(self.versrsrc)):
  453. # relative version-info path is relative to spec file
  454. self.versrsrc = os.path.join(
  455. CONF['specpath'], self.versrsrc)
  456. self.pkg = PKG(self.toc, cdict=kwargs.get('cdict', None),
  457. exclude_binaries=self.exclude_binaries,
  458. strip_binaries=self.strip, upx_binaries=self.upx,
  459. upx_exclude=self.upx_exclude,
  460. target_arch=self.target_arch,
  461. codesign_identity=self.codesign_identity,
  462. entitlements_file=self.entitlements_file
  463. )
  464. self.dependencies = self.pkg.dependencies
  465. # Get the path of the bootloader and store it in a TOC, so it
  466. # can be checked for being changed.
  467. exe = self._bootloader_file('run', '.exe' if is_win or is_cygwin else '')
  468. self.exefiles = TOC([(os.path.basename(exe), exe, 'EXECUTABLE')])
  469. self.__postinit__()
  470. _GUTS = (# input parameters
  471. ('name', _check_guts_eq),
  472. ('console', _check_guts_eq),
  473. ('debug', _check_guts_eq),
  474. ('exclude_binaries', _check_guts_eq),
  475. ('icon', _check_guts_eq),
  476. ('versrsrc', _check_guts_eq),
  477. ('uac_admin', _check_guts_eq),
  478. ('uac_uiaccess', _check_guts_eq),
  479. ('manifest', _check_guts_eq),
  480. ('append_pkg', _check_guts_eq),
  481. ('target_arch', _check_guts_eq),
  482. ('codesign_identity', _check_guts_eq),
  483. ('entitlements_file', _check_guts_eq),
  484. # for the case the directory ius shared between platforms:
  485. ('pkgname', _check_guts_eq),
  486. ('toc', _check_guts_eq),
  487. ('resources', _check_guts_eq),
  488. ('strip', _check_guts_eq),
  489. ('upx', _check_guts_eq),
  490. ('mtm', None,), # checked below
  491. # no calculated/analysed values
  492. ('exefiles', _check_guts_toc),
  493. )
  494. def _check_guts(self, data, last_build):
  495. if not os.path.exists(self.name):
  496. logger.info("Rebuilding %s because %s missing",
  497. self.tocbasename, os.path.basename(self.name))
  498. return 1
  499. if not self.append_pkg and not os.path.exists(self.pkgname):
  500. logger.info("Rebuilding because %s missing",
  501. os.path.basename(self.pkgname))
  502. return 1
  503. if Target._check_guts(self, data, last_build):
  504. return True
  505. if (data['versrsrc'] or data['resources']) and not is_win:
  506. # todo: really ignore :-)
  507. logger.warning('ignoring version, manifest and resources, platform not capable')
  508. if data['icon'] and not (is_win or is_darwin):
  509. logger.warning('ignoring icon, platform not capable')
  510. mtm = data['mtm']
  511. if mtm != misc.mtime(self.name):
  512. logger.info("Rebuilding %s because mtimes don't match", self.tocbasename)
  513. return True
  514. if mtm < misc.mtime(self.pkg.tocfilename):
  515. logger.info("Rebuilding %s because pkg is more recent", self.tocbasename)
  516. return True
  517. return False
  518. def _bootloader_file(self, exe, extension=None):
  519. """
  520. Pick up the right bootloader file - debug, console, windowed.
  521. """
  522. # Having console/windowed bootolader makes sense only on Windows and
  523. # Mac OS X.
  524. if is_win or is_darwin:
  525. if not self.console:
  526. exe = exe + 'w'
  527. # There are two types of bootloaders:
  528. # run - release, no verbose messages in console.
  529. # run_d - contains verbose messages in console.
  530. if self.debug:
  531. exe = exe + '_d'
  532. if extension:
  533. exe = exe + extension
  534. bootloader_file = os.path.join(HOMEPATH, 'PyInstaller', 'bootloader', PLATFORM, exe)
  535. logger.info('Bootloader %s' % bootloader_file)
  536. return bootloader_file
  537. def assemble(self):
  538. from PyInstaller.config import CONF
  539. logger.info("Building EXE from %s", self.tocbasename)
  540. trash = []
  541. if os.path.exists(self.name):
  542. os.remove(self.name)
  543. if not os.path.exists(os.path.dirname(self.name)):
  544. os.makedirs(os.path.dirname(self.name))
  545. exe = self.exefiles[0][1] # pathname of bootloader
  546. if not os.path.exists(exe):
  547. raise SystemExit(_MISSING_BOOTLOADER_ERRORMSG)
  548. if is_win:
  549. fd, tmpnm = tempfile.mkstemp(prefix=os.path.basename(exe) + ".",
  550. dir=CONF['workpath'])
  551. # need to close the file, otherwise copying resources will fail
  552. # with "the file [...] is being used by another process"
  553. os.close(fd)
  554. self._copyfile(exe, tmpnm)
  555. os.chmod(tmpnm, 0o755)
  556. if self.icon != "NONE":
  557. icon.CopyIcons(tmpnm, self.icon)
  558. if self.versrsrc:
  559. versioninfo.SetVersion(tmpnm, self.versrsrc)
  560. for res in self.resources:
  561. res = res.split(",")
  562. for i in range(1, len(res)):
  563. try:
  564. res[i] = int(res[i])
  565. except ValueError:
  566. pass
  567. resfile = res[0]
  568. if not os.path.isabs(resfile):
  569. resfile = os.path.join(CONF['specpath'], resfile)
  570. restype = resname = reslang = None
  571. if len(res) > 1:
  572. restype = res[1]
  573. if len(res) > 2:
  574. resname = res[2]
  575. if len(res) > 3:
  576. reslang = res[3]
  577. try:
  578. winresource.UpdateResourcesFromResFile(tmpnm, resfile,
  579. [restype or "*"],
  580. [resname or "*"],
  581. [reslang or "*"])
  582. except winresource.pywintypes.error as exc:
  583. if exc.args[0] != winresource.ERROR_BAD_EXE_FORMAT:
  584. logger.error("Error while updating resources in %s"
  585. " from resource file %s", tmpnm, resfile, exc_info=1)
  586. continue
  587. # Handle the case where the file contains no resources, and is
  588. # intended as a single resource to be added to the exe.
  589. if not restype or not resname:
  590. logger.error("resource type and/or name not specified")
  591. continue
  592. if "*" in (restype, resname):
  593. logger.error("no wildcards allowed for resource type "
  594. "and name when source file does not "
  595. "contain resources")
  596. continue
  597. try:
  598. winresource.UpdateResourcesFromDataFile(tmpnm,
  599. resfile,
  600. restype,
  601. [resname],
  602. [reslang or 0])
  603. except winresource.pywintypes.error:
  604. logger.error("Error while updating resource %s %s in %s"
  605. " from data file %s",
  606. restype, resname, tmpnm, resfile, exc_info=1)
  607. if self.manifest and not self.exclude_binaries:
  608. self.manifest.update_resources(tmpnm, [1])
  609. trash.append(tmpnm)
  610. exe = tmpnm
  611. # NOTE: Do not look up for bootloader file in the cache because it might
  612. # get corrupted by UPX when UPX is available. See #1863 for details.
  613. if not self.append_pkg:
  614. logger.info("Copying bootloader exe to %s", self.name)
  615. self._copyfile(exe, self.name)
  616. logger.info("Copying archive to %s", self.pkgname)
  617. self._copyfile(self.pkg.name, self.pkgname)
  618. elif is_linux:
  619. self._copyfile(exe, self.name)
  620. logger.info("Appending archive to ELF section in EXE %s", self.name)
  621. retcode, stdout, stderr = exec_command_all(
  622. 'objcopy', '--add-section', 'pydata=%s' % self.pkg.name,
  623. self.name)
  624. logger.debug("objcopy returned %i", retcode)
  625. if stdout:
  626. logger.debug(stdout)
  627. if stderr:
  628. logger.debug(stderr)
  629. if retcode != 0:
  630. raise SystemError("objcopy Failure: %s" % stderr)
  631. elif is_darwin:
  632. import PyInstaller.utils.osx as osxutils
  633. # Copy bootloader
  634. logger.info("Copying bootloader exe to %s", self.name)
  635. with open(self.name, 'wb') as outf:
  636. with open(exe, 'rb') as inf:
  637. shutil.copyfileobj(inf, outf, length=64*1024)
  638. # Convert bootloader to target arch
  639. logger.info("Converting EXE to target arch (%s)", self.target_arch)
  640. osxutils.binary_to_target_arch(self.name, self.target_arch,
  641. display_name='Bootloader EXE')
  642. # Strip signatures from all arch slices. Strictly speaking,
  643. # we need to remove signature (if present) from the last
  644. # slice, because we will be appending data to it. When
  645. # building universal2 bootloaders natively on macOS, only
  646. # arm64 slices have a (dummy) signature. However, when
  647. # cross-compiling with osxcross, we seem to get dummy
  648. # signatures on both x86_64 and arm64 slices. While the former
  649. # should not have any impact, it does seem to cause issues
  650. # with further binary signing using real identity. Therefore,
  651. # we remove all signatures and re-sign the binary using
  652. # dummy signature once the data is appended.
  653. logger.info("Removing signature(s) from EXE")
  654. osxutils.remove_signature_from_binary(self.name)
  655. # Append the data
  656. with open(self.name, 'ab') as outf:
  657. with open(self.pkg.name, 'rb') as inf:
  658. shutil.copyfileobj(inf, outf, length=64*1024)
  659. # If the version of macOS SDK used to build bootloader exceeds
  660. # that of macOS SDK used to built Python library (and, by
  661. # extension, bundled Tcl/Tk libraries), force the version
  662. # declared by the frozen executable to match that of the Python
  663. # library.
  664. # Having macOS attempt to enable new features (based on SDK
  665. # version) for frozen application has no benefit if the Python
  666. # library does not support them as well.
  667. # On the other hand, there seem to be UI issues in tkinter
  668. # due to failed or partial enablement of dark mode (i.e., the
  669. # bootloader executable being built against SDK 10.14 or later,
  670. # which causes macOS to enable dark mode, and Tk libraries being
  671. # built against an earlier SDK version that does not support the
  672. # dark mode). With python.org Intel macOS installers, this
  673. # manifests as black Tk windows and UI elements (see issue #5827),
  674. # while in Anaconda python, it may result in white text on bright
  675. # background.
  676. pylib_version = osxutils.get_macos_sdk_version(
  677. bindepend.get_python_library_path())
  678. exe_version = osxutils.get_macos_sdk_version(self.name)
  679. if pylib_version < exe_version:
  680. logger.info(
  681. "Rewriting executable's macOS SDK version (%d.%d.%d) to "
  682. "match the SDK version of the Python library (%d.%d.%d) "
  683. "in order to avoid inconsistent behavior and potential UI "
  684. "issues in the frozen application.", *exe_version,
  685. *pylib_version)
  686. osxutils.set_macos_sdk_version(self.name, *pylib_version)
  687. # Fix Mach-O header for codesigning on OS X.
  688. logger.info("Fixing EXE for code signing %s", self.name)
  689. osxutils.fix_exe_for_code_signing(self.name)
  690. # Re-sign the binary (either ad-hoc or using real identity,
  691. # if provided)
  692. logger.info("Re-signing the EXE")
  693. osxutils.sign_binary(self.name, self.codesign_identity,
  694. self.entitlements_file)
  695. else:
  696. # Fall back to just append on end of file
  697. logger.info("Appending archive to EXE %s", self.name)
  698. with open(self.name, 'wb') as outf:
  699. # write the bootloader data
  700. with open(exe, 'rb') as infh:
  701. shutil.copyfileobj(infh, outf, length=64*1024)
  702. # write the archive data
  703. with open(self.pkg.name, 'rb') as infh:
  704. shutil.copyfileobj(infh, outf, length=64*1024)
  705. if is_win:
  706. # Set checksum to appease antiviral software.
  707. from PyInstaller.utils.win32.winutils import set_exe_checksum
  708. set_exe_checksum(self.name)
  709. os.chmod(self.name, 0o755)
  710. # get mtime for storing into the guts
  711. self.mtm = misc.mtime(self.name)
  712. for item in trash:
  713. os.remove(item)
  714. logger.info("Building EXE from %s completed successfully.",
  715. self.tocbasename)
  716. def _copyfile(self, infile, outfile):
  717. with open(infile, 'rb') as infh:
  718. with open(outfile, 'wb') as outfh:
  719. shutil.copyfileobj(infh, outfh, length=64*1024)
  720. class COLLECT(Target):
  721. """
  722. In one-dir mode creates the output folder with all necessary files.
  723. """
  724. def __init__(self, *args, **kws):
  725. """
  726. args
  727. One or more arguments that are either TOCs Targets.
  728. kws
  729. Possible keywork arguments:
  730. name
  731. The name of the directory to be built.
  732. """
  733. from PyInstaller.config import CONF
  734. Target.__init__(self)
  735. self.strip_binaries = kws.get('strip', False)
  736. self.upx_exclude = kws.get("upx_exclude", [])
  737. self.console = True
  738. self.target_arch = None
  739. self.codesign_identity = None
  740. self.entitlements_file = None
  741. if CONF['hasUPX']:
  742. self.upx_binaries = kws.get('upx', False)
  743. else:
  744. self.upx_binaries = False
  745. self.name = kws.get('name')
  746. # Old .spec format included in 'name' the path where to collect files
  747. # for the created app.
  748. # app. New format includes only directory name.
  749. #
  750. # The 'name' directory is created in DISTPATH and necessary files are
  751. # then collected to this directory.
  752. self.name = os.path.join(CONF['distpath'], os.path.basename(self.name))
  753. self.toc = TOC()
  754. for arg in args:
  755. if isinstance(arg, TOC):
  756. self.toc.extend(arg)
  757. elif isinstance(arg, Target):
  758. self.toc.append((os.path.basename(arg.name), arg.name, arg.typ))
  759. if isinstance(arg, EXE):
  760. self.console = arg.console
  761. self.target_arch = arg.target_arch
  762. self.codesign_identity = arg.codesign_identity
  763. self.entitlements_file = arg.entitlements_file
  764. for tocnm, fnm, typ in arg.toc:
  765. if tocnm == os.path.basename(arg.name) + ".manifest":
  766. self.toc.append((tocnm, fnm, typ))
  767. if not arg.append_pkg:
  768. self.toc.append((os.path.basename(arg.pkgname), arg.pkgname, 'PKG'))
  769. self.toc.extend(arg.dependencies)
  770. else:
  771. self.toc.extend(arg)
  772. self.__postinit__()
  773. _GUTS = (
  774. # COLLECT always builds, just want the toc to be written out
  775. ('toc', None),
  776. )
  777. def _check_guts(self, data, last_build):
  778. # COLLECT always needs to be executed, since it will clean the output
  779. # directory anyway to make sure there is no existing cruft accumulating
  780. return 1
  781. def assemble(self):
  782. _make_clean_directory(self.name)
  783. logger.info("Building COLLECT %s", self.tocbasename)
  784. for inm, fnm, typ in self.toc:
  785. # Adjust name for extensions, if applicable
  786. inm, fnm, typ = add_suffix_to_extension(inm, fnm, typ)
  787. if not os.path.exists(fnm) or not os.path.isfile(fnm) and is_path_to_egg(fnm):
  788. # file is contained within python egg, it is added with the egg
  789. continue
  790. if os.pardir in os.path.normpath(inm).split(os.sep) \
  791. or os.path.isabs(inm):
  792. raise SystemExit('Security-Alert: try to store file outside '
  793. 'of dist-directory. Aborting. %r' % inm)
  794. tofnm = os.path.join(self.name, inm)
  795. todir = os.path.dirname(tofnm)
  796. if not os.path.exists(todir):
  797. os.makedirs(todir)
  798. elif not os.path.isdir(todir):
  799. raise SystemExit(
  800. "Pyinstaller needs to make a directory, but there "
  801. "already is a file at that path. "
  802. "The file at issue is {!r}".format(todir))
  803. if typ in ('EXTENSION', 'BINARY'):
  804. fnm = checkCache(fnm, strip=self.strip_binaries,
  805. upx=self.upx_binaries,
  806. upx_exclude=self.upx_exclude,
  807. dist_nm=inm,
  808. target_arch=self.target_arch,
  809. codesign_identity=self.codesign_identity,
  810. entitlements_file=self.entitlements_file)
  811. if typ != 'DEPENDENCY':
  812. if os.path.isdir(fnm):
  813. # beacuse shutil.copy2() is the default copy function
  814. # for shutil.copytree, this will also copy file metadata
  815. shutil.copytree(fnm, tofnm)
  816. else:
  817. shutil.copy(fnm, tofnm)
  818. try:
  819. shutil.copystat(fnm, tofnm)
  820. except OSError:
  821. logger.warning("failed to copy flags of %s", fnm)
  822. if typ in ('EXTENSION', 'BINARY'):
  823. os.chmod(tofnm, 0o755)
  824. logger.info("Building COLLECT %s completed successfully.",
  825. self.tocbasename)
  826. class MERGE(object):
  827. """
  828. Merge repeated dependencies from other executables into the first
  829. execuable. Data and binary files are then present only once and some
  830. disk space is thus reduced.
  831. """
  832. def __init__(self, *args):
  833. """
  834. Repeated dependencies are then present only once in the first
  835. executable in the 'args' list. Other executables depend on the
  836. first one. Other executables have to extract necessary files
  837. from the first executable.
  838. args dependencies in a list of (Analysis, id, filename) tuples.
  839. Replace id with the correct filename.
  840. """
  841. # The first Analysis object with all dependencies.
  842. # Any item from the first executable cannot be removed.
  843. self._main = None
  844. self._dependencies = {}
  845. self._id_to_path = {}
  846. for _, i, p in args:
  847. self._id_to_path[os.path.normcase(i)] = p
  848. # Get the longest common path
  849. common_prefix = os.path.commonprefix([os.path.normcase(os.path.abspath(a.scripts[-1][1])) for a, _, _ in args])
  850. self._common_prefix = os.path.dirname(common_prefix)
  851. if self._common_prefix[-1] != os.sep:
  852. self._common_prefix += os.sep
  853. logger.info("Common prefix: %s", self._common_prefix)
  854. self._merge_dependencies(args)
  855. def _merge_dependencies(self, args):
  856. """
  857. Filter shared dependencies to be only in first executable.
  858. """
  859. for analysis, _, _ in args:
  860. path = os.path.normcase(os.path.abspath(analysis.scripts[-1][1]))
  861. path = path.replace(self._common_prefix, "", 1)
  862. path = os.path.splitext(path)[0]
  863. if os.path.normcase(path) in self._id_to_path:
  864. path = self._id_to_path[os.path.normcase(path)]
  865. self._set_dependencies(analysis, path)
  866. def _set_dependencies(self, analysis, path):
  867. """
  868. Synchronize the Analysis result with the needed dependencies.
  869. """
  870. for toc in (analysis.binaries, analysis.datas):
  871. for i, tpl in enumerate(toc):
  872. if not tpl[1] in self._dependencies:
  873. logger.debug("Adding dependency %s located in %s" % (tpl[1], path))
  874. self._dependencies[tpl[1]] = path
  875. else:
  876. dep_path = self._get_relative_path(path, self._dependencies[tpl[1]])
  877. # Ignore references that point to the origin package.
  878. # This can happen if the same resource is listed
  879. # multiple times in TOCs (e.g., once as binary and
  880. # once as data).
  881. if dep_path.endswith(path):
  882. logger.debug("Ignoring self-reference of %s for %s, "
  883. "located in %s - duplicated TOC entry?",
  884. tpl[1], path, dep_path)
  885. # Clear the entry as it is a duplicate.
  886. toc[i] = (None, None, None)
  887. continue
  888. logger.debug("Referencing %s to be a dependecy for %s, located in %s" % (tpl[1], path, dep_path))
  889. # Determine the path relative to dep_path (i.e, within
  890. # the target directory) from the 'name' component
  891. # of the TOC tuple. If entry is EXTENSION, then the
  892. # relative path needs to be reconstructed from the
  893. # name components.
  894. if tpl[2] == 'EXTENSION':
  895. # Split on os.path.sep first, to handle additional
  896. # path prefix (e.g., lib-dynload)
  897. ext_components = tpl[0].split(os.path.sep)
  898. ext_components = ext_components[:-1] \
  899. + ext_components[-1].split('.')[:-1]
  900. if ext_components:
  901. rel_path = os.path.join(*ext_components)
  902. else:
  903. rel_path = ''
  904. else:
  905. rel_path = os.path.dirname(tpl[0])
  906. # Take filename from 'path' (second component of
  907. # TOC tuple); this way, we don't need to worry about
  908. # suffix of extensions.
  909. filename = os.path.basename(tpl[1])
  910. # Construct the full file path relative to dep_path...
  911. filename = os.path.join(rel_path, filename)
  912. # ...and use it in new DEPENDENCY entry
  913. analysis.dependencies.append(
  914. (":".join((dep_path, filename)),
  915. tpl[1],
  916. "DEPENDENCY"))
  917. toc[i] = (None, None, None)
  918. # Clean the list
  919. toc[:] = [tpl for tpl in toc if tpl != (None, None, None)]
  920. # TODO move this function to PyInstaller.compat module (probably improve
  921. # function compat.relpath()
  922. # TODO use os.path.relpath instead
  923. def _get_relative_path(self, startpath, topath):
  924. start = startpath.split(os.sep)[:-1]
  925. start = ['..'] * len(start)
  926. if start:
  927. start.append(topath)
  928. return os.sep.join(start)
  929. else:
  930. return topath
  931. UNCOMPRESSED = 0
  932. COMPRESSED = 1
  933. _MISSING_BOOTLOADER_ERRORMSG = """
  934. Fatal error: PyInstaller does not include a pre-compiled bootloader for your
  935. platform. For more details and instructions how to build the bootloader see
  936. <https://pyinstaller.readthedocs.io/en/stable/bootloader-building.html>
  937. """