datastruct.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2023, 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. import os
  12. import pathlib
  13. import warnings
  14. from PyInstaller import log as logging
  15. from PyInstaller.building.utils import _check_guts_eq
  16. from PyInstaller.utils import misc
  17. logger = logging.getLogger(__name__)
  18. def unique_name(entry):
  19. """
  20. Return the filename used to enforce uniqueness for the given TOC entry.
  21. Parameters
  22. ----------
  23. entry : tuple
  24. Returns
  25. -------
  26. unique_name: str
  27. """
  28. name, path, typecode = entry
  29. if typecode in ('BINARY', 'DATA', 'EXTENSION', 'DEPENDENCY'):
  30. name = os.path.normcase(name)
  31. return name
  32. # This class is deprecated and has been replaced by plain lists with explicit normalization (de-duplication) via
  33. # `normalize_toc` and `normalize_pyz_toc` helper functions.
  34. class TOC(list):
  35. """
  36. TOC (Table of Contents) class is a list of tuples of the form (name, path, typecode).
  37. typecode name path description
  38. --------------------------------------------------------------------------------------
  39. EXTENSION Python internal name. Full path name in build. Extension module.
  40. PYSOURCE Python internal name. Full path name in build. Script.
  41. PYMODULE Python internal name. Full path name in build. Pure Python module (including __init__ modules).
  42. PYZ Runtime name. Full path name in build. A .pyz archive (ZlibArchive data structure).
  43. PKG Runtime name. Full path name in build. A .pkg archive (Carchive data structure).
  44. BINARY Runtime name. Full path name in build. Shared library.
  45. DATA Runtime name. Full path name in build. Arbitrary files.
  46. OPTION The option. Unused. Python runtime option (frozen into executable).
  47. A TOC contains various types of files. A TOC contains no duplicates and preserves order.
  48. PyInstaller uses TOC data type to collect necessary files bundle them into an executable.
  49. """
  50. def __init__(self, initlist=None):
  51. super().__init__()
  52. # Deprecation warning
  53. warnings.warn(
  54. "TOC class is deprecated. Use a plain list of 3-element tuples instead.",
  55. DeprecationWarning,
  56. stacklevel=2,
  57. )
  58. self.filenames = set()
  59. if initlist:
  60. for entry in initlist:
  61. self.append(entry)
  62. def append(self, entry):
  63. if not isinstance(entry, tuple):
  64. logger.info("TOC found a %s, not a tuple", entry)
  65. raise TypeError("Expected tuple, not %s." % type(entry).__name__)
  66. unique = unique_name(entry)
  67. if unique not in self.filenames:
  68. self.filenames.add(unique)
  69. super().append(entry)
  70. def insert(self, pos, entry):
  71. if not isinstance(entry, tuple):
  72. logger.info("TOC found a %s, not a tuple", entry)
  73. raise TypeError("Expected tuple, not %s." % type(entry).__name__)
  74. unique = unique_name(entry)
  75. if unique not in self.filenames:
  76. self.filenames.add(unique)
  77. super().insert(pos, entry)
  78. def __add__(self, other):
  79. result = TOC(self)
  80. result.extend(other)
  81. return result
  82. def __radd__(self, other):
  83. result = TOC(other)
  84. result.extend(self)
  85. return result
  86. def __iadd__(self, other):
  87. for entry in other:
  88. self.append(entry)
  89. return self
  90. def extend(self, other):
  91. # TODO: look if this can be done more efficient with out the loop, e.g. by not using a list as base at all.
  92. for entry in other:
  93. self.append(entry)
  94. def __sub__(self, other):
  95. # Construct new TOC with entries not contained in the other TOC
  96. other = TOC(other)
  97. return TOC([entry for entry in self if unique_name(entry) not in other.filenames])
  98. def __rsub__(self, other):
  99. result = TOC(other)
  100. return result.__sub__(self)
  101. def __setitem__(self, key, value):
  102. if isinstance(key, slice):
  103. if key == slice(None, None, None):
  104. # special case: set the entire list
  105. self.filenames = set()
  106. self.clear()
  107. self.extend(value)
  108. return
  109. else:
  110. raise KeyError("TOC.__setitem__ doesn't handle slices")
  111. else:
  112. old_value = self[key]
  113. old_name = unique_name(old_value)
  114. self.filenames.remove(old_name)
  115. new_name = unique_name(value)
  116. if new_name not in self.filenames:
  117. self.filenames.add(new_name)
  118. super(TOC, self).__setitem__(key, value)
  119. class Target:
  120. invcnum = 0
  121. def __init__(self):
  122. from PyInstaller.config import CONF
  123. # Get a (per class) unique number to avoid conflicts between toc objects
  124. self.invcnum = self.__class__.invcnum
  125. self.__class__.invcnum += 1
  126. self.tocfilename = os.path.join(CONF['workpath'], '%s-%02d.toc' % (self.__class__.__name__, self.invcnum))
  127. self.tocbasename = os.path.basename(self.tocfilename)
  128. self.dependencies = []
  129. def __postinit__(self):
  130. """
  131. Check if the target need to be rebuild and if so, re-assemble.
  132. `__postinit__` is to be called at the end of `__init__` of every subclass of Target. `__init__` is meant to
  133. setup the parameters and `__postinit__` is checking if rebuild is required and in case calls `assemble()`
  134. """
  135. logger.info("checking %s", self.__class__.__name__)
  136. data = None
  137. last_build = misc.mtime(self.tocfilename)
  138. if last_build == 0:
  139. logger.info("Building %s because %s is non existent", self.__class__.__name__, self.tocbasename)
  140. else:
  141. try:
  142. data = misc.load_py_data_struct(self.tocfilename)
  143. except Exception:
  144. logger.info("Building because %s is bad", self.tocbasename)
  145. else:
  146. # create a dict for easier access
  147. data = dict(zip((g[0] for g in self._GUTS), data))
  148. # assemble if previous data was not found or is outdated
  149. if not data or self._check_guts(data, last_build):
  150. self.assemble()
  151. self._save_guts()
  152. _GUTS = []
  153. def _check_guts(self, data, last_build):
  154. """
  155. Returns True if rebuild/assemble is required.
  156. """
  157. if len(data) != len(self._GUTS):
  158. logger.info("Building because %s is bad", self.tocbasename)
  159. return True
  160. for attr, func in self._GUTS:
  161. if func is None:
  162. # no check for this value
  163. continue
  164. if func(attr, data[attr], getattr(self, attr), last_build):
  165. return True
  166. return False
  167. def _save_guts(self):
  168. """
  169. Save the input parameters and the work-product of this run to maybe avoid regenerating it later.
  170. """
  171. data = tuple(getattr(self, g[0]) for g in self._GUTS)
  172. misc.save_py_data_struct(self.tocfilename, data)
  173. class Tree(Target, list):
  174. """
  175. This class is a way of creating a TOC (Table of Contents) list that describes some or all of the files within a
  176. directory.
  177. """
  178. def __init__(self, root=None, prefix=None, excludes=None, typecode='DATA'):
  179. """
  180. root
  181. The root of the tree (on the build system).
  182. prefix
  183. Optional prefix to the names of the target system.
  184. excludes
  185. A list of names to exclude. Two forms are allowed:
  186. name
  187. Files with this basename will be excluded (do not include the path).
  188. *.ext
  189. Any file with the given extension will be excluded.
  190. typecode
  191. The typecode to be used for all files found in this tree. See the TOC class for for information about
  192. the typcodes.
  193. """
  194. Target.__init__(self)
  195. list.__init__(self)
  196. self.root = root
  197. self.prefix = prefix
  198. self.excludes = excludes
  199. self.typecode = typecode
  200. if excludes is None:
  201. self.excludes = []
  202. self.__postinit__()
  203. _GUTS = ( # input parameters
  204. ('root', _check_guts_eq),
  205. ('prefix', _check_guts_eq),
  206. ('excludes', _check_guts_eq),
  207. ('typecode', _check_guts_eq),
  208. ('data', None), # tested below
  209. # no calculated/analysed values
  210. )
  211. def _check_guts(self, data, last_build):
  212. if Target._check_guts(self, data, last_build):
  213. return True
  214. # Walk the collected directories as check if they have been changed - which means files have been added or
  215. # removed. There is no need to check for the files, since `Tree` is only about the directory contents (which is
  216. # the list of files).
  217. stack = [data['root']]
  218. while stack:
  219. d = stack.pop()
  220. if misc.mtime(d) > last_build:
  221. logger.info("Building %s because directory %s changed", self.tocbasename, d)
  222. return True
  223. for nm in os.listdir(d):
  224. path = os.path.join(d, nm)
  225. if os.path.isdir(path):
  226. stack.append(path)
  227. self[:] = data['data'] # collected files
  228. return False
  229. def _save_guts(self):
  230. # Use the attribute `data` to save the list
  231. self.data = self
  232. super()._save_guts()
  233. del self.data
  234. def assemble(self):
  235. logger.info("Building Tree %s", self.tocbasename)
  236. stack = [(self.root, self.prefix)]
  237. excludes = set()
  238. xexcludes = set()
  239. for name in self.excludes:
  240. if name.startswith('*'):
  241. xexcludes.add(name[1:])
  242. else:
  243. excludes.add(name)
  244. result = []
  245. while stack:
  246. dir, prefix = stack.pop()
  247. for filename in os.listdir(dir):
  248. if filename in excludes:
  249. continue
  250. ext = os.path.splitext(filename)[1]
  251. if ext in xexcludes:
  252. continue
  253. fullfilename = os.path.join(dir, filename)
  254. if prefix:
  255. resfilename = os.path.join(prefix, filename)
  256. else:
  257. resfilename = filename
  258. if os.path.isdir(fullfilename):
  259. stack.append((fullfilename, resfilename))
  260. else:
  261. result.append((resfilename, fullfilename, self.typecode))
  262. self[:] = result
  263. def normalize_toc(toc):
  264. # Default priority: 0
  265. _TOC_TYPE_PRIORITIES = {
  266. # DEPENDENCY entries need to replace original entries, so they need the highest priority.
  267. 'DEPENDENCY': 3,
  268. # SYMLINK entries have higher priority than other regular entries
  269. 'SYMLINK': 2,
  270. # BINARY/EXTENSION entries undergo additional processing, so give them precedence over DATA and other entries.
  271. 'BINARY': 1,
  272. 'EXTENSION': 1,
  273. }
  274. def _type_case_normalization_fcn(typecode):
  275. # Case-normalize all entries except OPTION.
  276. return typecode not in {
  277. "OPTION",
  278. }
  279. return _normalize_toc(toc, _TOC_TYPE_PRIORITIES, _type_case_normalization_fcn)
  280. def normalize_pyz_toc(toc):
  281. # Default priority: 0
  282. _TOC_TYPE_PRIORITIES = {
  283. # Ensure that entries with higher optimization level take precedence.
  284. 'PYMODULE-2': 2,
  285. 'PYMODULE-1': 1,
  286. 'PYMODULE': 0,
  287. }
  288. return _normalize_toc(toc, _TOC_TYPE_PRIORITIES)
  289. def _normalize_toc(toc, toc_type_priorities, type_case_normalization_fcn=lambda typecode: False):
  290. options_toc = []
  291. tmp_toc = dict()
  292. for dest_name, src_name, typecode in toc:
  293. # Exempt OPTION entries from de-duplication processing. Some options might allow being specified multiple times.
  294. if typecode == 'OPTION':
  295. options_toc.append(((dest_name, src_name, typecode)))
  296. continue
  297. # Always sanitize the dest_name with `os.path.normpath` to remove any local loops with parent directory path
  298. # components. `pathlib` does not seem to offer equivalent functionality.
  299. dest_name = os.path.normpath(dest_name)
  300. # Normalize the destination name for uniqueness. Use `pathlib.PurePath` to ensure that keys are both
  301. # case-normalized (on OSes where applicable) and directory-separator normalized (just in case).
  302. if type_case_normalization_fcn(typecode):
  303. entry_key = pathlib.PurePath(dest_name)
  304. else:
  305. entry_key = dest_name
  306. existing_entry = tmp_toc.get(entry_key)
  307. if existing_entry is None:
  308. # Entry does not exist - insert
  309. tmp_toc[entry_key] = (dest_name, src_name, typecode)
  310. else:
  311. # Entry already exists - replace if its typecode has higher priority
  312. _, _, existing_typecode = existing_entry
  313. if toc_type_priorities.get(typecode, 0) > toc_type_priorities.get(existing_typecode, 0):
  314. tmp_toc[entry_key] = (dest_name, src_name, typecode)
  315. # Return the items as list. The order matches the original order due to python dict maintaining the insertion order.
  316. # The exception are OPTION entries, which are now placed at the beginning of the TOC.
  317. return options_toc + list(tmp_toc.values())
  318. def toc_process_symbolic_links(toc):
  319. """
  320. Process TOC entries and replace entries whose files are symbolic links with SYMLINK entries (provided original file
  321. is also being collected).
  322. """
  323. # Dictionary of all destination names, for a fast look-up.
  324. all_dest_files = set([dest_name for dest_name, src_name, typecode in toc])
  325. # Process the TOC to create SYMLINK entries
  326. new_toc = []
  327. for entry in toc:
  328. dest_name, src_name, typecode = entry
  329. # Skip entries that are already symbolic links
  330. if typecode == 'SYMLINK':
  331. new_toc.append(entry)
  332. continue
  333. # Skip entries without valid source name (e.g., OPTION)
  334. if not src_name:
  335. new_toc.append(entry)
  336. continue
  337. # Source path is not a symbolic link (i.e., it is a regular file or directory)
  338. if not os.path.islink(src_name):
  339. new_toc.append(entry)
  340. continue
  341. # Try preserving the symbolic link, under strict relative-relationship-preservation check
  342. symlink_entry = _try_preserving_symbolic_link(dest_name, src_name, all_dest_files)
  343. if symlink_entry:
  344. new_toc.append(symlink_entry)
  345. else:
  346. new_toc.append(entry)
  347. return new_toc
  348. def _try_preserving_symbolic_link(dest_name, src_name, all_dest_files):
  349. seen_src_files = set()
  350. # Set initial values for the loop
  351. ref_src_file = src_name
  352. ref_dest_file = dest_name
  353. while True:
  354. # Guard against cyclic links...
  355. if ref_src_file in seen_src_files:
  356. break
  357. seen_src_files.add(ref_src_file)
  358. # Stop when referenced source file is not a symbolic link anymore.
  359. if not os.path.islink(ref_src_file):
  360. break
  361. # Read the symbolic link's target, but do not fully resolve it using os.path.realpath(), because there might be
  362. # other symbolic links involved as well (for example, /lib64 -> /usr/lib64 whereas we are processing
  363. # /lib64/liba.so -> /lib64/liba.so.1)
  364. symlink_target = os.readlink(ref_src_file)
  365. if os.path.isabs(symlink_target):
  366. break # We support only relative symbolic links.
  367. ref_dest_file = os.path.join(os.path.dirname(ref_dest_file), symlink_target)
  368. ref_dest_file = os.path.normpath(ref_dest_file) # remove any '..'
  369. ref_src_file = os.path.join(os.path.dirname(ref_src_file), symlink_target)
  370. ref_src_file = os.path.normpath(ref_src_file) # remove any '..'
  371. # Check if referenced destination file is valid (i.e., we are collecting a file under referenced name).
  372. if ref_dest_file in all_dest_files:
  373. # Sanity check: original source name and current referenced source name must, after complete resolution,
  374. # point to the same file.
  375. if os.path.realpath(src_name) == os.path.realpath(ref_src_file):
  376. # Compute relative link for the destination file (might be modified, if we went over non-collected
  377. # intermediate links).
  378. rel_link = os.path.relpath(ref_dest_file, os.path.dirname(dest_name))
  379. return dest_name, rel_link, 'SYMLINK'
  380. # If referenced destination is not valid, do another iteration in case we are dealing with chained links and we
  381. # are not collecting an intermediate link...
  382. return None