writers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. Utilities to create data structures for embedding Python modules and additional files into the executable.
  13. """
  14. # While an Archive is really an abstraction for any "filesystem within a file", it is tuned for use with
  15. # imputil.FuncImporter. This assumes it contains python code objects, indexed by the the internal name (ie, no '.py').
  16. #
  17. # See pyi_carchive.py for a more general archive (contains anything) that can be understood by a C program.
  18. import io
  19. import marshal
  20. import os
  21. import struct
  22. import sys
  23. import zlib
  24. from types import CodeType
  25. from PyInstaller.building.utils import fake_pyc_timestamp, get_code_object, strip_paths_in_code
  26. from PyInstaller.compat import BYTECODE_MAGIC, is_py37, is_win
  27. from PyInstaller.loader.pyimod02_archive import PYZ_TYPE_DATA, PYZ_TYPE_MODULE, PYZ_TYPE_NSPKG, PYZ_TYPE_PKG
  28. class ArchiveWriter(object):
  29. """
  30. A base class for a repository of python code objects. The extract method is used by imputil.ArchiveImporter to
  31. get code objects by name (fully qualified name), so an end-user "import a.b" becomes extract('a.__init__') and
  32. extract('a.b').
  33. """
  34. MAGIC = b'PYL\0'
  35. HDRLEN = 12 # default is MAGIC followed by python's magic, int pos of toc
  36. TOCPOS = 8
  37. def __init__(self, archive_path, logical_toc):
  38. """
  39. Create an archive file of name 'archive_path'. logical_toc is a 'logical TOC', a list of (name, path, ...),
  40. where name is the internal name (e.g., 'a') and path is a file to get the object from (e.g., './a.pyc').
  41. """
  42. self.start = 0
  43. self._start_add_entries(archive_path)
  44. self._add_from_table_of_contents(logical_toc)
  45. self._finalize()
  46. def _start_add_entries(self, archive_path):
  47. """
  48. Open an empty archive for addition of entries.
  49. """
  50. self.lib = open(archive_path, 'wb')
  51. # Reserve space for the header.
  52. if self.HDRLEN:
  53. self.lib.write(b'\0' * self.HDRLEN)
  54. # Create an empty table of contents. Use a list to support reproducible builds.
  55. self.toc = []
  56. def _add_from_table_of_contents(self, toc):
  57. """
  58. Add entries from a logical TOC (without absolute positioning info).
  59. An entry in a logical TOC is a tuple:
  60. entry[0] is name (under which it will be saved).
  61. entry[1] is fullpathname of the file.
  62. entry[2] is a flag for its storage format (True or 1 if compressed).
  63. entry[3] is the entry's type code.
  64. """
  65. for toc_entry in toc:
  66. self.add(toc_entry) # The guts of the archive.
  67. def _finalize(self):
  68. """
  69. Finalize an archive which has been opened using _start_add_entries(), writing any needed padding and the
  70. table of contents.
  71. """
  72. toc_pos = self.lib.tell()
  73. self.save_trailer(toc_pos)
  74. if self.HDRLEN:
  75. self.update_headers(toc_pos)
  76. self.lib.close()
  77. # manages keeping the internal TOC and the guts in sync #
  78. def add(self, entry):
  79. """
  80. Override this to influence the mechanics of the Archive. Assumes entry is a seq beginning with (nm, pth, ...),
  81. where nm is the key by which we will be asked for the object. pth is the name of where we find the object.
  82. Overrides of get_obj_from can make use of further elements in entry.
  83. """
  84. nm = entry[0]
  85. pth = entry[1]
  86. pynm, ext = os.path.splitext(os.path.basename(pth))
  87. ispkg = pynm == '__init__'
  88. assert ext in ('.pyc', '.pyo')
  89. self.toc.append((nm, (ispkg, self.lib.tell())))
  90. with open(entry[1], 'rb') as f:
  91. f.seek(8) # skip magic and timestamp
  92. self.lib.write(f.read())
  93. def save_trailer(self, tocpos):
  94. """
  95. Default - toc is a dict Gets marshaled to self.lib
  96. """
  97. try:
  98. self.lib.write(marshal.dumps(self.toc))
  99. # If the TOC to be marshalled contains an unmarshallable object, Python raises a cryptic exception providing no
  100. # details on why such object is unmarshallable. Correct this by iteratively inspecting the TOC for
  101. # unmarshallable objects.
  102. except ValueError as exception:
  103. if str(exception) == 'unmarshallable object':
  104. # List of all marshallable types.
  105. MARSHALLABLE_TYPES = {
  106. bool, int, float, complex, str, bytes, bytearray, tuple, list, set, frozenset, dict, CodeType
  107. }
  108. for module_name, module_tuple in self.toc.items():
  109. if type(module_name) not in MARSHALLABLE_TYPES:
  110. print('Module name "%s" (%s) unmarshallable.' % (module_name, type(module_name)))
  111. if type(module_tuple) not in MARSHALLABLE_TYPES:
  112. print(
  113. 'Module "%s" tuple "%s" (%s) unmarshallable.' %
  114. (module_name, module_tuple, type(module_tuple))
  115. )
  116. elif type(module_tuple) == tuple:
  117. for i in range(len(module_tuple)):
  118. if type(module_tuple[i]) not in MARSHALLABLE_TYPES:
  119. print(
  120. 'Module "%s" tuple index %s item "%s" (%s) unmarshallable.' %
  121. (module_name, i, module_tuple[i], type(module_tuple[i]))
  122. )
  123. raise
  124. def update_headers(self, tocpos):
  125. """
  126. Default - MAGIC + Python's magic + tocpos
  127. """
  128. self.lib.seek(self.start)
  129. self.lib.write(self.MAGIC)
  130. self.lib.write(BYTECODE_MAGIC)
  131. self.lib.write(struct.pack('!i', tocpos))
  132. class ZlibArchiveWriter(ArchiveWriter):
  133. """
  134. ZlibArchive - an archive with compressed entries. Archive is read from the executable created by PyInstaller.
  135. This archive is used for bundling python modules inside the executable.
  136. NOTE: The whole ZlibArchive (PYZ) is compressed, so it is not necessary to compress individual modules.
  137. """
  138. MAGIC = b'PYZ\0'
  139. TOCPOS = 8
  140. HDRLEN = ArchiveWriter.HDRLEN + 5
  141. COMPRESSION_LEVEL = 6 # Default level of the 'zlib' module from Python.
  142. def __init__(self, archive_path, logical_toc, code_dict=None, cipher=None):
  143. """
  144. code_dict dict containing module code objects from ModuleGraph.
  145. """
  146. # Keep references to module code objects constructed by ModuleGraph to avoid writting .pyc/pyo files to hdd.
  147. self.code_dict = code_dict or {}
  148. self.cipher = cipher or None
  149. super().__init__(archive_path, logical_toc)
  150. def add(self, entry):
  151. name, path, typ = entry
  152. if typ == 'PYMODULE':
  153. typ = PYZ_TYPE_MODULE
  154. if path in ('-', None):
  155. # This is a NamespacePackage, modulegraph marks them by using the filename '-'. (But wants to use None,
  156. # so check for None, too, to be forward-compatible.)
  157. typ = PYZ_TYPE_NSPKG
  158. else:
  159. base, ext = os.path.splitext(os.path.basename(path))
  160. if base == '__init__':
  161. typ = PYZ_TYPE_PKG
  162. data = marshal.dumps(self.code_dict[name])
  163. else:
  164. # Any data files, that might be required by pkg_resources.
  165. typ = PYZ_TYPE_DATA
  166. with open(path, 'rb') as fh:
  167. data = fh.read()
  168. # No need to use forward slash as path-separator here since pkg_resources on Windows back slash as
  169. # path-separator.
  170. obj = zlib.compress(data, self.COMPRESSION_LEVEL)
  171. # First compress then encrypt.
  172. if self.cipher:
  173. obj = self.cipher.encrypt(obj)
  174. self.toc.append((name, (typ, self.lib.tell(), len(obj))))
  175. self.lib.write(obj)
  176. def update_headers(self, tocpos):
  177. """
  178. Add level.
  179. """
  180. ArchiveWriter.update_headers(self, tocpos)
  181. self.lib.write(struct.pack('!B', self.cipher is not None))
  182. class CTOC(object):
  183. """
  184. A class encapsulating the table of contents of a CArchive.
  185. When written to disk, it is easily read from C.
  186. """
  187. # (structlen, dpos, dlen, ulen, flag, typcd) followed by name
  188. ENTRYSTRUCT = '!iIIIBB'
  189. ENTRYLEN = struct.calcsize(ENTRYSTRUCT)
  190. def __init__(self):
  191. self.data = []
  192. def tobinary(self):
  193. """
  194. Return self as a binary string.
  195. """
  196. rslt = []
  197. for (dpos, dlen, ulen, flag, typcd, nm) in self.data:
  198. # Encode all names using UTF-8. This should be safe as standard python modules only contain ascii-characters
  199. # (and standard shared libraries should have the same), and thus the C-code still can handle this correctly.
  200. nm = nm.encode('utf-8')
  201. nmlen = len(nm) + 1 # add 1 for a '\0'
  202. # align to 16 byte boundary so xplatform C can read
  203. toclen = nmlen + self.ENTRYLEN
  204. if toclen % 16 == 0:
  205. pad = b'\0'
  206. else:
  207. padlen = 16 - (toclen % 16)
  208. pad = b'\0' * padlen
  209. nmlen = nmlen + padlen
  210. rslt.append(
  211. struct.pack(
  212. self.ENTRYSTRUCT + '%is' % nmlen, nmlen + self.ENTRYLEN, dpos, dlen, ulen, flag, ord(typcd),
  213. nm + pad
  214. )
  215. )
  216. return b''.join(rslt)
  217. def add(self, dpos, dlen, ulen, flag, typcd, nm):
  218. """
  219. Add an entry to the table of contents.
  220. DPOS is data position.
  221. DLEN is data length.
  222. ULEN is the uncompressed data len.
  223. FLAG says if the data is compressed.
  224. TYPCD is the "type" of the entry (used by the C code)
  225. NM is the entry's name.
  226. This function is used only while creating an executable.
  227. """
  228. # Ensure forward slashes in paths are on Windows converted to back slashes '\\' since on Windows the bootloader
  229. # works only with back slashes.
  230. nm = os.path.normpath(nm)
  231. if is_win and os.path.sep == '/':
  232. # When building under MSYS, the above path normalization uses Unix-style separators, so replace them
  233. # manually.
  234. nm = nm.replace(os.path.sep, '\\')
  235. self.data.append((dpos, dlen, ulen, flag, typcd, nm))
  236. class CArchiveWriter(ArchiveWriter):
  237. """
  238. An Archive subclass that can hold arbitrary data.
  239. This class encapsulates all files that are bundled within an executable. It can contain ZlibArchive (Python .pyc
  240. files), dlls, Python C extensions and all other data files that are bundled in --onefile mode.
  241. Easily handled from C or from Python.
  242. """
  243. # MAGIC is usefull to verify that conversion of Python data types to C structure and back works properly.
  244. MAGIC = b'MEI\014\013\012\013\016'
  245. HDRLEN = 0
  246. LEVEL = 9
  247. # Cookie - holds some information for the bootloader. C struct format definition. '!' at the beginning means network
  248. # byte order. C struct looks like:
  249. #
  250. # typedef struct _cookie {
  251. # char magic[8]; /* 'MEI\014\013\012\013\016' */
  252. # uint32_t len; /* len of entire package */
  253. # uint32_t TOC; /* pos (rel to start) of TableOfContents */
  254. # int TOClen; /* length of TableOfContents */
  255. # int pyvers; /* new in v4 */
  256. # char pylibname[64]; /* Filename of Python dynamic library. */
  257. # } COOKIE;
  258. #
  259. _cookie_format = '!8sIIii64s'
  260. _cookie_size = struct.calcsize(_cookie_format)
  261. def __init__(self, archive_path, logical_toc, pylib_name):
  262. """
  263. Constructor.
  264. archive_path path name of file (create empty CArchive if path is None).
  265. start is the seekposition within PATH.
  266. len is the length of the CArchive (if 0, then read till EOF).
  267. pylib_name name of Python DLL which bootloader will use.
  268. """
  269. self._pylib_name = pylib_name
  270. # A CArchive created from scratch starts at 0, no leading bootloader.
  271. super().__init__(archive_path, logical_toc)
  272. def _start_add_entries(self, path):
  273. """
  274. Open an empty archive for addition of entries.
  275. """
  276. super()._start_add_entries(path)
  277. # Override parents' toc {} with a class.
  278. self.toc = CTOC()
  279. def add(self, entry):
  280. """
  281. Add an ENTRY to the CArchive.
  282. ENTRY must have:
  283. entry[0] is name (under which it will be saved).
  284. entry[1] is fullpathname of the file.
  285. entry[2] is a flag for it's storage format (0==uncompressed,
  286. 1==compressed)
  287. entry[3] is the entry's type code.
  288. Version 5:
  289. If the type code is 'o':
  290. entry[0] is the runtime option
  291. eg: v (meaning verbose imports)
  292. u (meaning unbuffered)
  293. W arg (warning option arg)
  294. s (meaning do site.py processing.
  295. """
  296. (nm, pathnm, flag, typcd) = entry[:4]
  297. # FIXME Could we make the version 5 the default one?
  298. # Version 5 - allow type 'o' = runtime option.
  299. code_data = None
  300. fh = None
  301. try:
  302. if typcd in ('o', 'd'):
  303. ulen = 0
  304. flag = 0
  305. elif typcd == 's':
  306. # If it is a source code file, compile it to a code object and marshall the object, so it can be
  307. # unmarshalled by the bootloader.
  308. code = get_code_object(nm, pathnm)
  309. code = strip_paths_in_code(code)
  310. code_data = marshal.dumps(code)
  311. ulen = len(code_data)
  312. elif typcd == 'm':
  313. fh = open(pathnm, 'rb')
  314. ulen = os.fstat(fh.fileno()).st_size
  315. # Check if it is a PYC file
  316. header = fh.read(4)
  317. fh.seek(0)
  318. if header == BYTECODE_MAGIC:
  319. # Read whole header and load code. According to PEP-552, in python versions prior to 3.7, the PYC
  320. # header consists of three 32-bit words (magic, timestamp, and source file size).
  321. # From python 3.7 on, the PYC header was extended to four 32-bit words (magic, flags, and, depending
  322. # on the flags, either timestamp and source file size, or a 64-bit hash).
  323. if is_py37:
  324. header = fh.read(16)
  325. else:
  326. header = fh.read(12)
  327. code = marshal.load(fh)
  328. # Strip paths from code, marshal back into module form. The header fields (timestamp, size, hash,
  329. # etc.) are all referring to the source file, so our modification of the code object does not affect
  330. # them, and we can re-use the original header.
  331. code = strip_paths_in_code(code)
  332. data = header + marshal.dumps(code)
  333. # Create file-like object for timestamp re-write in the subsequent steps.
  334. fh = io.BytesIO(data)
  335. ulen = len(data)
  336. else:
  337. fh = open(pathnm, 'rb')
  338. ulen = os.fstat(fh.fileno()).st_size
  339. except IOError:
  340. print("Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd))
  341. raise
  342. where = self.lib.tell()
  343. assert flag in range(3)
  344. if not fh and not code_data:
  345. # No need to write anything.
  346. pass
  347. elif flag == 1:
  348. comprobj = zlib.compressobj(self.LEVEL)
  349. if code_data is not None:
  350. self.lib.write(comprobj.compress(code_data))
  351. else:
  352. assert fh
  353. # We only want to change it for pyc files.
  354. modify_header = typcd in ('M', 'm', 's')
  355. while 1:
  356. buf = fh.read(16 * 1024)
  357. if not buf:
  358. break
  359. if modify_header:
  360. modify_header = False
  361. buf = fake_pyc_timestamp(buf)
  362. self.lib.write(comprobj.compress(buf))
  363. self.lib.write(comprobj.flush())
  364. else:
  365. if code_data is not None:
  366. self.lib.write(code_data)
  367. else:
  368. assert fh
  369. while 1:
  370. buf = fh.read(16 * 1024)
  371. if not buf:
  372. break
  373. self.lib.write(buf)
  374. dlen = self.lib.tell() - where
  375. if typcd == 'm':
  376. if pathnm.find('.__init__.py') > -1:
  377. typcd = 'M'
  378. if fh:
  379. fh.close()
  380. # Record the entry in the CTOC
  381. self.toc.add(where, dlen, ulen, flag, typcd, nm)
  382. def save_trailer(self, tocpos):
  383. """
  384. Save the table of contents and the cookie for the bootlader to disk.
  385. CArchives can be opened from the end - the cookie points back to the start.
  386. """
  387. tocstr = self.toc.tobinary()
  388. self.lib.write(tocstr)
  389. toclen = len(tocstr)
  390. # now save teh cookie
  391. total_len = tocpos + toclen + self._cookie_size
  392. pyvers = sys.version_info[0] * 100 + sys.version_info[1]
  393. # Before saving cookie we need to convert it to corresponding C representation.
  394. cookie = struct.pack(
  395. self._cookie_format, self.MAGIC, total_len, tocpos, toclen, pyvers, self._pylib_name.encode('ascii')
  396. )
  397. self.lib.write(cookie)
  398. class SplashWriter(ArchiveWriter):
  399. """
  400. This ArchiveWriter bundles the data for the splash screen resources.
  401. Splash screen resources will be added as an entry into the CArchive with the typecode ARCHIVE_ITEM_SPLASH.
  402. This writer creates the bundled information in the archive.
  403. """
  404. # This struct describes the splash resources as it will be in an buffer inside the bootloader. All necessary parts
  405. # are bundled, the *_len and *_offset fields describe the data beyond this header definition.
  406. # Whereas script and image fields are binary data, the requirements fields describe an array of strings. Each string
  407. # is null-terminated in order to easily iterate over this list from within C.
  408. #
  409. # typedef struct _splash_data_header {
  410. # char tcl_libname[16]; /* Name of tcl library, e.g. tcl86t.dll */
  411. # char tk_libname[16]; /* Name of tk library, e.g. tk86t.dll */
  412. # char tk_lib[16]; /* Tk Library generic, e.g. "tk/" */
  413. # char rundir[16]; /* temp folder inside extraction path in
  414. # * which the dependencies are extracted */
  415. #
  416. # int script_len; /* Length of the script */
  417. # int script_offset; /* Offset (rel to start) of the script */
  418. #
  419. # int image_len; /* Length of the image data */
  420. # int image_offset; /* Offset (rel to start) of the image */
  421. #
  422. # int requirements_len;
  423. # int requirements_offset;
  424. #
  425. # } SPLASH_DATA_HEADER;
  426. #
  427. _header_format = '!16s 16s 16s 16s ii ii ii'
  428. HDRLEN = struct.calcsize(_header_format)
  429. # The created resource will be compressed by the CArchive, so no need to compress the data here.
  430. def __init__(self, archive_path, name_list, tcl_libname, tk_libname, tklib, rundir, image, script):
  431. """
  432. Custom writer for splash screen resources which will be bundled into the CArchive as an entry.
  433. :param archive_path: The filename of the archive to create
  434. :param name_list: List of filenames for the requirements array
  435. :param str tcl_libname: Name of the tcl shared library file
  436. :param str tk_libname: Name of the tk shared library file
  437. :param str tklib: Root of tk library (e.g. tk/)
  438. :param str rundir: Unique path to extract requirements to
  439. :param Union[str, bytes] image: Image like object
  440. :param str script: The tcl/tk script to execute to create the screen.
  441. """
  442. self._tcl_libname = tcl_libname
  443. self._tk_libname = tk_libname
  444. self._tklib = tklib
  445. self._rundir = rundir
  446. self._image = image
  447. self._image_len = 0
  448. self._image_offset = 0
  449. self._script = script
  450. self._script_len = 0
  451. self._script_offset = 0
  452. self._requirements_len = 0
  453. self._requirements_offset = 0
  454. super().__init__(archive_path, name_list)
  455. def add(self, name):
  456. """
  457. This methods adds a name to the requirement list in the splash data. This list (more an array) contains the
  458. names of all files the bootloader needs to extract before the splash screen can be started. The
  459. implementation terminates every name with a null-byte, that keeps the list short memory wise and makes it
  460. iterable from C.
  461. """
  462. name = name.encode('utf-8')
  463. self.lib.write(name + b'\0')
  464. self._requirements_len += len(name) + 1 # zero byte at the end
  465. def update_headers(self, tocpos):
  466. """
  467. Updates the offsets of the fields.
  468. This function is called after self.save_trailer().
  469. :param tocpos:
  470. :return:
  471. """
  472. self.lib.seek(self.start)
  473. self.lib.write(
  474. struct.pack(
  475. self._header_format,
  476. self._tcl_libname.encode("utf-8"),
  477. self._tk_libname.encode("utf-8"),
  478. self._tklib.encode("utf-8"),
  479. self._rundir.encode("utf-8"),
  480. self._script_len,
  481. self._script_offset,
  482. self._image_len,
  483. self._image_offset,
  484. self._requirements_len,
  485. self._requirements_offset,
  486. )
  487. )
  488. def save_trailer(self, script_pos):
  489. """
  490. Adds the image and script.
  491. """
  492. self._requirements_offset = script_pos - self._requirements_len
  493. self._script_offset = script_pos
  494. self.save_script()
  495. self._image_offset = self.lib.tell()
  496. self.save_image()
  497. def save_script(self):
  498. """
  499. Add the tcl/tk script into the archive. This strips out every comment in the source to save some space.
  500. """
  501. self._script_len = len(self._script)
  502. self.lib.write(self._script.encode("utf-8"))
  503. def save_image(self):
  504. """
  505. Copy the image into the archive. If self._image are bytes the buffer will be written directly into the archive,
  506. otherwise it is assumed to be a path and the file will be written into it.
  507. """
  508. if isinstance(self._image, bytes):
  509. # image was converted by PIL/Pillow
  510. buf = self._image
  511. self.lib.write(self._image)
  512. else:
  513. # Copy image to lib
  514. with open(self._image, 'rb') as image_file:
  515. buf = image_file.read()
  516. self._image_len = len(buf)
  517. self.lib.write(buf)