zipimport.py 27 KB

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