logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

zipimport.py (30143B)


  1. """zipimport provides support for importing Python modules from Zip archives.
  2. This module exports three objects:
  3. - zipimporter: a class; its constructor takes a path to a Zip archive.
  4. - ZipImportError: exception raised by zipimporter objects. It's a
  5. subclass of ImportError, so it can be caught as ImportError, too.
  6. - _zip_directory_cache: a dict, mapping archive paths to zip directory
  7. info dicts, as used in zipimporter._files.
  8. It is usually not needed to use the zipimport module explicitly; it is
  9. used by the builtin import mechanism for sys.path items that are paths
  10. to Zip archives.
  11. """
  12. #from importlib import _bootstrap_external
  13. #from importlib import _bootstrap # for _verbose_message
  14. import _frozen_importlib_external as _bootstrap_external
  15. from _frozen_importlib_external import _unpack_uint16, _unpack_uint32
  16. import _frozen_importlib as _bootstrap # for _verbose_message
  17. import _imp # for check_hash_based_pycs
  18. import _io # for open
  19. import marshal # for loads
  20. import sys # for modules
  21. import time # for mktime
  22. import _warnings # For warn()
  23. __all__ = ['ZipImportError', 'zipimporter']
  24. path_sep = _bootstrap_external.path_sep
  25. alt_path_sep = _bootstrap_external.path_separators[1:]
  26. class ZipImportError(ImportError):
  27. pass
  28. # _read_directory() cache
  29. _zip_directory_cache = {}
  30. _module_type = type(sys)
  31. END_CENTRAL_DIR_SIZE = 22
  32. STRING_END_ARCHIVE = b'PK\x05\x06'
  33. MAX_COMMENT_LEN = (1 << 16) - 1
  34. class zipimporter(_bootstrap_external._LoaderBasics):
  35. """zipimporter(archivepath) -> zipimporter object
  36. Create a new zipimporter instance. 'archivepath' must be a path to
  37. a zipfile, or to a specific path inside a zipfile. For example, it can be
  38. '/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a
  39. valid directory inside the archive.
  40. 'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip
  41. archive.
  42. The 'archive' attribute of zipimporter objects contains the name of the
  43. zipfile targeted.
  44. """
  45. # Split the "subdirectory" from the Zip archive path, lookup a matching
  46. # entry in sys.path_importer_cache, fetch the file directory from there
  47. # if found, or else read it from the archive.
  48. def __init__(self, path):
  49. if not isinstance(path, str):
  50. import os
  51. path = os.fsdecode(path)
  52. if not path:
  53. raise ZipImportError('archive path is empty', path=path)
  54. if alt_path_sep:
  55. path = path.replace(alt_path_sep, path_sep)
  56. prefix = []
  57. while True:
  58. try:
  59. st = _bootstrap_external._path_stat(path)
  60. except (OSError, ValueError):
  61. # On Windows a ValueError is raised for too long paths.
  62. # Back up one path element.
  63. dirname, basename = _bootstrap_external._path_split(path)
  64. if dirname == path:
  65. raise ZipImportError('not a Zip file', path=path)
  66. path = dirname
  67. prefix.append(basename)
  68. else:
  69. # it exists
  70. if (st.st_mode & 0o170000) != 0o100000: # stat.S_ISREG
  71. # it's a not file
  72. raise ZipImportError('not a Zip file', path=path)
  73. break
  74. try:
  75. files = _zip_directory_cache[path]
  76. except KeyError:
  77. files = _read_directory(path)
  78. _zip_directory_cache[path] = files
  79. self._files = files
  80. self.archive = path
  81. # a prefix directory following the ZIP file path.
  82. self.prefix = _bootstrap_external._path_join(*prefix[::-1])
  83. if self.prefix:
  84. self.prefix += path_sep
  85. # Check whether we can satisfy the import of the module named by
  86. # 'fullname', or whether it could be a portion of a namespace
  87. # package. Return self if we can load it, a string containing the
  88. # full path if it's a possible namespace portion, None if we
  89. # can't load it.
  90. def find_loader(self, fullname, path=None):
  91. """find_loader(fullname, path=None) -> self, str or None.
  92. Search for a module specified by 'fullname'. 'fullname' must be the
  93. fully qualified (dotted) module name. It returns the zipimporter
  94. instance itself if the module was found, a string containing the
  95. full path name if it's possibly a portion of a namespace package,
  96. or None otherwise. The optional 'path' argument is ignored -- it's
  97. there for compatibility with the importer protocol.
  98. Deprecated since Python 3.10. Use find_spec() instead.
  99. """
  100. _warnings.warn("zipimporter.find_loader() is deprecated and slated for "
  101. "removal in Python 3.12; use find_spec() instead",
  102. DeprecationWarning)
  103. mi = _get_module_info(self, fullname)
  104. if mi is not None:
  105. # This is a module or package.
  106. return self, []
  107. # Not a module or regular package. See if this is a directory, and
  108. # therefore possibly a portion of a namespace package.
  109. # We're only interested in the last path component of fullname
  110. # earlier components are recorded in self.prefix.
  111. modpath = _get_module_path(self, fullname)
  112. if _is_dir(self, modpath):
  113. # This is possibly a portion of a namespace
  114. # package. Return the string representing its path,
  115. # without a trailing separator.
  116. return None, [f'{self.archive}{path_sep}{modpath}']
  117. return None, []
  118. # Check whether we can satisfy the import of the module named by
  119. # 'fullname'. Return self if we can, None if we can't.
  120. def find_module(self, fullname, path=None):
  121. """find_module(fullname, path=None) -> self or None.
  122. Search for a module specified by 'fullname'. 'fullname' must be the
  123. fully qualified (dotted) module name. It returns the zipimporter
  124. instance itself if the module was found, or None if it wasn't.
  125. The optional 'path' argument is ignored -- it's there for compatibility
  126. with the importer protocol.
  127. Deprecated since Python 3.10. Use find_spec() instead.
  128. """
  129. _warnings.warn("zipimporter.find_module() is deprecated and slated for "
  130. "removal in Python 3.12; use find_spec() instead",
  131. DeprecationWarning)
  132. return self.find_loader(fullname, path)[0]
  133. def find_spec(self, fullname, target=None):
  134. """Create a ModuleSpec for the specified module.
  135. Returns None if the module cannot be found.
  136. """
  137. module_info = _get_module_info(self, fullname)
  138. if module_info is not None:
  139. return _bootstrap.spec_from_loader(fullname, self, is_package=module_info)
  140. else:
  141. # Not a module or regular package. See if this is a directory, and
  142. # therefore possibly a portion of a namespace package.
  143. # We're only interested in the last path component of fullname
  144. # earlier components are recorded in self.prefix.
  145. modpath = _get_module_path(self, fullname)
  146. if _is_dir(self, modpath):
  147. # This is possibly a portion of a namespace
  148. # package. Return the string representing its path,
  149. # without a trailing separator.
  150. path = f'{self.archive}{path_sep}{modpath}'
  151. spec = _bootstrap.ModuleSpec(name=fullname, loader=None,
  152. is_package=True)
  153. spec.submodule_search_locations.append(path)
  154. return spec
  155. else:
  156. return None
  157. def get_code(self, fullname):
  158. """get_code(fullname) -> code object.
  159. Return the code object for the specified module. Raise ZipImportError
  160. if the module couldn't be imported.
  161. """
  162. code, ispackage, modpath = _get_module_code(self, fullname)
  163. return code
  164. def get_data(self, pathname):
  165. """get_data(pathname) -> string with file data.
  166. Return the data associated with 'pathname'. Raise OSError if
  167. the file wasn't found.
  168. """
  169. if alt_path_sep:
  170. pathname = pathname.replace(alt_path_sep, path_sep)
  171. key = pathname
  172. if pathname.startswith(self.archive + path_sep):
  173. key = pathname[len(self.archive + path_sep):]
  174. try:
  175. toc_entry = self._files[key]
  176. except KeyError:
  177. raise OSError(0, '', key)
  178. return _get_data(self.archive, toc_entry)
  179. # Return a string matching __file__ for the named module
  180. def get_filename(self, fullname):
  181. """get_filename(fullname) -> filename string.
  182. Return the filename for the specified module or raise ZipImportError
  183. if it couldn't be imported.
  184. """
  185. # Deciding the filename requires working out where the code
  186. # would come from if the module was actually loaded
  187. code, ispackage, modpath = _get_module_code(self, fullname)
  188. return modpath
  189. def get_source(self, fullname):
  190. """get_source(fullname) -> source string.
  191. Return the source code for the specified module. Raise ZipImportError
  192. if the module couldn't be found, return None if the archive does
  193. contain the module, but has no source for it.
  194. """
  195. mi = _get_module_info(self, fullname)
  196. if mi is None:
  197. raise ZipImportError(f"can't find module {fullname!r}", name=fullname)
  198. path = _get_module_path(self, fullname)
  199. if mi:
  200. fullpath = _bootstrap_external._path_join(path, '__init__.py')
  201. else:
  202. fullpath = f'{path}.py'
  203. try:
  204. toc_entry = self._files[fullpath]
  205. except KeyError:
  206. # we have the module, but no source
  207. return None
  208. return _get_data(self.archive, toc_entry).decode()
  209. # Return a bool signifying whether the module is a package or not.
  210. def is_package(self, fullname):
  211. """is_package(fullname) -> bool.
  212. Return True if the module specified by fullname is a package.
  213. Raise ZipImportError if the module couldn't be found.
  214. """
  215. mi = _get_module_info(self, fullname)
  216. if mi is None:
  217. raise ZipImportError(f"can't find module {fullname!r}", name=fullname)
  218. return mi
  219. # Load and return the module named by 'fullname'.
  220. def load_module(self, fullname):
  221. """load_module(fullname) -> module.
  222. Load the module specified by 'fullname'. 'fullname' must be the
  223. fully qualified (dotted) module name. It returns the imported
  224. module, or raises ZipImportError if it could not be imported.
  225. Deprecated since Python 3.10. Use exec_module() instead.
  226. """
  227. msg = ("zipimport.zipimporter.load_module() is deprecated and slated for "
  228. "removal in Python 3.12; use exec_module() instead")
  229. _warnings.warn(msg, DeprecationWarning)
  230. code, ispackage, modpath = _get_module_code(self, fullname)
  231. mod = sys.modules.get(fullname)
  232. if mod is None or not isinstance(mod, _module_type):
  233. mod = _module_type(fullname)
  234. sys.modules[fullname] = mod
  235. mod.__loader__ = self
  236. try:
  237. if ispackage:
  238. # add __path__ to the module *before* the code gets
  239. # executed
  240. path = _get_module_path(self, fullname)
  241. fullpath = _bootstrap_external._path_join(self.archive, path)
  242. mod.__path__ = [fullpath]
  243. if not hasattr(mod, '__builtins__'):
  244. mod.__builtins__ = __builtins__
  245. _bootstrap_external._fix_up_module(mod.__dict__, fullname, modpath)
  246. exec(code, mod.__dict__)
  247. except:
  248. del sys.modules[fullname]
  249. raise
  250. try:
  251. mod = sys.modules[fullname]
  252. except KeyError:
  253. raise ImportError(f'Loaded module {fullname!r} not found in sys.modules')
  254. _bootstrap._verbose_message('import {} # loaded from Zip {}', fullname, modpath)
  255. return mod
  256. def get_resource_reader(self, fullname):
  257. """Return the ResourceReader for a package in a zip file.
  258. If 'fullname' is a package within the zip file, return the
  259. 'ResourceReader' object for the package. Otherwise return None.
  260. """
  261. try:
  262. if not self.is_package(fullname):
  263. return None
  264. except ZipImportError:
  265. return None
  266. from importlib.readers import ZipReader
  267. return ZipReader(self, fullname)
  268. def invalidate_caches(self):
  269. """Reload the file data of the archive path."""
  270. try:
  271. self._files = _read_directory(self.archive)
  272. _zip_directory_cache[self.archive] = self._files
  273. except ZipImportError:
  274. _zip_directory_cache.pop(self.archive, None)
  275. self._files = None
  276. def __repr__(self):
  277. return f'<zipimporter object "{self.archive}{path_sep}{self.prefix}">'
  278. # _zip_searchorder defines how we search for a module in the Zip
  279. # archive: we first search for a package __init__, then for
  280. # non-package .pyc, and .py entries. The .pyc entries
  281. # are swapped by initzipimport() if we run in optimized mode. Also,
  282. # '/' is replaced by path_sep there.
  283. _zip_searchorder = (
  284. (path_sep + '__init__.pyc', True, True),
  285. (path_sep + '__init__.py', False, True),
  286. ('.pyc', True, False),
  287. ('.py', False, False),
  288. )
  289. # Given a module name, return the potential file path in the
  290. # archive (without extension).
  291. def _get_module_path(self, fullname):
  292. return self.prefix + fullname.rpartition('.')[2]
  293. # Does this path represent a directory?
  294. def _is_dir(self, path):
  295. # See if this is a "directory". If so, it's eligible to be part
  296. # of a namespace package. We test by seeing if the name, with an
  297. # appended path separator, exists.
  298. dirpath = path + path_sep
  299. # If dirpath is present in self._files, we have a directory.
  300. return dirpath in self._files
  301. # Return some information about a module.
  302. def _get_module_info(self, fullname):
  303. path = _get_module_path(self, fullname)
  304. for suffix, isbytecode, ispackage in _zip_searchorder:
  305. fullpath = path + suffix
  306. if fullpath in self._files:
  307. return ispackage
  308. return None
  309. # implementation
  310. # _read_directory(archive) -> files dict (new reference)
  311. #
  312. # Given a path to a Zip archive, build a dict, mapping file names
  313. # (local to the archive, using SEP as a separator) to toc entries.
  314. #
  315. # A toc_entry is a tuple:
  316. #
  317. # (__file__, # value to use for __file__, available for all files,
  318. # # encoded to the filesystem encoding
  319. # compress, # compression kind; 0 for uncompressed
  320. # data_size, # size of compressed data on disk
  321. # file_size, # size of decompressed data
  322. # file_offset, # offset of file header from start of archive
  323. # time, # mod time of file (in dos format)
  324. # date, # mod data of file (in dos format)
  325. # crc, # crc checksum of the data
  326. # )
  327. #
  328. # Directories can be recognized by the trailing path_sep in the name,
  329. # data_size and file_offset are 0.
  330. def _read_directory(archive):
  331. try:
  332. fp = _io.open_code(archive)
  333. except OSError:
  334. raise ZipImportError(f"can't open Zip file: {archive!r}", path=archive)
  335. with fp:
  336. try:
  337. fp.seek(-END_CENTRAL_DIR_SIZE, 2)
  338. header_position = fp.tell()
  339. buffer = fp.read(END_CENTRAL_DIR_SIZE)
  340. except OSError:
  341. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  342. if len(buffer) != END_CENTRAL_DIR_SIZE:
  343. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  344. if buffer[:4] != STRING_END_ARCHIVE:
  345. # Bad: End of Central Dir signature
  346. # Check if there's a comment.
  347. try:
  348. fp.seek(0, 2)
  349. file_size = fp.tell()
  350. except OSError:
  351. raise ZipImportError(f"can't read Zip file: {archive!r}",
  352. path=archive)
  353. max_comment_start = max(file_size - MAX_COMMENT_LEN -
  354. END_CENTRAL_DIR_SIZE, 0)
  355. try:
  356. fp.seek(max_comment_start)
  357. data = fp.read()
  358. except OSError:
  359. raise ZipImportError(f"can't read Zip file: {archive!r}",
  360. path=archive)
  361. pos = data.rfind(STRING_END_ARCHIVE)
  362. if pos < 0:
  363. raise ZipImportError(f'not a Zip file: {archive!r}',
  364. path=archive)
  365. buffer = data[pos:pos+END_CENTRAL_DIR_SIZE]
  366. if len(buffer) != END_CENTRAL_DIR_SIZE:
  367. raise ZipImportError(f"corrupt Zip file: {archive!r}",
  368. path=archive)
  369. header_position = file_size - len(data) + pos
  370. header_size = _unpack_uint32(buffer[12:16])
  371. header_offset = _unpack_uint32(buffer[16:20])
  372. if header_position < header_size:
  373. raise ZipImportError(f'bad central directory size: {archive!r}', path=archive)
  374. if header_position < header_offset:
  375. raise ZipImportError(f'bad central directory offset: {archive!r}', path=archive)
  376. header_position -= header_size
  377. arc_offset = header_position - header_offset
  378. if arc_offset < 0:
  379. raise ZipImportError(f'bad central directory size or offset: {archive!r}', path=archive)
  380. files = {}
  381. # Start of Central Directory
  382. count = 0
  383. try:
  384. fp.seek(header_position)
  385. except OSError:
  386. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  387. while True:
  388. buffer = fp.read(46)
  389. if len(buffer) < 4:
  390. raise EOFError('EOF read where not expected')
  391. # Start of file header
  392. if buffer[:4] != b'PK\x01\x02':
  393. break # Bad: Central Dir File Header
  394. if len(buffer) != 46:
  395. raise EOFError('EOF read where not expected')
  396. flags = _unpack_uint16(buffer[8:10])
  397. compress = _unpack_uint16(buffer[10:12])
  398. time = _unpack_uint16(buffer[12:14])
  399. date = _unpack_uint16(buffer[14:16])
  400. crc = _unpack_uint32(buffer[16:20])
  401. data_size = _unpack_uint32(buffer[20:24])
  402. file_size = _unpack_uint32(buffer[24:28])
  403. name_size = _unpack_uint16(buffer[28:30])
  404. extra_size = _unpack_uint16(buffer[30:32])
  405. comment_size = _unpack_uint16(buffer[32:34])
  406. file_offset = _unpack_uint32(buffer[42:46])
  407. header_size = name_size + extra_size + comment_size
  408. if file_offset > header_offset:
  409. raise ZipImportError(f'bad local header offset: {archive!r}', path=archive)
  410. file_offset += arc_offset
  411. try:
  412. name = fp.read(name_size)
  413. except OSError:
  414. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  415. if len(name) != name_size:
  416. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  417. # On Windows, calling fseek to skip over the fields we don't use is
  418. # slower than reading the data because fseek flushes stdio's
  419. # internal buffers. See issue #8745.
  420. try:
  421. if len(fp.read(header_size - name_size)) != header_size - name_size:
  422. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  423. except OSError:
  424. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  425. if flags & 0x800:
  426. # UTF-8 file names extension
  427. name = name.decode()
  428. else:
  429. # Historical ZIP filename encoding
  430. try:
  431. name = name.decode('ascii')
  432. except UnicodeDecodeError:
  433. name = name.decode('latin1').translate(cp437_table)
  434. name = name.replace('/', path_sep)
  435. path = _bootstrap_external._path_join(archive, name)
  436. t = (path, compress, data_size, file_size, file_offset, time, date, crc)
  437. files[name] = t
  438. count += 1
  439. _bootstrap._verbose_message('zipimport: found {} names in {!r}', count, archive)
  440. return files
  441. # During bootstrap, we may need to load the encodings
  442. # package from a ZIP file. But the cp437 encoding is implemented
  443. # in Python in the encodings package.
  444. #
  445. # Break out of this dependency by using the translation table for
  446. # the cp437 encoding.
  447. cp437_table = (
  448. # ASCII part, 8 rows x 16 chars
  449. '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
  450. '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'
  451. ' !"#$%&\'()*+,-./'
  452. '0123456789:;<=>?'
  453. '@ABCDEFGHIJKLMNO'
  454. 'PQRSTUVWXYZ[\\]^_'
  455. '`abcdefghijklmno'
  456. 'pqrstuvwxyz{|}~\x7f'
  457. # non-ASCII part, 16 rows x 8 chars
  458. '\xc7\xfc\xe9\xe2\xe4\xe0\xe5\xe7'
  459. '\xea\xeb\xe8\xef\xee\xec\xc4\xc5'
  460. '\xc9\xe6\xc6\xf4\xf6\xf2\xfb\xf9'
  461. '\xff\xd6\xdc\xa2\xa3\xa5\u20a7\u0192'
  462. '\xe1\xed\xf3\xfa\xf1\xd1\xaa\xba'
  463. '\xbf\u2310\xac\xbd\xbc\xa1\xab\xbb'
  464. '\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556'
  465. '\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510'
  466. '\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f'
  467. '\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567'
  468. '\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b'
  469. '\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580'
  470. '\u03b1\xdf\u0393\u03c0\u03a3\u03c3\xb5\u03c4'
  471. '\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229'
  472. '\u2261\xb1\u2265\u2264\u2320\u2321\xf7\u2248'
  473. '\xb0\u2219\xb7\u221a\u207f\xb2\u25a0\xa0'
  474. )
  475. _importing_zlib = False
  476. # Return the zlib.decompress function object, or NULL if zlib couldn't
  477. # be imported. The function is cached when found, so subsequent calls
  478. # don't import zlib again.
  479. def _get_decompress_func():
  480. global _importing_zlib
  481. if _importing_zlib:
  482. # Someone has a zlib.py[co] in their Zip file
  483. # let's avoid a stack overflow.
  484. _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
  485. raise ZipImportError("can't decompress data; zlib not available")
  486. _importing_zlib = True
  487. try:
  488. from zlib import decompress
  489. except Exception:
  490. _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
  491. raise ZipImportError("can't decompress data; zlib not available")
  492. finally:
  493. _importing_zlib = False
  494. _bootstrap._verbose_message('zipimport: zlib available')
  495. return decompress
  496. # Given a path to a Zip file and a toc_entry, return the (uncompressed) data.
  497. def _get_data(archive, toc_entry):
  498. datapath, compress, data_size, file_size, file_offset, time, date, crc = toc_entry
  499. if data_size < 0:
  500. raise ZipImportError('negative data size')
  501. with _io.open_code(archive) as fp:
  502. # Check to make sure the local file header is correct
  503. try:
  504. fp.seek(file_offset)
  505. except OSError:
  506. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  507. buffer = fp.read(30)
  508. if len(buffer) != 30:
  509. raise EOFError('EOF read where not expected')
  510. if buffer[:4] != b'PK\x03\x04':
  511. # Bad: Local File Header
  512. raise ZipImportError(f'bad local file header: {archive!r}', path=archive)
  513. name_size = _unpack_uint16(buffer[26:28])
  514. extra_size = _unpack_uint16(buffer[28:30])
  515. header_size = 30 + name_size + extra_size
  516. file_offset += header_size # Start of file data
  517. try:
  518. fp.seek(file_offset)
  519. except OSError:
  520. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  521. raw_data = fp.read(data_size)
  522. if len(raw_data) != data_size:
  523. raise OSError("zipimport: can't read data")
  524. if compress == 0:
  525. # data is not compressed
  526. return raw_data
  527. # Decompress with zlib
  528. try:
  529. decompress = _get_decompress_func()
  530. except Exception:
  531. raise ZipImportError("can't decompress data; zlib not available")
  532. return decompress(raw_data, -15)
  533. # Lenient date/time comparison function. The precision of the mtime
  534. # in the archive is lower than the mtime stored in a .pyc: we
  535. # must allow a difference of at most one second.
  536. def _eq_mtime(t1, t2):
  537. # dostime only stores even seconds, so be lenient
  538. return abs(t1 - t2) <= 1
  539. # Given the contents of a .py[co] file, unmarshal the data
  540. # and return the code object. Raises ImportError it the magic word doesn't
  541. # match, or if the recorded .py[co] metadata does not match the source.
  542. def _unmarshal_code(self, pathname, fullpath, fullname, data):
  543. exc_details = {
  544. 'name': fullname,
  545. 'path': fullpath,
  546. }
  547. flags = _bootstrap_external._classify_pyc(data, fullname, exc_details)
  548. hash_based = flags & 0b1 != 0
  549. if hash_based:
  550. check_source = flags & 0b10 != 0
  551. if (_imp.check_hash_based_pycs != 'never' and
  552. (check_source or _imp.check_hash_based_pycs == 'always')):
  553. source_bytes = _get_pyc_source(self, fullpath)
  554. if source_bytes is not None:
  555. source_hash = _imp.source_hash(
  556. _bootstrap_external._RAW_MAGIC_NUMBER,
  557. source_bytes,
  558. )
  559. _bootstrap_external._validate_hash_pyc(
  560. data, source_hash, fullname, exc_details)
  561. else:
  562. source_mtime, source_size = \
  563. _get_mtime_and_size_of_source(self, fullpath)
  564. if source_mtime:
  565. # We don't use _bootstrap_external._validate_timestamp_pyc
  566. # to allow for a more lenient timestamp check.
  567. if (not _eq_mtime(_unpack_uint32(data[8:12]), source_mtime) or
  568. _unpack_uint32(data[12:16]) != source_size):
  569. _bootstrap._verbose_message(
  570. f'bytecode is stale for {fullname!r}')
  571. return None
  572. code = marshal.loads(data[16:])
  573. if not isinstance(code, _code_type):
  574. raise TypeError(f'compiled module {pathname!r} is not a code object')
  575. return code
  576. _code_type = type(_unmarshal_code.__code__)
  577. # Replace any occurrences of '\r\n?' in the input string with '\n'.
  578. # This converts DOS and Mac line endings to Unix line endings.
  579. def _normalize_line_endings(source):
  580. source = source.replace(b'\r\n', b'\n')
  581. source = source.replace(b'\r', b'\n')
  582. return source
  583. # Given a string buffer containing Python source code, compile it
  584. # and return a code object.
  585. def _compile_source(pathname, source):
  586. source = _normalize_line_endings(source)
  587. return compile(source, pathname, 'exec', dont_inherit=True)
  588. # Convert the date/time values found in the Zip archive to a value
  589. # that's compatible with the time stamp stored in .pyc files.
  590. def _parse_dostime(d, t):
  591. return time.mktime((
  592. (d >> 9) + 1980, # bits 9..15: year
  593. (d >> 5) & 0xF, # bits 5..8: month
  594. d & 0x1F, # bits 0..4: day
  595. t >> 11, # bits 11..15: hours
  596. (t >> 5) & 0x3F, # bits 8..10: minutes
  597. (t & 0x1F) * 2, # bits 0..7: seconds / 2
  598. -1, -1, -1))
  599. # Given a path to a .pyc file in the archive, return the
  600. # modification time of the matching .py file and its size,
  601. # or (0, 0) if no source is available.
  602. def _get_mtime_and_size_of_source(self, path):
  603. try:
  604. # strip 'c' or 'o' from *.py[co]
  605. assert path[-1:] in ('c', 'o')
  606. path = path[:-1]
  607. toc_entry = self._files[path]
  608. # fetch the time stamp of the .py file for comparison
  609. # with an embedded pyc time stamp
  610. time = toc_entry[5]
  611. date = toc_entry[6]
  612. uncompressed_size = toc_entry[3]
  613. return _parse_dostime(date, time), uncompressed_size
  614. except (KeyError, IndexError, TypeError):
  615. return 0, 0
  616. # Given a path to a .pyc file in the archive, return the
  617. # contents of the matching .py file, or None if no source
  618. # is available.
  619. def _get_pyc_source(self, path):
  620. # strip 'c' or 'o' from *.py[co]
  621. assert path[-1:] in ('c', 'o')
  622. path = path[:-1]
  623. try:
  624. toc_entry = self._files[path]
  625. except KeyError:
  626. return None
  627. else:
  628. return _get_data(self.archive, toc_entry)
  629. # Get the code object associated with the module specified by
  630. # 'fullname'.
  631. def _get_module_code(self, fullname):
  632. path = _get_module_path(self, fullname)
  633. import_error = None
  634. for suffix, isbytecode, ispackage in _zip_searchorder:
  635. fullpath = path + suffix
  636. _bootstrap._verbose_message('trying {}{}{}', self.archive, path_sep, fullpath, verbosity=2)
  637. try:
  638. toc_entry = self._files[fullpath]
  639. except KeyError:
  640. pass
  641. else:
  642. modpath = toc_entry[0]
  643. data = _get_data(self.archive, toc_entry)
  644. code = None
  645. if isbytecode:
  646. try:
  647. code = _unmarshal_code(self, modpath, fullpath, fullname, data)
  648. except ImportError as exc:
  649. import_error = exc
  650. else:
  651. code = _compile_source(modpath, data)
  652. if code is None:
  653. # bad magic number or non-matching mtime
  654. # in byte code, try next
  655. continue
  656. modpath = toc_entry[0]
  657. return code, ispackage, modpath
  658. else:
  659. if import_error:
  660. msg = f"module load failed: {import_error}"
  661. raise ZipImportError(msg, name=fullname) from import_error
  662. else:
  663. raise ZipImportError(f"can't find module {fullname!r}", name=fullname)