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

_bootstrap_external.py (64472B)


  1. """Core implementation of path-based import.
  2. This module is NOT meant to be directly imported! It has been designed such
  3. that it can be bootstrapped into Python as the implementation of import. As
  4. such it requires the injection of specific modules and attributes in order to
  5. work. One should use importlib as the public-facing version of this module.
  6. """
  7. # IMPORTANT: Whenever making changes to this module, be sure to run a top-level
  8. # `make regen-importlib` followed by `make` in order to get the frozen version
  9. # of the module updated. Not doing so will result in the Makefile to fail for
  10. # all others who don't have a ./python around to freeze the module in the early
  11. # stages of compilation.
  12. #
  13. # See importlib._setup() for what is injected into the global namespace.
  14. # When editing this code be aware that code executed at import time CANNOT
  15. # reference any injected objects! This includes not only global code but also
  16. # anything specified at the class level.
  17. # Module injected manually by _set_bootstrap_module()
  18. _bootstrap = None
  19. # Import builtin modules
  20. import _imp
  21. import _io
  22. import sys
  23. import _warnings
  24. import marshal
  25. _MS_WINDOWS = (sys.platform == 'win32')
  26. if _MS_WINDOWS:
  27. import nt as _os
  28. import winreg
  29. else:
  30. import posix as _os
  31. if _MS_WINDOWS:
  32. path_separators = ['\\', '/']
  33. else:
  34. path_separators = ['/']
  35. # Assumption made in _path_join()
  36. assert all(len(sep) == 1 for sep in path_separators)
  37. path_sep = path_separators[0]
  38. path_sep_tuple = tuple(path_separators)
  39. path_separators = ''.join(path_separators)
  40. _pathseps_with_colon = {f':{s}' for s in path_separators}
  41. # Bootstrap-related code ######################################################
  42. _CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win',
  43. _CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin'
  44. _CASE_INSENSITIVE_PLATFORMS = (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY
  45. + _CASE_INSENSITIVE_PLATFORMS_STR_KEY)
  46. def _make_relax_case():
  47. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  48. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):
  49. key = 'PYTHONCASEOK'
  50. else:
  51. key = b'PYTHONCASEOK'
  52. def _relax_case():
  53. """True if filenames must be checked case-insensitively and ignore environment flags are not set."""
  54. return not sys.flags.ignore_environment and key in _os.environ
  55. else:
  56. def _relax_case():
  57. """True if filenames must be checked case-insensitively."""
  58. return False
  59. return _relax_case
  60. _relax_case = _make_relax_case()
  61. def _pack_uint32(x):
  62. """Convert a 32-bit integer to little-endian."""
  63. return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
  64. def _unpack_uint32(data):
  65. """Convert 4 bytes in little-endian to an integer."""
  66. assert len(data) == 4
  67. return int.from_bytes(data, 'little')
  68. def _unpack_uint16(data):
  69. """Convert 2 bytes in little-endian to an integer."""
  70. assert len(data) == 2
  71. return int.from_bytes(data, 'little')
  72. if _MS_WINDOWS:
  73. def _path_join(*path_parts):
  74. """Replacement for os.path.join()."""
  75. if not path_parts:
  76. return ""
  77. if len(path_parts) == 1:
  78. return path_parts[0]
  79. root = ""
  80. path = []
  81. for new_root, tail in map(_os._path_splitroot, path_parts):
  82. if new_root.startswith(path_sep_tuple) or new_root.endswith(path_sep_tuple):
  83. root = new_root.rstrip(path_separators) or root
  84. path = [path_sep + tail]
  85. elif new_root.endswith(':'):
  86. if root.casefold() != new_root.casefold():
  87. # Drive relative paths have to be resolved by the OS, so we reset the
  88. # tail but do not add a path_sep prefix.
  89. root = new_root
  90. path = [tail]
  91. else:
  92. path.append(tail)
  93. else:
  94. root = new_root or root
  95. path.append(tail)
  96. path = [p.rstrip(path_separators) for p in path if p]
  97. if len(path) == 1 and not path[0]:
  98. # Avoid losing the root's trailing separator when joining with nothing
  99. return root + path_sep
  100. return root + path_sep.join(path)
  101. else:
  102. def _path_join(*path_parts):
  103. """Replacement for os.path.join()."""
  104. return path_sep.join([part.rstrip(path_separators)
  105. for part in path_parts if part])
  106. def _path_split(path):
  107. """Replacement for os.path.split()."""
  108. i = max(path.rfind(p) for p in path_separators)
  109. if i < 0:
  110. return '', path
  111. return path[:i], path[i + 1:]
  112. def _path_stat(path):
  113. """Stat the path.
  114. Made a separate function to make it easier to override in experiments
  115. (e.g. cache stat results).
  116. """
  117. return _os.stat(path)
  118. def _path_is_mode_type(path, mode):
  119. """Test whether the path is the specified mode type."""
  120. try:
  121. stat_info = _path_stat(path)
  122. except OSError:
  123. return False
  124. return (stat_info.st_mode & 0o170000) == mode
  125. def _path_isfile(path):
  126. """Replacement for os.path.isfile."""
  127. return _path_is_mode_type(path, 0o100000)
  128. def _path_isdir(path):
  129. """Replacement for os.path.isdir."""
  130. if not path:
  131. path = _os.getcwd()
  132. return _path_is_mode_type(path, 0o040000)
  133. if _MS_WINDOWS:
  134. def _path_isabs(path):
  135. """Replacement for os.path.isabs."""
  136. if not path:
  137. return False
  138. root = _os._path_splitroot(path)[0].replace('/', '\\')
  139. return len(root) > 1 and (root.startswith('\\\\') or root.endswith('\\'))
  140. else:
  141. def _path_isabs(path):
  142. """Replacement for os.path.isabs."""
  143. return path.startswith(path_separators)
  144. def _write_atomic(path, data, mode=0o666):
  145. """Best-effort function to write data to a path atomically.
  146. Be prepared to handle a FileExistsError if concurrent writing of the
  147. temporary file is attempted."""
  148. # id() is used to generate a pseudo-random filename.
  149. path_tmp = '{}.{}'.format(path, id(path))
  150. fd = _os.open(path_tmp,
  151. _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
  152. try:
  153. # We first write data to a temporary file, and then use os.replace() to
  154. # perform an atomic rename.
  155. with _io.FileIO(fd, 'wb') as file:
  156. file.write(data)
  157. _os.replace(path_tmp, path)
  158. except OSError:
  159. try:
  160. _os.unlink(path_tmp)
  161. except OSError:
  162. pass
  163. raise
  164. _code_type = type(_write_atomic.__code__)
  165. # Finder/loader utility code ###############################################
  166. # Magic word to reject .pyc files generated by other Python versions.
  167. # It should change for each incompatible change to the bytecode.
  168. #
  169. # The value of CR and LF is incorporated so if you ever read or write
  170. # a .pyc file in text mode the magic number will be wrong; also, the
  171. # Apple MPW compiler swaps their values, botching string constants.
  172. #
  173. # There were a variety of old schemes for setting the magic number.
  174. # The current working scheme is to increment the previous value by
  175. # 10.
  176. #
  177. # Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
  178. # number also includes a new "magic tag", i.e. a human readable string used
  179. # to represent the magic number in __pycache__ directories. When you change
  180. # the magic number, you must also set a new unique magic tag. Generally this
  181. # can be named after the Python major version of the magic number bump, but
  182. # it can really be anything, as long as it's different than anything else
  183. # that's come before. The tags are included in the following table, starting
  184. # with Python 3.2a0.
  185. #
  186. # Known values:
  187. # Python 1.5: 20121
  188. # Python 1.5.1: 20121
  189. # Python 1.5.2: 20121
  190. # Python 1.6: 50428
  191. # Python 2.0: 50823
  192. # Python 2.0.1: 50823
  193. # Python 2.1: 60202
  194. # Python 2.1.1: 60202
  195. # Python 2.1.2: 60202
  196. # Python 2.2: 60717
  197. # Python 2.3a0: 62011
  198. # Python 2.3a0: 62021
  199. # Python 2.3a0: 62011 (!)
  200. # Python 2.4a0: 62041
  201. # Python 2.4a3: 62051
  202. # Python 2.4b1: 62061
  203. # Python 2.5a0: 62071
  204. # Python 2.5a0: 62081 (ast-branch)
  205. # Python 2.5a0: 62091 (with)
  206. # Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
  207. # Python 2.5b3: 62101 (fix wrong code: for x, in ...)
  208. # Python 2.5b3: 62111 (fix wrong code: x += yield)
  209. # Python 2.5c1: 62121 (fix wrong lnotab with for loops and
  210. # storing constants that should have been removed)
  211. # Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
  212. # Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
  213. # Python 2.6a1: 62161 (WITH_CLEANUP optimization)
  214. # Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
  215. # Python 2.7a0: 62181 (optimize conditional branches:
  216. # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
  217. # Python 2.7a0 62191 (introduce SETUP_WITH)
  218. # Python 2.7a0 62201 (introduce BUILD_SET)
  219. # Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
  220. # Python 3000: 3000
  221. # 3010 (removed UNARY_CONVERT)
  222. # 3020 (added BUILD_SET)
  223. # 3030 (added keyword-only parameters)
  224. # 3040 (added signature annotations)
  225. # 3050 (print becomes a function)
  226. # 3060 (PEP 3115 metaclass syntax)
  227. # 3061 (string literals become unicode)
  228. # 3071 (PEP 3109 raise changes)
  229. # 3081 (PEP 3137 make __file__ and __name__ unicode)
  230. # 3091 (kill str8 interning)
  231. # 3101 (merge from 2.6a0, see 62151)
  232. # 3103 (__file__ points to source file)
  233. # Python 3.0a4: 3111 (WITH_CLEANUP optimization).
  234. # Python 3.0b1: 3131 (lexical exception stacking, including POP_EXCEPT
  235. #3021)
  236. # Python 3.1a1: 3141 (optimize list, set and dict comprehensions:
  237. # change LIST_APPEND and SET_ADD, add MAP_ADD #2183)
  238. # Python 3.1a1: 3151 (optimize conditional branches:
  239. # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
  240. #4715)
  241. # Python 3.2a1: 3160 (add SETUP_WITH #6101)
  242. # tag: cpython-32
  243. # Python 3.2a2: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR #9225)
  244. # tag: cpython-32
  245. # Python 3.2a3 3180 (add DELETE_DEREF #4617)
  246. # Python 3.3a1 3190 (__class__ super closure changed)
  247. # Python 3.3a1 3200 (PEP 3155 __qualname__ added #13448)
  248. # Python 3.3a1 3210 (added size modulo 2**32 to the pyc header #13645)
  249. # Python 3.3a2 3220 (changed PEP 380 implementation #14230)
  250. # Python 3.3a4 3230 (revert changes to implicit __class__ closure #14857)
  251. # Python 3.4a1 3250 (evaluate positional default arguments before
  252. # keyword-only defaults #16967)
  253. # Python 3.4a1 3260 (add LOAD_CLASSDEREF; allow locals of class to override
  254. # free vars #17853)
  255. # Python 3.4a1 3270 (various tweaks to the __class__ closure #12370)
  256. # Python 3.4a1 3280 (remove implicit class argument)
  257. # Python 3.4a4 3290 (changes to __qualname__ computation #19301)
  258. # Python 3.4a4 3300 (more changes to __qualname__ computation #19301)
  259. # Python 3.4rc2 3310 (alter __qualname__ computation #20625)
  260. # Python 3.5a1 3320 (PEP 465: Matrix multiplication operator #21176)
  261. # Python 3.5b1 3330 (PEP 448: Additional Unpacking Generalizations #2292)
  262. # Python 3.5b2 3340 (fix dictionary display evaluation order #11205)
  263. # Python 3.5b3 3350 (add GET_YIELD_FROM_ITER opcode #24400)
  264. # Python 3.5.2 3351 (fix BUILD_MAP_UNPACK_WITH_CALL opcode #27286)
  265. # Python 3.6a0 3360 (add FORMAT_VALUE opcode #25483)
  266. # Python 3.6a1 3361 (lineno delta of code.co_lnotab becomes signed #26107)
  267. # Python 3.6a2 3370 (16 bit wordcode #26647)
  268. # Python 3.6a2 3371 (add BUILD_CONST_KEY_MAP opcode #27140)
  269. # Python 3.6a2 3372 (MAKE_FUNCTION simplification, remove MAKE_CLOSURE
  270. # #27095)
  271. # Python 3.6b1 3373 (add BUILD_STRING opcode #27078)
  272. # Python 3.6b1 3375 (add SETUP_ANNOTATIONS and STORE_ANNOTATION opcodes
  273. # #27985)
  274. # Python 3.6b1 3376 (simplify CALL_FUNCTIONs & BUILD_MAP_UNPACK_WITH_CALL
  275. #27213)
  276. # Python 3.6b1 3377 (set __class__ cell from type.__new__ #23722)
  277. # Python 3.6b2 3378 (add BUILD_TUPLE_UNPACK_WITH_CALL #28257)
  278. # Python 3.6rc1 3379 (more thorough __class__ validation #23722)
  279. # Python 3.7a1 3390 (add LOAD_METHOD and CALL_METHOD opcodes #26110)
  280. # Python 3.7a2 3391 (update GET_AITER #31709)
  281. # Python 3.7a4 3392 (PEP 552: Deterministic pycs #31650)
  282. # Python 3.7b1 3393 (remove STORE_ANNOTATION opcode #32550)
  283. # Python 3.7b5 3394 (restored docstring as the first stmt in the body;
  284. # this might affected the first line number #32911)
  285. # Python 3.8a1 3400 (move frame block handling to compiler #17611)
  286. # Python 3.8a1 3401 (add END_ASYNC_FOR #33041)
  287. # Python 3.8a1 3410 (PEP570 Python Positional-Only Parameters #36540)
  288. # Python 3.8b2 3411 (Reverse evaluation order of key: value in dict
  289. # comprehensions #35224)
  290. # Python 3.8b2 3412 (Swap the position of positional args and positional
  291. # only args in ast.arguments #37593)
  292. # Python 3.8b4 3413 (Fix "break" and "continue" in "finally" #37830)
  293. # Python 3.9a0 3420 (add LOAD_ASSERTION_ERROR #34880)
  294. # Python 3.9a0 3421 (simplified bytecode for with blocks #32949)
  295. # Python 3.9a0 3422 (remove BEGIN_FINALLY, END_FINALLY, CALL_FINALLY, POP_FINALLY bytecodes #33387)
  296. # Python 3.9a2 3423 (add IS_OP, CONTAINS_OP and JUMP_IF_NOT_EXC_MATCH bytecodes #39156)
  297. # Python 3.9a2 3424 (simplify bytecodes for *value unpacking)
  298. # Python 3.9a2 3425 (simplify bytecodes for **value unpacking)
  299. # Python 3.10a1 3430 (Make 'annotations' future by default)
  300. # Python 3.10a1 3431 (New line number table format -- PEP 626)
  301. # Python 3.10a2 3432 (Function annotation for MAKE_FUNCTION is changed from dict to tuple bpo-42202)
  302. # Python 3.10a2 3433 (RERAISE restores f_lasti if oparg != 0)
  303. # Python 3.10a6 3434 (PEP 634: Structural Pattern Matching)
  304. # Python 3.10a7 3435 Use instruction offsets (as opposed to byte offsets).
  305. # Python 3.10b1 3436 (Add GEN_START bytecode #43683)
  306. # Python 3.10b1 3437 (Undo making 'annotations' future by default - We like to dance among core devs!)
  307. # Python 3.10b1 3438 Safer line number table handling.
  308. # Python 3.10b1 3439 (Add ROT_N)
  309. #
  310. # MAGIC must change whenever the bytecode emitted by the compiler may no
  311. # longer be understood by older implementations of the eval loop (usually
  312. # due to the addition of new opcodes).
  313. #
  314. # Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array
  315. # in PC/launcher.c must also be updated.
  316. MAGIC_NUMBER = (3439).to_bytes(2, 'little') + b'\r\n'
  317. _RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c
  318. _PYCACHE = '__pycache__'
  319. _OPT = 'opt-'
  320. SOURCE_SUFFIXES = ['.py']
  321. if _MS_WINDOWS:
  322. SOURCE_SUFFIXES.append('.pyw')
  323. EXTENSION_SUFFIXES = _imp.extension_suffixes()
  324. BYTECODE_SUFFIXES = ['.pyc']
  325. # Deprecated.
  326. DEBUG_BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES = BYTECODE_SUFFIXES
  327. def cache_from_source(path, debug_override=None, *, optimization=None):
  328. """Given the path to a .py file, return the path to its .pyc file.
  329. The .py file does not need to exist; this simply returns the path to the
  330. .pyc file calculated as if the .py file were imported.
  331. The 'optimization' parameter controls the presumed optimization level of
  332. the bytecode file. If 'optimization' is not None, the string representation
  333. of the argument is taken and verified to be alphanumeric (else ValueError
  334. is raised).
  335. The debug_override parameter is deprecated. If debug_override is not None,
  336. a True value is the same as setting 'optimization' to the empty string
  337. while a False value is equivalent to setting 'optimization' to '1'.
  338. If sys.implementation.cache_tag is None then NotImplementedError is raised.
  339. """
  340. if debug_override is not None:
  341. _warnings.warn('the debug_override parameter is deprecated; use '
  342. "'optimization' instead", DeprecationWarning)
  343. if optimization is not None:
  344. message = 'debug_override or optimization must be set to None'
  345. raise TypeError(message)
  346. optimization = '' if debug_override else 1
  347. path = _os.fspath(path)
  348. head, tail = _path_split(path)
  349. base, sep, rest = tail.rpartition('.')
  350. tag = sys.implementation.cache_tag
  351. if tag is None:
  352. raise NotImplementedError('sys.implementation.cache_tag is None')
  353. almost_filename = ''.join([(base if base else rest), sep, tag])
  354. if optimization is None:
  355. if sys.flags.optimize == 0:
  356. optimization = ''
  357. else:
  358. optimization = sys.flags.optimize
  359. optimization = str(optimization)
  360. if optimization != '':
  361. if not optimization.isalnum():
  362. raise ValueError('{!r} is not alphanumeric'.format(optimization))
  363. almost_filename = '{}.{}{}'.format(almost_filename, _OPT, optimization)
  364. filename = almost_filename + BYTECODE_SUFFIXES[0]
  365. if sys.pycache_prefix is not None:
  366. # We need an absolute path to the py file to avoid the possibility of
  367. # collisions within sys.pycache_prefix, if someone has two different
  368. # `foo/bar.py` on their system and they import both of them using the
  369. # same sys.pycache_prefix. Let's say sys.pycache_prefix is
  370. # `C:\Bytecode`; the idea here is that if we get `Foo\Bar`, we first
  371. # make it absolute (`C:\Somewhere\Foo\Bar`), then make it root-relative
  372. # (`Somewhere\Foo\Bar`), so we end up placing the bytecode file in an
  373. # unambiguous `C:\Bytecode\Somewhere\Foo\Bar\`.
  374. if not _path_isabs(head):
  375. head = _path_join(_os.getcwd(), head)
  376. # Strip initial drive from a Windows path. We know we have an absolute
  377. # path here, so the second part of the check rules out a POSIX path that
  378. # happens to contain a colon at the second character.
  379. if head[1] == ':' and head[0] not in path_separators:
  380. head = head[2:]
  381. # Strip initial path separator from `head` to complete the conversion
  382. # back to a root-relative path before joining.
  383. return _path_join(
  384. sys.pycache_prefix,
  385. head.lstrip(path_separators),
  386. filename,
  387. )
  388. return _path_join(head, _PYCACHE, filename)
  389. def source_from_cache(path):
  390. """Given the path to a .pyc. file, return the path to its .py file.
  391. The .pyc file does not need to exist; this simply returns the path to
  392. the .py file calculated to correspond to the .pyc file. If path does
  393. not conform to PEP 3147/488 format, ValueError will be raised. If
  394. sys.implementation.cache_tag is None then NotImplementedError is raised.
  395. """
  396. if sys.implementation.cache_tag is None:
  397. raise NotImplementedError('sys.implementation.cache_tag is None')
  398. path = _os.fspath(path)
  399. head, pycache_filename = _path_split(path)
  400. found_in_pycache_prefix = False
  401. if sys.pycache_prefix is not None:
  402. stripped_path = sys.pycache_prefix.rstrip(path_separators)
  403. if head.startswith(stripped_path + path_sep):
  404. head = head[len(stripped_path):]
  405. found_in_pycache_prefix = True
  406. if not found_in_pycache_prefix:
  407. head, pycache = _path_split(head)
  408. if pycache != _PYCACHE:
  409. raise ValueError(f'{_PYCACHE} not bottom-level directory in '
  410. f'{path!r}')
  411. dot_count = pycache_filename.count('.')
  412. if dot_count not in {2, 3}:
  413. raise ValueError(f'expected only 2 or 3 dots in {pycache_filename!r}')
  414. elif dot_count == 3:
  415. optimization = pycache_filename.rsplit('.', 2)[-2]
  416. if not optimization.startswith(_OPT):
  417. raise ValueError("optimization portion of filename does not start "
  418. f"with {_OPT!r}")
  419. opt_level = optimization[len(_OPT):]
  420. if not opt_level.isalnum():
  421. raise ValueError(f"optimization level {optimization!r} is not an "
  422. "alphanumeric value")
  423. base_filename = pycache_filename.partition('.')[0]
  424. return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
  425. def _get_sourcefile(bytecode_path):
  426. """Convert a bytecode file path to a source path (if possible).
  427. This function exists purely for backwards-compatibility for
  428. PyImport_ExecCodeModuleWithFilenames() in the C API.
  429. """
  430. if len(bytecode_path) == 0:
  431. return None
  432. rest, _, extension = bytecode_path.rpartition('.')
  433. if not rest or extension.lower()[-3:-1] != 'py':
  434. return bytecode_path
  435. try:
  436. source_path = source_from_cache(bytecode_path)
  437. except (NotImplementedError, ValueError):
  438. source_path = bytecode_path[:-1]
  439. return source_path if _path_isfile(source_path) else bytecode_path
  440. def _get_cached(filename):
  441. if filename.endswith(tuple(SOURCE_SUFFIXES)):
  442. try:
  443. return cache_from_source(filename)
  444. except NotImplementedError:
  445. pass
  446. elif filename.endswith(tuple(BYTECODE_SUFFIXES)):
  447. return filename
  448. else:
  449. return None
  450. def _calc_mode(path):
  451. """Calculate the mode permissions for a bytecode file."""
  452. try:
  453. mode = _path_stat(path).st_mode
  454. except OSError:
  455. mode = 0o666
  456. # We always ensure write access so we can update cached files
  457. # later even when the source files are read-only on Windows (#6074)
  458. mode |= 0o200
  459. return mode
  460. def _check_name(method):
  461. """Decorator to verify that the module being requested matches the one the
  462. loader can handle.
  463. The first argument (self) must define _name which the second argument is
  464. compared against. If the comparison fails then ImportError is raised.
  465. """
  466. def _check_name_wrapper(self, name=None, *args, **kwargs):
  467. if name is None:
  468. name = self.name
  469. elif self.name != name:
  470. raise ImportError('loader for %s cannot handle %s' %
  471. (self.name, name), name=name)
  472. return method(self, name, *args, **kwargs)
  473. # FIXME: @_check_name is used to define class methods before the
  474. # _bootstrap module is set by _set_bootstrap_module().
  475. if _bootstrap is not None:
  476. _wrap = _bootstrap._wrap
  477. else:
  478. def _wrap(new, old):
  479. for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
  480. if hasattr(old, replace):
  481. setattr(new, replace, getattr(old, replace))
  482. new.__dict__.update(old.__dict__)
  483. _wrap(_check_name_wrapper, method)
  484. return _check_name_wrapper
  485. def _find_module_shim(self, fullname):
  486. """Try to find a loader for the specified module by delegating to
  487. self.find_loader().
  488. This method is deprecated in favor of finder.find_spec().
  489. """
  490. _warnings.warn("find_module() is deprecated and "
  491. "slated for removal in Python 3.12; use find_spec() instead",
  492. DeprecationWarning)
  493. # Call find_loader(). If it returns a string (indicating this
  494. # is a namespace package portion), generate a warning and
  495. # return None.
  496. loader, portions = self.find_loader(fullname)
  497. if loader is None and len(portions):
  498. msg = 'Not importing directory {}: missing __init__'
  499. _warnings.warn(msg.format(portions[0]), ImportWarning)
  500. return loader
  501. def _classify_pyc(data, name, exc_details):
  502. """Perform basic validity checking of a pyc header and return the flags field,
  503. which determines how the pyc should be further validated against the source.
  504. *data* is the contents of the pyc file. (Only the first 16 bytes are
  505. required, though.)
  506. *name* is the name of the module being imported. It is used for logging.
  507. *exc_details* is a dictionary passed to ImportError if it raised for
  508. improved debugging.
  509. ImportError is raised when the magic number is incorrect or when the flags
  510. field is invalid. EOFError is raised when the data is found to be truncated.
  511. """
  512. magic = data[:4]
  513. if magic != MAGIC_NUMBER:
  514. message = f'bad magic number in {name!r}: {magic!r}'
  515. _bootstrap._verbose_message('{}', message)
  516. raise ImportError(message, **exc_details)
  517. if len(data) < 16:
  518. message = f'reached EOF while reading pyc header of {name!r}'
  519. _bootstrap._verbose_message('{}', message)
  520. raise EOFError(message)
  521. flags = _unpack_uint32(data[4:8])
  522. # Only the first two flags are defined.
  523. if flags & ~0b11:
  524. message = f'invalid flags {flags!r} in {name!r}'
  525. raise ImportError(message, **exc_details)
  526. return flags
  527. def _validate_timestamp_pyc(data, source_mtime, source_size, name,
  528. exc_details):
  529. """Validate a pyc against the source last-modified time.
  530. *data* is the contents of the pyc file. (Only the first 16 bytes are
  531. required.)
  532. *source_mtime* is the last modified timestamp of the source file.
  533. *source_size* is None or the size of the source file in bytes.
  534. *name* is the name of the module being imported. It is used for logging.
  535. *exc_details* is a dictionary passed to ImportError if it raised for
  536. improved debugging.
  537. An ImportError is raised if the bytecode is stale.
  538. """
  539. if _unpack_uint32(data[8:12]) != (source_mtime & 0xFFFFFFFF):
  540. message = f'bytecode is stale for {name!r}'
  541. _bootstrap._verbose_message('{}', message)
  542. raise ImportError(message, **exc_details)
  543. if (source_size is not None and
  544. _unpack_uint32(data[12:16]) != (source_size & 0xFFFFFFFF)):
  545. raise ImportError(f'bytecode is stale for {name!r}', **exc_details)
  546. def _validate_hash_pyc(data, source_hash, name, exc_details):
  547. """Validate a hash-based pyc by checking the real source hash against the one in
  548. the pyc header.
  549. *data* is the contents of the pyc file. (Only the first 16 bytes are
  550. required.)
  551. *source_hash* is the importlib.util.source_hash() of the source file.
  552. *name* is the name of the module being imported. It is used for logging.
  553. *exc_details* is a dictionary passed to ImportError if it raised for
  554. improved debugging.
  555. An ImportError is raised if the bytecode is stale.
  556. """
  557. if data[8:16] != source_hash:
  558. raise ImportError(
  559. f'hash in bytecode doesn\'t match hash of source {name!r}',
  560. **exc_details,
  561. )
  562. def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
  563. """Compile bytecode as found in a pyc."""
  564. code = marshal.loads(data)
  565. if isinstance(code, _code_type):
  566. _bootstrap._verbose_message('code object from {!r}', bytecode_path)
  567. if source_path is not None:
  568. _imp._fix_co_filename(code, source_path)
  569. return code
  570. else:
  571. raise ImportError('Non-code object in {!r}'.format(bytecode_path),
  572. name=name, path=bytecode_path)
  573. def _code_to_timestamp_pyc(code, mtime=0, source_size=0):
  574. "Produce the data for a timestamp-based pyc."
  575. data = bytearray(MAGIC_NUMBER)
  576. data.extend(_pack_uint32(0))
  577. data.extend(_pack_uint32(mtime))
  578. data.extend(_pack_uint32(source_size))
  579. data.extend(marshal.dumps(code))
  580. return data
  581. def _code_to_hash_pyc(code, source_hash, checked=True):
  582. "Produce the data for a hash-based pyc."
  583. data = bytearray(MAGIC_NUMBER)
  584. flags = 0b1 | checked << 1
  585. data.extend(_pack_uint32(flags))
  586. assert len(source_hash) == 8
  587. data.extend(source_hash)
  588. data.extend(marshal.dumps(code))
  589. return data
  590. def decode_source(source_bytes):
  591. """Decode bytes representing source code and return the string.
  592. Universal newline support is used in the decoding.
  593. """
  594. import tokenize # To avoid bootstrap issues.
  595. source_bytes_readline = _io.BytesIO(source_bytes).readline
  596. encoding = tokenize.detect_encoding(source_bytes_readline)
  597. newline_decoder = _io.IncrementalNewlineDecoder(None, True)
  598. return newline_decoder.decode(source_bytes.decode(encoding[0]))
  599. # Module specifications #######################################################
  600. _POPULATE = object()
  601. def spec_from_file_location(name, location=None, *, loader=None,
  602. submodule_search_locations=_POPULATE):
  603. """Return a module spec based on a file location.
  604. To indicate that the module is a package, set
  605. submodule_search_locations to a list of directory paths. An
  606. empty list is sufficient, though its not otherwise useful to the
  607. import system.
  608. The loader must take a spec as its only __init__() arg.
  609. """
  610. if location is None:
  611. # The caller may simply want a partially populated location-
  612. # oriented spec. So we set the location to a bogus value and
  613. # fill in as much as we can.
  614. location = '<unknown>'
  615. if hasattr(loader, 'get_filename'):
  616. # ExecutionLoader
  617. try:
  618. location = loader.get_filename(name)
  619. except ImportError:
  620. pass
  621. else:
  622. location = _os.fspath(location)
  623. if not _path_isabs(location):
  624. try:
  625. location = _path_join(_os.getcwd(), location)
  626. except OSError:
  627. pass
  628. # If the location is on the filesystem, but doesn't actually exist,
  629. # we could return None here, indicating that the location is not
  630. # valid. However, we don't have a good way of testing since an
  631. # indirect location (e.g. a zip file or URL) will look like a
  632. # non-existent file relative to the filesystem.
  633. spec = _bootstrap.ModuleSpec(name, loader, origin=location)
  634. spec._set_fileattr = True
  635. # Pick a loader if one wasn't provided.
  636. if loader is None:
  637. for loader_class, suffixes in _get_supported_file_loaders():
  638. if location.endswith(tuple(suffixes)):
  639. loader = loader_class(name, location)
  640. spec.loader = loader
  641. break
  642. else:
  643. return None
  644. # Set submodule_search_paths appropriately.
  645. if submodule_search_locations is _POPULATE:
  646. # Check the loader.
  647. if hasattr(loader, 'is_package'):
  648. try:
  649. is_package = loader.is_package(name)
  650. except ImportError:
  651. pass
  652. else:
  653. if is_package:
  654. spec.submodule_search_locations = []
  655. else:
  656. spec.submodule_search_locations = submodule_search_locations
  657. if spec.submodule_search_locations == []:
  658. if location:
  659. dirname = _path_split(location)[0]
  660. spec.submodule_search_locations.append(dirname)
  661. return spec
  662. # Loaders #####################################################################
  663. class WindowsRegistryFinder:
  664. """Meta path finder for modules declared in the Windows registry."""
  665. REGISTRY_KEY = (
  666. 'Software\\Python\\PythonCore\\{sys_version}'
  667. '\\Modules\\{fullname}')
  668. REGISTRY_KEY_DEBUG = (
  669. 'Software\\Python\\PythonCore\\{sys_version}'
  670. '\\Modules\\{fullname}\\Debug')
  671. DEBUG_BUILD = (_MS_WINDOWS and '_d.pyd' in EXTENSION_SUFFIXES)
  672. @staticmethod
  673. def _open_registry(key):
  674. try:
  675. return winreg.OpenKey(winreg.HKEY_CURRENT_USER, key)
  676. except OSError:
  677. return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key)
  678. @classmethod
  679. def _search_registry(cls, fullname):
  680. if cls.DEBUG_BUILD:
  681. registry_key = cls.REGISTRY_KEY_DEBUG
  682. else:
  683. registry_key = cls.REGISTRY_KEY
  684. key = registry_key.format(fullname=fullname,
  685. sys_version='%d.%d' % sys.version_info[:2])
  686. try:
  687. with cls._open_registry(key) as hkey:
  688. filepath = winreg.QueryValue(hkey, '')
  689. except OSError:
  690. return None
  691. return filepath
  692. @classmethod
  693. def find_spec(cls, fullname, path=None, target=None):
  694. filepath = cls._search_registry(fullname)
  695. if filepath is None:
  696. return None
  697. try:
  698. _path_stat(filepath)
  699. except OSError:
  700. return None
  701. for loader, suffixes in _get_supported_file_loaders():
  702. if filepath.endswith(tuple(suffixes)):
  703. spec = _bootstrap.spec_from_loader(fullname,
  704. loader(fullname, filepath),
  705. origin=filepath)
  706. return spec
  707. @classmethod
  708. def find_module(cls, fullname, path=None):
  709. """Find module named in the registry.
  710. This method is deprecated. Use find_spec() instead.
  711. """
  712. _warnings.warn("WindowsRegistryFinder.find_module() is deprecated and "
  713. "slated for removal in Python 3.12; use find_spec() instead",
  714. DeprecationWarning)
  715. spec = cls.find_spec(fullname, path)
  716. if spec is not None:
  717. return spec.loader
  718. else:
  719. return None
  720. class _LoaderBasics:
  721. """Base class of common code needed by both SourceLoader and
  722. SourcelessFileLoader."""
  723. def is_package(self, fullname):
  724. """Concrete implementation of InspectLoader.is_package by checking if
  725. the path returned by get_filename has a filename of '__init__.py'."""
  726. filename = _path_split(self.get_filename(fullname))[1]
  727. filename_base = filename.rsplit('.', 1)[0]
  728. tail_name = fullname.rpartition('.')[2]
  729. return filename_base == '__init__' and tail_name != '__init__'
  730. def create_module(self, spec):
  731. """Use default semantics for module creation."""
  732. def exec_module(self, module):
  733. """Execute the module."""
  734. code = self.get_code(module.__name__)
  735. if code is None:
  736. raise ImportError('cannot load module {!r} when get_code() '
  737. 'returns None'.format(module.__name__))
  738. _bootstrap._call_with_frames_removed(exec, code, module.__dict__)
  739. def load_module(self, fullname):
  740. """This method is deprecated."""
  741. # Warning implemented in _load_module_shim().
  742. return _bootstrap._load_module_shim(self, fullname)
  743. class SourceLoader(_LoaderBasics):
  744. def path_mtime(self, path):
  745. """Optional method that returns the modification time (an int) for the
  746. specified path (a str).
  747. Raises OSError when the path cannot be handled.
  748. """
  749. raise OSError
  750. def path_stats(self, path):
  751. """Optional method returning a metadata dict for the specified
  752. path (a str).
  753. Possible keys:
  754. - 'mtime' (mandatory) is the numeric timestamp of last source
  755. code modification;
  756. - 'size' (optional) is the size in bytes of the source code.
  757. Implementing this method allows the loader to read bytecode files.
  758. Raises OSError when the path cannot be handled.
  759. """
  760. return {'mtime': self.path_mtime(path)}
  761. def _cache_bytecode(self, source_path, cache_path, data):
  762. """Optional method which writes data (bytes) to a file path (a str).
  763. Implementing this method allows for the writing of bytecode files.
  764. The source path is needed in order to correctly transfer permissions
  765. """
  766. # For backwards compatibility, we delegate to set_data()
  767. return self.set_data(cache_path, data)
  768. def set_data(self, path, data):
  769. """Optional method which writes data (bytes) to a file path (a str).
  770. Implementing this method allows for the writing of bytecode files.
  771. """
  772. def get_source(self, fullname):
  773. """Concrete implementation of InspectLoader.get_source."""
  774. path = self.get_filename(fullname)
  775. try:
  776. source_bytes = self.get_data(path)
  777. except OSError as exc:
  778. raise ImportError('source not available through get_data()',
  779. name=fullname) from exc
  780. return decode_source(source_bytes)
  781. def source_to_code(self, data, path, *, _optimize=-1):
  782. """Return the code object compiled from source.
  783. The 'data' argument can be any object type that compile() supports.
  784. """
  785. return _bootstrap._call_with_frames_removed(compile, data, path, 'exec',
  786. dont_inherit=True, optimize=_optimize)
  787. def get_code(self, fullname):
  788. """Concrete implementation of InspectLoader.get_code.
  789. Reading of bytecode requires path_stats to be implemented. To write
  790. bytecode, set_data must also be implemented.
  791. """
  792. source_path = self.get_filename(fullname)
  793. source_mtime = None
  794. source_bytes = None
  795. source_hash = None
  796. hash_based = False
  797. check_source = True
  798. try:
  799. bytecode_path = cache_from_source(source_path)
  800. except NotImplementedError:
  801. bytecode_path = None
  802. else:
  803. try:
  804. st = self.path_stats(source_path)
  805. except OSError:
  806. pass
  807. else:
  808. source_mtime = int(st['mtime'])
  809. try:
  810. data = self.get_data(bytecode_path)
  811. except OSError:
  812. pass
  813. else:
  814. exc_details = {
  815. 'name': fullname,
  816. 'path': bytecode_path,
  817. }
  818. try:
  819. flags = _classify_pyc(data, fullname, exc_details)
  820. bytes_data = memoryview(data)[16:]
  821. hash_based = flags & 0b1 != 0
  822. if hash_based:
  823. check_source = flags & 0b10 != 0
  824. if (_imp.check_hash_based_pycs != 'never' and
  825. (check_source or
  826. _imp.check_hash_based_pycs == 'always')):
  827. source_bytes = self.get_data(source_path)
  828. source_hash = _imp.source_hash(
  829. _RAW_MAGIC_NUMBER,
  830. source_bytes,
  831. )
  832. _validate_hash_pyc(data, source_hash, fullname,
  833. exc_details)
  834. else:
  835. _validate_timestamp_pyc(
  836. data,
  837. source_mtime,
  838. st['size'],
  839. fullname,
  840. exc_details,
  841. )
  842. except (ImportError, EOFError):
  843. pass
  844. else:
  845. _bootstrap._verbose_message('{} matches {}', bytecode_path,
  846. source_path)
  847. return _compile_bytecode(bytes_data, name=fullname,
  848. bytecode_path=bytecode_path,
  849. source_path=source_path)
  850. if source_bytes is None:
  851. source_bytes = self.get_data(source_path)
  852. code_object = self.source_to_code(source_bytes, source_path)
  853. _bootstrap._verbose_message('code object from {}', source_path)
  854. if (not sys.dont_write_bytecode and bytecode_path is not None and
  855. source_mtime is not None):
  856. if hash_based:
  857. if source_hash is None:
  858. source_hash = _imp.source_hash(source_bytes)
  859. data = _code_to_hash_pyc(code_object, source_hash, check_source)
  860. else:
  861. data = _code_to_timestamp_pyc(code_object, source_mtime,
  862. len(source_bytes))
  863. try:
  864. self._cache_bytecode(source_path, bytecode_path, data)
  865. except NotImplementedError:
  866. pass
  867. return code_object
  868. class FileLoader:
  869. """Base file loader class which implements the loader protocol methods that
  870. require file system usage."""
  871. def __init__(self, fullname, path):
  872. """Cache the module name and the path to the file found by the
  873. finder."""
  874. self.name = fullname
  875. self.path = path
  876. def __eq__(self, other):
  877. return (self.__class__ == other.__class__ and
  878. self.__dict__ == other.__dict__)
  879. def __hash__(self):
  880. return hash(self.name) ^ hash(self.path)
  881. @_check_name
  882. def load_module(self, fullname):
  883. """Load a module from a file.
  884. This method is deprecated. Use exec_module() instead.
  885. """
  886. # The only reason for this method is for the name check.
  887. # Issue #14857: Avoid the zero-argument form of super so the implementation
  888. # of that form can be updated without breaking the frozen module.
  889. return super(FileLoader, self).load_module(fullname)
  890. @_check_name
  891. def get_filename(self, fullname):
  892. """Return the path to the source file as found by the finder."""
  893. return self.path
  894. def get_data(self, path):
  895. """Return the data from path as raw bytes."""
  896. if isinstance(self, (SourceLoader, ExtensionFileLoader)):
  897. with _io.open_code(str(path)) as file:
  898. return file.read()
  899. else:
  900. with _io.FileIO(path, 'r') as file:
  901. return file.read()
  902. @_check_name
  903. def get_resource_reader(self, module):
  904. from importlib.readers import FileReader
  905. return FileReader(self)
  906. class SourceFileLoader(FileLoader, SourceLoader):
  907. """Concrete implementation of SourceLoader using the file system."""
  908. def path_stats(self, path):
  909. """Return the metadata for the path."""
  910. st = _path_stat(path)
  911. return {'mtime': st.st_mtime, 'size': st.st_size}
  912. def _cache_bytecode(self, source_path, bytecode_path, data):
  913. # Adapt between the two APIs
  914. mode = _calc_mode(source_path)
  915. return self.set_data(bytecode_path, data, _mode=mode)
  916. def set_data(self, path, data, *, _mode=0o666):
  917. """Write bytes data to a file."""
  918. parent, filename = _path_split(path)
  919. path_parts = []
  920. # Figure out what directories are missing.
  921. while parent and not _path_isdir(parent):
  922. parent, part = _path_split(parent)
  923. path_parts.append(part)
  924. # Create needed directories.
  925. for part in reversed(path_parts):
  926. parent = _path_join(parent, part)
  927. try:
  928. _os.mkdir(parent)
  929. except FileExistsError:
  930. # Probably another Python process already created the dir.
  931. continue
  932. except OSError as exc:
  933. # Could be a permission error, read-only filesystem: just forget
  934. # about writing the data.
  935. _bootstrap._verbose_message('could not create {!r}: {!r}',
  936. parent, exc)
  937. return
  938. try:
  939. _write_atomic(path, data, _mode)
  940. _bootstrap._verbose_message('created {!r}', path)
  941. except OSError as exc:
  942. # Same as above: just don't write the bytecode.
  943. _bootstrap._verbose_message('could not create {!r}: {!r}', path,
  944. exc)
  945. class SourcelessFileLoader(FileLoader, _LoaderBasics):
  946. """Loader which handles sourceless file imports."""
  947. def get_code(self, fullname):
  948. path = self.get_filename(fullname)
  949. data = self.get_data(path)
  950. # Call _classify_pyc to do basic validation of the pyc but ignore the
  951. # result. There's no source to check against.
  952. exc_details = {
  953. 'name': fullname,
  954. 'path': path,
  955. }
  956. _classify_pyc(data, fullname, exc_details)
  957. return _compile_bytecode(
  958. memoryview(data)[16:],
  959. name=fullname,
  960. bytecode_path=path,
  961. )
  962. def get_source(self, fullname):
  963. """Return None as there is no source code."""
  964. return None
  965. class ExtensionFileLoader(FileLoader, _LoaderBasics):
  966. """Loader for extension modules.
  967. The constructor is designed to work with FileFinder.
  968. """
  969. def __init__(self, name, path):
  970. self.name = name
  971. self.path = path
  972. def __eq__(self, other):
  973. return (self.__class__ == other.__class__ and
  974. self.__dict__ == other.__dict__)
  975. def __hash__(self):
  976. return hash(self.name) ^ hash(self.path)
  977. def create_module(self, spec):
  978. """Create an unitialized extension module"""
  979. module = _bootstrap._call_with_frames_removed(
  980. _imp.create_dynamic, spec)
  981. _bootstrap._verbose_message('extension module {!r} loaded from {!r}',
  982. spec.name, self.path)
  983. return module
  984. def exec_module(self, module):
  985. """Initialize an extension module"""
  986. _bootstrap._call_with_frames_removed(_imp.exec_dynamic, module)
  987. _bootstrap._verbose_message('extension module {!r} executed from {!r}',
  988. self.name, self.path)
  989. def is_package(self, fullname):
  990. """Return True if the extension module is a package."""
  991. file_name = _path_split(self.path)[1]
  992. return any(file_name == '__init__' + suffix
  993. for suffix in EXTENSION_SUFFIXES)
  994. def get_code(self, fullname):
  995. """Return None as an extension module cannot create a code object."""
  996. return None
  997. def get_source(self, fullname):
  998. """Return None as extension modules have no source code."""
  999. return None
  1000. @_check_name
  1001. def get_filename(self, fullname):
  1002. """Return the path to the source file as found by the finder."""
  1003. return self.path
  1004. class _NamespacePath:
  1005. """Represents a namespace package's path. It uses the module name
  1006. to find its parent module, and from there it looks up the parent's
  1007. __path__. When this changes, the module's own path is recomputed,
  1008. using path_finder. For top-level modules, the parent module's path
  1009. is sys.path."""
  1010. def __init__(self, name, path, path_finder):
  1011. self._name = name
  1012. self._path = path
  1013. self._last_parent_path = tuple(self._get_parent_path())
  1014. self._path_finder = path_finder
  1015. def _find_parent_path_names(self):
  1016. """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
  1017. parent, dot, me = self._name.rpartition('.')
  1018. if dot == '':
  1019. # This is a top-level module. sys.path contains the parent path.
  1020. return 'sys', 'path'
  1021. # Not a top-level module. parent-module.__path__ contains the
  1022. # parent path.
  1023. return parent, '__path__'
  1024. def _get_parent_path(self):
  1025. parent_module_name, path_attr_name = self._find_parent_path_names()
  1026. return getattr(sys.modules[parent_module_name], path_attr_name)
  1027. def _recalculate(self):
  1028. # If the parent's path has changed, recalculate _path
  1029. parent_path = tuple(self._get_parent_path()) # Make a copy
  1030. if parent_path != self._last_parent_path:
  1031. spec = self._path_finder(self._name, parent_path)
  1032. # Note that no changes are made if a loader is returned, but we
  1033. # do remember the new parent path
  1034. if spec is not None and spec.loader is None:
  1035. if spec.submodule_search_locations:
  1036. self._path = spec.submodule_search_locations
  1037. self._last_parent_path = parent_path # Save the copy
  1038. return self._path
  1039. def __iter__(self):
  1040. return iter(self._recalculate())
  1041. def __getitem__(self, index):
  1042. return self._recalculate()[index]
  1043. def __setitem__(self, index, path):
  1044. self._path[index] = path
  1045. def __len__(self):
  1046. return len(self._recalculate())
  1047. def __repr__(self):
  1048. return '_NamespacePath({!r})'.format(self._path)
  1049. def __contains__(self, item):
  1050. return item in self._recalculate()
  1051. def append(self, item):
  1052. self._path.append(item)
  1053. # We use this exclusively in module_from_spec() for backward-compatibility.
  1054. class _NamespaceLoader:
  1055. def __init__(self, name, path, path_finder):
  1056. self._path = _NamespacePath(name, path, path_finder)
  1057. @staticmethod
  1058. def module_repr(module):
  1059. """Return repr for the module.
  1060. The method is deprecated. The import machinery does the job itself.
  1061. """
  1062. _warnings.warn("_NamespaceLoader.module_repr() is deprecated and "
  1063. "slated for removal in Python 3.12", DeprecationWarning)
  1064. return '<module {!r} (namespace)>'.format(module.__name__)
  1065. def is_package(self, fullname):
  1066. return True
  1067. def get_source(self, fullname):
  1068. return ''
  1069. def get_code(self, fullname):
  1070. return compile('', '<string>', 'exec', dont_inherit=True)
  1071. def create_module(self, spec):
  1072. """Use default semantics for module creation."""
  1073. def exec_module(self, module):
  1074. pass
  1075. def load_module(self, fullname):
  1076. """Load a namespace module.
  1077. This method is deprecated. Use exec_module() instead.
  1078. """
  1079. # The import system never calls this method.
  1080. _bootstrap._verbose_message('namespace module loaded with path {!r}',
  1081. self._path)
  1082. # Warning implemented in _load_module_shim().
  1083. return _bootstrap._load_module_shim(self, fullname)
  1084. def get_resource_reader(self, module):
  1085. from importlib.readers import NamespaceReader
  1086. return NamespaceReader(self._path)
  1087. # Finders #####################################################################
  1088. class PathFinder:
  1089. """Meta path finder for sys.path and package __path__ attributes."""
  1090. @staticmethod
  1091. def invalidate_caches():
  1092. """Call the invalidate_caches() method on all path entry finders
  1093. stored in sys.path_importer_caches (where implemented)."""
  1094. for name, finder in list(sys.path_importer_cache.items()):
  1095. if finder is None:
  1096. del sys.path_importer_cache[name]
  1097. elif hasattr(finder, 'invalidate_caches'):
  1098. finder.invalidate_caches()
  1099. @staticmethod
  1100. def _path_hooks(path):
  1101. """Search sys.path_hooks for a finder for 'path'."""
  1102. if sys.path_hooks is not None and not sys.path_hooks:
  1103. _warnings.warn('sys.path_hooks is empty', ImportWarning)
  1104. for hook in sys.path_hooks:
  1105. try:
  1106. return hook(path)
  1107. except ImportError:
  1108. continue
  1109. else:
  1110. return None
  1111. @classmethod
  1112. def _path_importer_cache(cls, path):
  1113. """Get the finder for the path entry from sys.path_importer_cache.
  1114. If the path entry is not in the cache, find the appropriate finder
  1115. and cache it. If no finder is available, store None.
  1116. """
  1117. if path == '':
  1118. try:
  1119. path = _os.getcwd()
  1120. except FileNotFoundError:
  1121. # Don't cache the failure as the cwd can easily change to
  1122. # a valid directory later on.
  1123. return None
  1124. try:
  1125. finder = sys.path_importer_cache[path]
  1126. except KeyError:
  1127. finder = cls._path_hooks(path)
  1128. sys.path_importer_cache[path] = finder
  1129. return finder
  1130. @classmethod
  1131. def _legacy_get_spec(cls, fullname, finder):
  1132. # This would be a good place for a DeprecationWarning if
  1133. # we ended up going that route.
  1134. if hasattr(finder, 'find_loader'):
  1135. msg = (f"{_bootstrap._object_name(finder)}.find_spec() not found; "
  1136. "falling back to find_loader()")
  1137. _warnings.warn(msg, ImportWarning)
  1138. loader, portions = finder.find_loader(fullname)
  1139. else:
  1140. msg = (f"{_bootstrap._object_name(finder)}.find_spec() not found; "
  1141. "falling back to find_module()")
  1142. _warnings.warn(msg, ImportWarning)
  1143. loader = finder.find_module(fullname)
  1144. portions = []
  1145. if loader is not None:
  1146. return _bootstrap.spec_from_loader(fullname, loader)
  1147. spec = _bootstrap.ModuleSpec(fullname, None)
  1148. spec.submodule_search_locations = portions
  1149. return spec
  1150. @classmethod
  1151. def _get_spec(cls, fullname, path, target=None):
  1152. """Find the loader or namespace_path for this module/package name."""
  1153. # If this ends up being a namespace package, namespace_path is
  1154. # the list of paths that will become its __path__
  1155. namespace_path = []
  1156. for entry in path:
  1157. if not isinstance(entry, (str, bytes)):
  1158. continue
  1159. finder = cls._path_importer_cache(entry)
  1160. if finder is not None:
  1161. if hasattr(finder, 'find_spec'):
  1162. spec = finder.find_spec(fullname, target)
  1163. else:
  1164. spec = cls._legacy_get_spec(fullname, finder)
  1165. if spec is None:
  1166. continue
  1167. if spec.loader is not None:
  1168. return spec
  1169. portions = spec.submodule_search_locations
  1170. if portions is None:
  1171. raise ImportError('spec missing loader')
  1172. # This is possibly part of a namespace package.
  1173. # Remember these path entries (if any) for when we
  1174. # create a namespace package, and continue iterating
  1175. # on path.
  1176. namespace_path.extend(portions)
  1177. else:
  1178. spec = _bootstrap.ModuleSpec(fullname, None)
  1179. spec.submodule_search_locations = namespace_path
  1180. return spec
  1181. @classmethod
  1182. def find_spec(cls, fullname, path=None, target=None):
  1183. """Try to find a spec for 'fullname' on sys.path or 'path'.
  1184. The search is based on sys.path_hooks and sys.path_importer_cache.
  1185. """
  1186. if path is None:
  1187. path = sys.path
  1188. spec = cls._get_spec(fullname, path, target)
  1189. if spec is None:
  1190. return None
  1191. elif spec.loader is None:
  1192. namespace_path = spec.submodule_search_locations
  1193. if namespace_path:
  1194. # We found at least one namespace path. Return a spec which
  1195. # can create the namespace package.
  1196. spec.origin = None
  1197. spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
  1198. return spec
  1199. else:
  1200. return None
  1201. else:
  1202. return spec
  1203. @classmethod
  1204. def find_module(cls, fullname, path=None):
  1205. """find the module on sys.path or 'path' based on sys.path_hooks and
  1206. sys.path_importer_cache.
  1207. This method is deprecated. Use find_spec() instead.
  1208. """
  1209. _warnings.warn("PathFinder.find_module() is deprecated and "
  1210. "slated for removal in Python 3.12; use find_spec() instead",
  1211. DeprecationWarning)
  1212. spec = cls.find_spec(fullname, path)
  1213. if spec is None:
  1214. return None
  1215. return spec.loader
  1216. @staticmethod
  1217. def find_distributions(*args, **kwargs):
  1218. """
  1219. Find distributions.
  1220. Return an iterable of all Distribution instances capable of
  1221. loading the metadata for packages matching ``context.name``
  1222. (or all names if ``None`` indicated) along the paths in the list
  1223. of directories ``context.path``.
  1224. """
  1225. from importlib.metadata import MetadataPathFinder
  1226. return MetadataPathFinder.find_distributions(*args, **kwargs)
  1227. class FileFinder:
  1228. """File-based finder.
  1229. Interactions with the file system are cached for performance, being
  1230. refreshed when the directory the finder is handling has been modified.
  1231. """
  1232. def __init__(self, path, *loader_details):
  1233. """Initialize with the path to search on and a variable number of
  1234. 2-tuples containing the loader and the file suffixes the loader
  1235. recognizes."""
  1236. loaders = []
  1237. for loader, suffixes in loader_details:
  1238. loaders.extend((suffix, loader) for suffix in suffixes)
  1239. self._loaders = loaders
  1240. # Base (directory) path
  1241. self.path = path or '.'
  1242. if not _path_isabs(self.path):
  1243. self.path = _path_join(_os.getcwd(), self.path)
  1244. self._path_mtime = -1
  1245. self._path_cache = set()
  1246. self._relaxed_path_cache = set()
  1247. def invalidate_caches(self):
  1248. """Invalidate the directory mtime."""
  1249. self._path_mtime = -1
  1250. find_module = _find_module_shim
  1251. def find_loader(self, fullname):
  1252. """Try to find a loader for the specified module, or the namespace
  1253. package portions. Returns (loader, list-of-portions).
  1254. This method is deprecated. Use find_spec() instead.
  1255. """
  1256. _warnings.warn("FileFinder.find_loader() is deprecated and "
  1257. "slated for removal in Python 3.12; use find_spec() instead",
  1258. DeprecationWarning)
  1259. spec = self.find_spec(fullname)
  1260. if spec is None:
  1261. return None, []
  1262. return spec.loader, spec.submodule_search_locations or []
  1263. def _get_spec(self, loader_class, fullname, path, smsl, target):
  1264. loader = loader_class(fullname, path)
  1265. return spec_from_file_location(fullname, path, loader=loader,
  1266. submodule_search_locations=smsl)
  1267. def find_spec(self, fullname, target=None):
  1268. """Try to find a spec for the specified module.
  1269. Returns the matching spec, or None if not found.
  1270. """
  1271. is_namespace = False
  1272. tail_module = fullname.rpartition('.')[2]
  1273. try:
  1274. mtime = _path_stat(self.path or _os.getcwd()).st_mtime
  1275. except OSError:
  1276. mtime = -1
  1277. if mtime != self._path_mtime:
  1278. self._fill_cache()
  1279. self._path_mtime = mtime
  1280. # tail_module keeps the original casing, for __file__ and friends
  1281. if _relax_case():
  1282. cache = self._relaxed_path_cache
  1283. cache_module = tail_module.lower()
  1284. else:
  1285. cache = self._path_cache
  1286. cache_module = tail_module
  1287. # Check if the module is the name of a directory (and thus a package).
  1288. if cache_module in cache:
  1289. base_path = _path_join(self.path, tail_module)
  1290. for suffix, loader_class in self._loaders:
  1291. init_filename = '__init__' + suffix
  1292. full_path = _path_join(base_path, init_filename)
  1293. if _path_isfile(full_path):
  1294. return self._get_spec(loader_class, fullname, full_path, [base_path], target)
  1295. else:
  1296. # If a namespace package, return the path if we don't
  1297. # find a module in the next section.
  1298. is_namespace = _path_isdir(base_path)
  1299. # Check for a file w/ a proper suffix exists.
  1300. for suffix, loader_class in self._loaders:
  1301. try:
  1302. full_path = _path_join(self.path, tail_module + suffix)
  1303. except ValueError:
  1304. return None
  1305. _bootstrap._verbose_message('trying {}', full_path, verbosity=2)
  1306. if cache_module + suffix in cache:
  1307. if _path_isfile(full_path):
  1308. return self._get_spec(loader_class, fullname, full_path,
  1309. None, target)
  1310. if is_namespace:
  1311. _bootstrap._verbose_message('possible namespace for {}', base_path)
  1312. spec = _bootstrap.ModuleSpec(fullname, None)
  1313. spec.submodule_search_locations = [base_path]
  1314. return spec
  1315. return None
  1316. def _fill_cache(self):
  1317. """Fill the cache of potential modules and packages for this directory."""
  1318. path = self.path
  1319. try:
  1320. contents = _os.listdir(path or _os.getcwd())
  1321. except (FileNotFoundError, PermissionError, NotADirectoryError):
  1322. # Directory has either been removed, turned into a file, or made
  1323. # unreadable.
  1324. contents = []
  1325. # We store two cached versions, to handle runtime changes of the
  1326. # PYTHONCASEOK environment variable.
  1327. if not sys.platform.startswith('win'):
  1328. self._path_cache = set(contents)
  1329. else:
  1330. # Windows users can import modules with case-insensitive file
  1331. # suffixes (for legacy reasons). Make the suffix lowercase here
  1332. # so it's done once instead of for every import. This is safe as
  1333. # the specified suffixes to check against are always specified in a
  1334. # case-sensitive manner.
  1335. lower_suffix_contents = set()
  1336. for item in contents:
  1337. name, dot, suffix = item.partition('.')
  1338. if dot:
  1339. new_name = '{}.{}'.format(name, suffix.lower())
  1340. else:
  1341. new_name = name
  1342. lower_suffix_contents.add(new_name)
  1343. self._path_cache = lower_suffix_contents
  1344. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  1345. self._relaxed_path_cache = {fn.lower() for fn in contents}
  1346. @classmethod
  1347. def path_hook(cls, *loader_details):
  1348. """A class method which returns a closure to use on sys.path_hook
  1349. which will return an instance using the specified loaders and the path
  1350. called on the closure.
  1351. If the path called on the closure is not a directory, ImportError is
  1352. raised.
  1353. """
  1354. def path_hook_for_FileFinder(path):
  1355. """Path hook for importlib.machinery.FileFinder."""
  1356. if not _path_isdir(path):
  1357. raise ImportError('only directories are supported', path=path)
  1358. return cls(path, *loader_details)
  1359. return path_hook_for_FileFinder
  1360. def __repr__(self):
  1361. return 'FileFinder({!r})'.format(self.path)
  1362. # Import setup ###############################################################
  1363. def _fix_up_module(ns, name, pathname, cpathname=None):
  1364. # This function is used by PyImport_ExecCodeModuleObject().
  1365. loader = ns.get('__loader__')
  1366. spec = ns.get('__spec__')
  1367. if not loader:
  1368. if spec:
  1369. loader = spec.loader
  1370. elif pathname == cpathname:
  1371. loader = SourcelessFileLoader(name, pathname)
  1372. else:
  1373. loader = SourceFileLoader(name, pathname)
  1374. if not spec:
  1375. spec = spec_from_file_location(name, pathname, loader=loader)
  1376. try:
  1377. ns['__spec__'] = spec
  1378. ns['__loader__'] = loader
  1379. ns['__file__'] = pathname
  1380. ns['__cached__'] = cpathname
  1381. except Exception:
  1382. # Not important enough to report.
  1383. pass
  1384. def _get_supported_file_loaders():
  1385. """Returns a list of file-based module loaders.
  1386. Each item is a tuple (loader, suffixes).
  1387. """
  1388. extensions = ExtensionFileLoader, _imp.extension_suffixes()
  1389. source = SourceFileLoader, SOURCE_SUFFIXES
  1390. bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
  1391. return [extensions, source, bytecode]
  1392. def _set_bootstrap_module(_bootstrap_module):
  1393. global _bootstrap
  1394. _bootstrap = _bootstrap_module
  1395. def _install(_bootstrap_module):
  1396. """Install the path-based import components."""
  1397. _set_bootstrap_module(_bootstrap_module)
  1398. supported_loaders = _get_supported_file_loaders()
  1399. sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
  1400. sys.meta_path.append(PathFinder)