zipimport.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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 package in a zip file.
  209. If 'fullname' is a package within the zip file, return the
  210. 'ResourceReader' object for the package. Otherwise return None.
  211. """
  212. try:
  213. if not self.is_package(fullname):
  214. return None
  215. except ZipImportError:
  216. return None
  217. from importlib.readers import ZipReader
  218. return ZipReader(self, fullname)
  219. def invalidate_caches(self):
  220. """Reload the file data of the archive path."""
  221. try:
  222. self._files = _read_directory(self.archive)
  223. _zip_directory_cache[self.archive] = self._files
  224. except ZipImportError:
  225. _zip_directory_cache.pop(self.archive, None)
  226. self._files = {}
  227. def __repr__(self):
  228. return f'<zipimporter object "{self.archive}{path_sep}{self.prefix}">'
  229. # _zip_searchorder defines how we search for a module in the Zip
  230. # archive: we first search for a package __init__, then for
  231. # non-package .pyc, and .py entries. The .pyc entries
  232. # are swapped by initzipimport() if we run in optimized mode. Also,
  233. # '/' is replaced by path_sep there.
  234. _zip_searchorder = (
  235. (path_sep + '__init__.pyc', True, True),
  236. (path_sep + '__init__.py', False, True),
  237. ('.pyc', True, False),
  238. ('.py', False, False),
  239. )
  240. # Given a module name, return the potential file path in the
  241. # archive (without extension).
  242. def _get_module_path(self, fullname):
  243. return self.prefix + fullname.rpartition('.')[2]
  244. # Does this path represent a directory?
  245. def _is_dir(self, path):
  246. # See if this is a "directory". If so, it's eligible to be part
  247. # of a namespace package. We test by seeing if the name, with an
  248. # appended path separator, exists.
  249. dirpath = path + path_sep
  250. # If dirpath is present in self._files, we have a directory.
  251. return dirpath in self._files
  252. # Return some information about a module.
  253. def _get_module_info(self, fullname):
  254. path = _get_module_path(self, fullname)
  255. for suffix, isbytecode, ispackage in _zip_searchorder:
  256. fullpath = path + suffix
  257. if fullpath in self._files:
  258. return ispackage
  259. return None
  260. # implementation
  261. # _read_directory(archive) -> files dict (new reference)
  262. #
  263. # Given a path to a Zip archive, build a dict, mapping file names
  264. # (local to the archive, using SEP as a separator) to toc entries.
  265. #
  266. # A toc_entry is a tuple:
  267. #
  268. # (__file__, # value to use for __file__, available for all files,
  269. # # encoded to the filesystem encoding
  270. # compress, # compression kind; 0 for uncompressed
  271. # data_size, # size of compressed data on disk
  272. # file_size, # size of decompressed data
  273. # file_offset, # offset of file header from start of archive
  274. # time, # mod time of file (in dos format)
  275. # date, # mod data of file (in dos format)
  276. # crc, # crc checksum of the data
  277. # )
  278. #
  279. # Directories can be recognized by the trailing path_sep in the name,
  280. # data_size and file_offset are 0.
  281. def _read_directory(archive):
  282. try:
  283. fp = _io.open_code(archive)
  284. except OSError:
  285. raise ZipImportError(f"can't open Zip file: {archive!r}", path=archive)
  286. with fp:
  287. # GH-87235: On macOS all file descriptors for /dev/fd/N share the same
  288. # file offset, reset the file offset after scanning the zipfile diretory
  289. # to not cause problems when some runs 'python3 /dev/fd/9 9<some_script'
  290. start_offset = fp.tell()
  291. try:
  292. try:
  293. fp.seek(-END_CENTRAL_DIR_SIZE, 2)
  294. header_position = fp.tell()
  295. buffer = fp.read(END_CENTRAL_DIR_SIZE)
  296. except OSError:
  297. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  298. if len(buffer) != END_CENTRAL_DIR_SIZE:
  299. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  300. if buffer[:4] != STRING_END_ARCHIVE:
  301. # Bad: End of Central Dir signature
  302. # Check if there's a comment.
  303. try:
  304. fp.seek(0, 2)
  305. file_size = fp.tell()
  306. except OSError:
  307. raise ZipImportError(f"can't read Zip file: {archive!r}",
  308. path=archive)
  309. max_comment_start = max(file_size - MAX_COMMENT_LEN -
  310. END_CENTRAL_DIR_SIZE, 0)
  311. try:
  312. fp.seek(max_comment_start)
  313. data = fp.read()
  314. except OSError:
  315. raise ZipImportError(f"can't read Zip file: {archive!r}",
  316. path=archive)
  317. pos = data.rfind(STRING_END_ARCHIVE)
  318. if pos < 0:
  319. raise ZipImportError(f'not a Zip file: {archive!r}',
  320. path=archive)
  321. buffer = data[pos:pos+END_CENTRAL_DIR_SIZE]
  322. if len(buffer) != END_CENTRAL_DIR_SIZE:
  323. raise ZipImportError(f"corrupt Zip file: {archive!r}",
  324. path=archive)
  325. header_position = file_size - len(data) + pos
  326. header_size = _unpack_uint32(buffer[12:16])
  327. header_offset = _unpack_uint32(buffer[16:20])
  328. if header_position < header_size:
  329. raise ZipImportError(f'bad central directory size: {archive!r}', path=archive)
  330. if header_position < header_offset:
  331. raise ZipImportError(f'bad central directory offset: {archive!r}', path=archive)
  332. header_position -= header_size
  333. arc_offset = header_position - header_offset
  334. if arc_offset < 0:
  335. raise ZipImportError(f'bad central directory size or offset: {archive!r}', path=archive)
  336. files = {}
  337. # Start of Central Directory
  338. count = 0
  339. try:
  340. fp.seek(header_position)
  341. except OSError:
  342. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  343. while True:
  344. buffer = fp.read(46)
  345. if len(buffer) < 4:
  346. raise EOFError('EOF read where not expected')
  347. # Start of file header
  348. if buffer[:4] != b'PK\x01\x02':
  349. break # Bad: Central Dir File Header
  350. if len(buffer) != 46:
  351. raise EOFError('EOF read where not expected')
  352. flags = _unpack_uint16(buffer[8:10])
  353. compress = _unpack_uint16(buffer[10:12])
  354. time = _unpack_uint16(buffer[12:14])
  355. date = _unpack_uint16(buffer[14:16])
  356. crc = _unpack_uint32(buffer[16:20])
  357. data_size = _unpack_uint32(buffer[20:24])
  358. file_size = _unpack_uint32(buffer[24:28])
  359. name_size = _unpack_uint16(buffer[28:30])
  360. extra_size = _unpack_uint16(buffer[30:32])
  361. comment_size = _unpack_uint16(buffer[32:34])
  362. file_offset = _unpack_uint32(buffer[42:46])
  363. header_size = name_size + extra_size + comment_size
  364. if file_offset > header_offset:
  365. raise ZipImportError(f'bad local header offset: {archive!r}', path=archive)
  366. file_offset += arc_offset
  367. try:
  368. name = fp.read(name_size)
  369. except OSError:
  370. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  371. if len(name) != name_size:
  372. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  373. # On Windows, calling fseek to skip over the fields we don't use is
  374. # slower than reading the data because fseek flushes stdio's
  375. # internal buffers. See issue #8745.
  376. try:
  377. if len(fp.read(header_size - name_size)) != header_size - name_size:
  378. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  379. except OSError:
  380. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  381. if flags & 0x800:
  382. # UTF-8 file names extension
  383. name = name.decode()
  384. else:
  385. # Historical ZIP filename encoding
  386. try:
  387. name = name.decode('ascii')
  388. except UnicodeDecodeError:
  389. name = name.decode('latin1').translate(cp437_table)
  390. name = name.replace('/', path_sep)
  391. path = _bootstrap_external._path_join(archive, name)
  392. t = (path, compress, data_size, file_size, file_offset, time, date, crc)
  393. files[name] = t
  394. count += 1
  395. finally:
  396. fp.seek(start_offset)
  397. _bootstrap._verbose_message('zipimport: found {} names in {!r}', count, archive)
  398. return files
  399. # During bootstrap, we may need to load the encodings
  400. # package from a ZIP file. But the cp437 encoding is implemented
  401. # in Python in the encodings package.
  402. #
  403. # Break out of this dependency by using the translation table for
  404. # the cp437 encoding.
  405. cp437_table = (
  406. # ASCII part, 8 rows x 16 chars
  407. '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
  408. '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'
  409. ' !"#$%&\'()*+,-./'
  410. '0123456789:;<=>?'
  411. '@ABCDEFGHIJKLMNO'
  412. 'PQRSTUVWXYZ[\\]^_'
  413. '`abcdefghijklmno'
  414. 'pqrstuvwxyz{|}~\x7f'
  415. # non-ASCII part, 16 rows x 8 chars
  416. '\xc7\xfc\xe9\xe2\xe4\xe0\xe5\xe7'
  417. '\xea\xeb\xe8\xef\xee\xec\xc4\xc5'
  418. '\xc9\xe6\xc6\xf4\xf6\xf2\xfb\xf9'
  419. '\xff\xd6\xdc\xa2\xa3\xa5\u20a7\u0192'
  420. '\xe1\xed\xf3\xfa\xf1\xd1\xaa\xba'
  421. '\xbf\u2310\xac\xbd\xbc\xa1\xab\xbb'
  422. '\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556'
  423. '\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510'
  424. '\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f'
  425. '\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567'
  426. '\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b'
  427. '\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580'
  428. '\u03b1\xdf\u0393\u03c0\u03a3\u03c3\xb5\u03c4'
  429. '\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229'
  430. '\u2261\xb1\u2265\u2264\u2320\u2321\xf7\u2248'
  431. '\xb0\u2219\xb7\u221a\u207f\xb2\u25a0\xa0'
  432. )
  433. _importing_zlib = False
  434. # Return the zlib.decompress function object, or NULL if zlib couldn't
  435. # be imported. The function is cached when found, so subsequent calls
  436. # don't import zlib again.
  437. def _get_decompress_func():
  438. global _importing_zlib
  439. if _importing_zlib:
  440. # Someone has a zlib.py[co] in their Zip file
  441. # let's avoid a stack overflow.
  442. _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
  443. raise ZipImportError("can't decompress data; zlib not available")
  444. _importing_zlib = True
  445. try:
  446. from zlib import decompress
  447. except Exception:
  448. _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
  449. raise ZipImportError("can't decompress data; zlib not available")
  450. finally:
  451. _importing_zlib = False
  452. _bootstrap._verbose_message('zipimport: zlib available')
  453. return decompress
  454. # Given a path to a Zip file and a toc_entry, return the (uncompressed) data.
  455. def _get_data(archive, toc_entry):
  456. datapath, compress, data_size, file_size, file_offset, time, date, crc = toc_entry
  457. if data_size < 0:
  458. raise ZipImportError('negative data size')
  459. with _io.open_code(archive) as fp:
  460. # Check to make sure the local file header is correct
  461. try:
  462. fp.seek(file_offset)
  463. except OSError:
  464. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  465. buffer = fp.read(30)
  466. if len(buffer) != 30:
  467. raise EOFError('EOF read where not expected')
  468. if buffer[:4] != b'PK\x03\x04':
  469. # Bad: Local File Header
  470. raise ZipImportError(f'bad local file header: {archive!r}', path=archive)
  471. name_size = _unpack_uint16(buffer[26:28])
  472. extra_size = _unpack_uint16(buffer[28:30])
  473. header_size = 30 + name_size + extra_size
  474. file_offset += header_size # Start of file data
  475. try:
  476. fp.seek(file_offset)
  477. except OSError:
  478. raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
  479. raw_data = fp.read(data_size)
  480. if len(raw_data) != data_size:
  481. raise OSError("zipimport: can't read data")
  482. if compress == 0:
  483. # data is not compressed
  484. return raw_data
  485. # Decompress with zlib
  486. try:
  487. decompress = _get_decompress_func()
  488. except Exception:
  489. raise ZipImportError("can't decompress data; zlib not available")
  490. return decompress(raw_data, -15)
  491. # Lenient date/time comparison function. The precision of the mtime
  492. # in the archive is lower than the mtime stored in a .pyc: we
  493. # must allow a difference of at most one second.
  494. def _eq_mtime(t1, t2):
  495. # dostime only stores even seconds, so be lenient
  496. return abs(t1 - t2) <= 1
  497. # Given the contents of a .py[co] file, unmarshal the data
  498. # and return the code object. Raises ImportError it the magic word doesn't
  499. # match, or if the recorded .py[co] metadata does not match the source.
  500. def _unmarshal_code(self, pathname, fullpath, fullname, data):
  501. exc_details = {
  502. 'name': fullname,
  503. 'path': fullpath,
  504. }
  505. flags = _bootstrap_external._classify_pyc(data, fullname, exc_details)
  506. hash_based = flags & 0b1 != 0
  507. if hash_based:
  508. check_source = flags & 0b10 != 0
  509. if (_imp.check_hash_based_pycs != 'never' and
  510. (check_source or _imp.check_hash_based_pycs == 'always')):
  511. source_bytes = _get_pyc_source(self, fullpath)
  512. if source_bytes is not None:
  513. source_hash = _imp.source_hash(
  514. _bootstrap_external._RAW_MAGIC_NUMBER,
  515. source_bytes,
  516. )
  517. _bootstrap_external._validate_hash_pyc(
  518. data, source_hash, fullname, exc_details)
  519. else:
  520. source_mtime, source_size = \
  521. _get_mtime_and_size_of_source(self, fullpath)
  522. if source_mtime:
  523. # We don't use _bootstrap_external._validate_timestamp_pyc
  524. # to allow for a more lenient timestamp check.
  525. if (not _eq_mtime(_unpack_uint32(data[8:12]), source_mtime) or
  526. _unpack_uint32(data[12:16]) != source_size):
  527. _bootstrap._verbose_message(
  528. f'bytecode is stale for {fullname!r}')
  529. return None
  530. code = marshal.loads(data[16:])
  531. if not isinstance(code, _code_type):
  532. raise TypeError(f'compiled module {pathname!r} is not a code object')
  533. return code
  534. _code_type = type(_unmarshal_code.__code__)
  535. # Replace any occurrences of '\r\n?' in the input string with '\n'.
  536. # This converts DOS and Mac line endings to Unix line endings.
  537. def _normalize_line_endings(source):
  538. source = source.replace(b'\r\n', b'\n')
  539. source = source.replace(b'\r', b'\n')
  540. return source
  541. # Given a string buffer containing Python source code, compile it
  542. # and return a code object.
  543. def _compile_source(pathname, source):
  544. source = _normalize_line_endings(source)
  545. return compile(source, pathname, 'exec', dont_inherit=True)
  546. # Convert the date/time values found in the Zip archive to a value
  547. # that's compatible with the time stamp stored in .pyc files.
  548. def _parse_dostime(d, t):
  549. return time.mktime((
  550. (d >> 9) + 1980, # bits 9..15: year
  551. (d >> 5) & 0xF, # bits 5..8: month
  552. d & 0x1F, # bits 0..4: day
  553. t >> 11, # bits 11..15: hours
  554. (t >> 5) & 0x3F, # bits 8..10: minutes
  555. (t & 0x1F) * 2, # bits 0..7: seconds / 2
  556. -1, -1, -1))
  557. # Given a path to a .pyc file in the archive, return the
  558. # modification time of the matching .py file and its size,
  559. # or (0, 0) if no source is available.
  560. def _get_mtime_and_size_of_source(self, path):
  561. try:
  562. # strip 'c' or 'o' from *.py[co]
  563. assert path[-1:] in ('c', 'o')
  564. path = path[:-1]
  565. toc_entry = self._files[path]
  566. # fetch the time stamp of the .py file for comparison
  567. # with an embedded pyc time stamp
  568. time = toc_entry[5]
  569. date = toc_entry[6]
  570. uncompressed_size = toc_entry[3]
  571. return _parse_dostime(date, time), uncompressed_size
  572. except (KeyError, IndexError, TypeError):
  573. return 0, 0
  574. # Given a path to a .pyc file in the archive, return the
  575. # contents of the matching .py file, or None if no source
  576. # is available.
  577. def _get_pyc_source(self, path):
  578. # strip 'c' or 'o' from *.py[co]
  579. assert path[-1:] in ('c', 'o')
  580. path = path[:-1]
  581. try:
  582. toc_entry = self._files[path]
  583. except KeyError:
  584. return None
  585. else:
  586. return _get_data(self.archive, toc_entry)
  587. # Get the code object associated with the module specified by
  588. # 'fullname'.
  589. def _get_module_code(self, fullname):
  590. path = _get_module_path(self, fullname)
  591. import_error = None
  592. for suffix, isbytecode, ispackage in _zip_searchorder:
  593. fullpath = path + suffix
  594. _bootstrap._verbose_message('trying {}{}{}', self.archive, path_sep, fullpath, verbosity=2)
  595. try:
  596. toc_entry = self._files[fullpath]
  597. except KeyError:
  598. pass
  599. else:
  600. modpath = toc_entry[0]
  601. data = _get_data(self.archive, toc_entry)
  602. code = None
  603. if isbytecode:
  604. try:
  605. code = _unmarshal_code(self, modpath, fullpath, fullname, data)
  606. except ImportError as exc:
  607. import_error = exc
  608. else:
  609. code = _compile_source(modpath, data)
  610. if code is None:
  611. # bad magic number or non-matching mtime
  612. # in byte code, try next
  613. continue
  614. modpath = toc_entry[0]
  615. return code, ispackage, modpath
  616. else:
  617. if import_error:
  618. msg = f"module load failed: {import_error}"
  619. raise ZipImportError(msg, name=fullname) from import_error
  620. else:
  621. raise ZipImportError(f"can't find module {fullname!r}", name=fullname)