api.py 48 KB

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