writers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. 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 marshal
  19. import os
  20. import shutil
  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_win
  27. from PyInstaller.loader.pyimod02_archive import PYZ_TYPE_DATA, PYZ_TYPE_MODULE, PYZ_TYPE_NSPKG, PYZ_TYPE_PKG
  28. class ArchiveWriter:
  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 writing .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:
  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 useful 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, 1==compressed)
  286. entry[3] is the entry's type code.
  287. If the type code is 'o':
  288. entry[0] is the runtime option
  289. eg: v (meaning verbose imports)
  290. u (meaning unbuffered)
  291. W arg (warning option arg)
  292. s (meaning do site.py processing.
  293. """
  294. dest, source, compress, type = entry[:4]
  295. try:
  296. if type in ('o', 'd'):
  297. return self._write_blob(b"", dest, type)
  298. if type == 's':
  299. # If it is a source code file, compile it to a code object and marshall the object, so it can be
  300. # unmarshalled by the bootloader.
  301. code = get_code_object(dest, source)
  302. code = strip_paths_in_code(code)
  303. return self._write_blob(marshal.dumps(code), dest, type, compress=compress)
  304. elif type == 'm':
  305. with open(source, "rb") as f:
  306. data = f.read()
  307. # Check if it is a PYC file
  308. if data[:4] == BYTECODE_MAGIC:
  309. # Read whole header and load code. According to PEP-552, the PYC header consists of four 32-bit
  310. # words (magic, flags, and, depending on the flags, either timestamp and source file size, or a
  311. # 64-bit hash).
  312. header = data[:16]
  313. code = marshal.loads(data[16:])
  314. # Strip paths from code, marshal back into module form. The header fields (timestamp, size, hash,
  315. # etc.) are all referring to the source file, so our modification of the code object does not affect
  316. # them, and we can re-use the original header.
  317. code = strip_paths_in_code(code)
  318. data = header + marshal.dumps(code)
  319. if source.endswith('.__init__.py'):
  320. type = 'M'
  321. return self._write_blob(data, dest, type, compress=compress)
  322. elif type == "M":
  323. with open(source, "rb") as f:
  324. return self._write_blob(fake_pyc_timestamp(f.read()), dest, type, compress=compress)
  325. else:
  326. self._write_file(source, dest, type, compress=compress)
  327. except IOError:
  328. print("Cannot find ('%s', '%s', %s, '%s')" % (dest, source, compress, type))
  329. raise
  330. def _write_blob(self, blob: bytes, dest, type, compress=False):
  331. """
  332. Write the binary contents (**blob**) of a small file to both the archive and its table of contents.
  333. """
  334. start = self.lib.tell()
  335. length = len(blob)
  336. if compress:
  337. blob = zlib.compress(blob, level=self.LEVEL)
  338. self.lib.write(blob)
  339. self.toc.add(start, len(blob), length, int(compress), type, dest)
  340. def _write_file(self, source, dest, type, compress=False):
  341. """
  342. Stream copy a large file into the archive and update the table of contents.
  343. """
  344. start = self.lib.tell()
  345. length = os.stat(source).st_size
  346. with open(source, 'rb') as f:
  347. if compress:
  348. buffer = bytearray(16 * 1024)
  349. compressor = zlib.compressobj(self.LEVEL)
  350. while 1:
  351. read = f.readinto(buffer)
  352. if not read:
  353. break
  354. self.lib.write(compressor.compress(buffer[:read]))
  355. self.lib.write(compressor.flush())
  356. else:
  357. shutil.copyfileobj(f, self.lib)
  358. self.toc.add(start, self.lib.tell() - start, length, int(compress), type, dest)
  359. def save_trailer(self, tocpos):
  360. """
  361. Save the table of contents and the cookie for the bootlader to disk.
  362. CArchives can be opened from the end - the cookie points back to the start.
  363. """
  364. tocstr = self.toc.tobinary()
  365. self.lib.write(tocstr)
  366. toclen = len(tocstr)
  367. # now save the cookie
  368. total_len = tocpos + toclen + self._cookie_size
  369. pyvers = sys.version_info[0] * 100 + sys.version_info[1]
  370. # Before saving cookie we need to convert it to corresponding C representation.
  371. cookie = struct.pack(
  372. self._cookie_format, self.MAGIC, total_len, tocpos, toclen, pyvers, self._pylib_name.encode('ascii')
  373. )
  374. self.lib.write(cookie)
  375. class SplashWriter(ArchiveWriter):
  376. """
  377. This ArchiveWriter bundles the data for the splash screen resources.
  378. Splash screen resources will be added as an entry into the CArchive with the typecode ARCHIVE_ITEM_SPLASH.
  379. This writer creates the bundled information in the archive.
  380. """
  381. # This struct describes the splash resources as it will be in an buffer inside the bootloader. All necessary parts
  382. # are bundled, the *_len and *_offset fields describe the data beyond this header definition.
  383. # Whereas script and image fields are binary data, the requirements fields describe an array of strings. Each string
  384. # is null-terminated in order to easily iterate over this list from within C.
  385. #
  386. # typedef struct _splash_data_header {
  387. # char tcl_libname[16]; /* Name of tcl library, e.g. tcl86t.dll */
  388. # char tk_libname[16]; /* Name of tk library, e.g. tk86t.dll */
  389. # char tk_lib[16]; /* Tk Library generic, e.g. "tk/" */
  390. # char rundir[16]; /* temp folder inside extraction path in
  391. # * which the dependencies are extracted */
  392. #
  393. # int script_len; /* Length of the script */
  394. # int script_offset; /* Offset (rel to start) of the script */
  395. #
  396. # int image_len; /* Length of the image data */
  397. # int image_offset; /* Offset (rel to start) of the image */
  398. #
  399. # int requirements_len;
  400. # int requirements_offset;
  401. #
  402. # } SPLASH_DATA_HEADER;
  403. #
  404. _header_format = '!16s 16s 16s 16s ii ii ii'
  405. HDRLEN = struct.calcsize(_header_format)
  406. # The created resource will be compressed by the CArchive, so no need to compress the data here.
  407. def __init__(self, archive_path, name_list, tcl_libname, tk_libname, tklib, rundir, image, script):
  408. """
  409. Custom writer for splash screen resources which will be bundled into the CArchive as an entry.
  410. :param archive_path: The filename of the archive to create
  411. :param name_list: List of filenames for the requirements array
  412. :param str tcl_libname: Name of the tcl shared library file
  413. :param str tk_libname: Name of the tk shared library file
  414. :param str tklib: Root of tk library (e.g. tk/)
  415. :param str rundir: Unique path to extract requirements to
  416. :param Union[str, bytes] image: Image like object
  417. :param str script: The tcl/tk script to execute to create the screen.
  418. """
  419. self._tcl_libname = tcl_libname
  420. self._tk_libname = tk_libname
  421. self._tklib = tklib
  422. self._rundir = rundir
  423. self._image = image
  424. self._image_len = 0
  425. self._image_offset = 0
  426. self._script = script
  427. self._script_len = 0
  428. self._script_offset = 0
  429. self._requirements_len = 0
  430. self._requirements_offset = 0
  431. super().__init__(archive_path, name_list)
  432. def add(self, name):
  433. """
  434. This methods adds a name to the requirement list in the splash data. This list (more an array) contains the
  435. names of all files the bootloader needs to extract before the splash screen can be started. The
  436. implementation terminates every name with a null-byte, that keeps the list short memory wise and makes it
  437. iterable from C.
  438. """
  439. name = name.encode('utf-8')
  440. self.lib.write(name + b'\0')
  441. self._requirements_len += len(name) + 1 # zero byte at the end
  442. def update_headers(self, tocpos):
  443. """
  444. Updates the offsets of the fields.
  445. This function is called after self.save_trailer().
  446. :param tocpos:
  447. :return:
  448. """
  449. self.lib.seek(self.start)
  450. self.lib.write(
  451. struct.pack(
  452. self._header_format,
  453. self._tcl_libname.encode("utf-8"),
  454. self._tk_libname.encode("utf-8"),
  455. self._tklib.encode("utf-8"),
  456. self._rundir.encode("utf-8"),
  457. self._script_len,
  458. self._script_offset,
  459. self._image_len,
  460. self._image_offset,
  461. self._requirements_len,
  462. self._requirements_offset,
  463. )
  464. )
  465. def save_trailer(self, script_pos):
  466. """
  467. Adds the image and script.
  468. """
  469. self._requirements_offset = script_pos - self._requirements_len
  470. self._script_offset = script_pos
  471. self.save_script()
  472. self._image_offset = self.lib.tell()
  473. self.save_image()
  474. def save_script(self):
  475. """
  476. Add the tcl/tk script into the archive. This strips out every comment in the source to save some space.
  477. """
  478. self._script_len = len(self._script)
  479. self.lib.write(self._script.encode("utf-8"))
  480. def save_image(self):
  481. """
  482. Copy the image into the archive. If self._image are bytes the buffer will be written directly into the archive,
  483. otherwise it is assumed to be a path and the file will be written into it.
  484. """
  485. if isinstance(self._image, bytes):
  486. # image was converted by PIL/Pillow
  487. buf = self._image
  488. self.lib.write(self._image)
  489. else:
  490. # Copy image to lib
  491. with open(self._image, 'rb') as image_file:
  492. buf = image_file.read()
  493. self._image_len = len(buf)
  494. self.lib.write(buf)