_bootstrap_external.py 58 KB

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