_bootstrap_external.py 63 KB

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