• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Core implementation of path-based import.
2
3This module is NOT meant to be directly imported! It has been designed such
4that it can be bootstrapped into Python as the implementation of import. As
5such it requires the injection of specific modules and attributes in order to
6work. One should use importlib as the public-facing version of this module.
7
8"""
9# IMPORTANT: Whenever making changes to this module, be sure to run a top-level
10# `make regen-importlib` followed by `make` in order to get the frozen version
11# of the module updated. Not doing so will result in the Makefile to fail for
12# all others who don't have a ./python around to freeze the module in the early
13# stages of compilation.
14#
15
16# See importlib._setup() for what is injected into the global namespace.
17
18# When editing this code be aware that code executed at import time CANNOT
19# reference any injected objects! This includes not only global code but also
20# anything specified at the class level.
21
22# Module injected manually by _set_bootstrap_module()
23_bootstrap = None
24
25# Import builtin modules
26import _imp
27import _io
28import sys
29import _warnings
30import marshal
31
32
33_MS_WINDOWS = (sys.platform == 'win32')
34if _MS_WINDOWS:
35    import nt as _os
36    import winreg
37else:
38    import posix as _os
39
40
41if _MS_WINDOWS:
42    path_separators = ['\\', '/']
43else:
44    path_separators = ['/']
45# Assumption made in _path_join()
46assert all(len(sep) == 1 for sep in path_separators)
47path_sep = path_separators[0]
48path_sep_tuple = tuple(path_separators)
49path_separators = ''.join(path_separators)
50_pathseps_with_colon = {f':{s}' for s in path_separators}
51
52
53# Bootstrap-related code ######################################################
54_CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win',
55_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin', 'ios', 'tvos', 'watchos'
56_CASE_INSENSITIVE_PLATFORMS =  (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY
57                                + _CASE_INSENSITIVE_PLATFORMS_STR_KEY)
58
59
60def _make_relax_case():
61    if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
62        if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):
63            key = 'PYTHONCASEOK'
64        else:
65            key = b'PYTHONCASEOK'
66
67        def _relax_case():
68            """True if filenames must be checked case-insensitively and ignore environment flags are not set."""
69            return not sys.flags.ignore_environment and key in _os.environ
70    else:
71        def _relax_case():
72            """True if filenames must be checked case-insensitively."""
73            return False
74    return _relax_case
75
76_relax_case = _make_relax_case()
77
78
79def _pack_uint32(x):
80    """Convert a 32-bit integer to little-endian."""
81    return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
82
83
84def _unpack_uint64(data):
85    """Convert 8 bytes in little-endian to an integer."""
86    assert len(data) == 8
87    return int.from_bytes(data, 'little')
88
89def _unpack_uint32(data):
90    """Convert 4 bytes in little-endian to an integer."""
91    assert len(data) == 4
92    return int.from_bytes(data, 'little')
93
94def _unpack_uint16(data):
95    """Convert 2 bytes in little-endian to an integer."""
96    assert len(data) == 2
97    return int.from_bytes(data, 'little')
98
99
100if _MS_WINDOWS:
101    def _path_join(*path_parts):
102        """Replacement for os.path.join()."""
103        if not path_parts:
104            return ""
105        if len(path_parts) == 1:
106            return path_parts[0]
107        root = ""
108        path = []
109        for new_root, tail in map(_os._path_splitroot, path_parts):
110            if new_root.startswith(path_sep_tuple) or new_root.endswith(path_sep_tuple):
111                root = new_root.rstrip(path_separators) or root
112                path = [path_sep + tail]
113            elif new_root.endswith(':'):
114                if root.casefold() != new_root.casefold():
115                    # Drive relative paths have to be resolved by the OS, so we reset the
116                    # tail but do not add a path_sep prefix.
117                    root = new_root
118                    path = [tail]
119                else:
120                    path.append(tail)
121            else:
122                root = new_root or root
123                path.append(tail)
124        path = [p.rstrip(path_separators) for p in path if p]
125        if len(path) == 1 and not path[0]:
126            # Avoid losing the root's trailing separator when joining with nothing
127            return root + path_sep
128        return root + path_sep.join(path)
129
130else:
131    def _path_join(*path_parts):
132        """Replacement for os.path.join()."""
133        return path_sep.join([part.rstrip(path_separators)
134                              for part in path_parts if part])
135
136
137def _path_split(path):
138    """Replacement for os.path.split()."""
139    i = max(path.rfind(p) for p in path_separators)
140    if i < 0:
141        return '', path
142    return path[:i], path[i + 1:]
143
144
145def _path_stat(path):
146    """Stat the path.
147
148    Made a separate function to make it easier to override in experiments
149    (e.g. cache stat results).
150
151    """
152    return _os.stat(path)
153
154
155def _path_is_mode_type(path, mode):
156    """Test whether the path is the specified mode type."""
157    try:
158        stat_info = _path_stat(path)
159    except OSError:
160        return False
161    return (stat_info.st_mode & 0o170000) == mode
162
163
164def _path_isfile(path):
165    """Replacement for os.path.isfile."""
166    return _path_is_mode_type(path, 0o100000)
167
168
169def _path_isdir(path):
170    """Replacement for os.path.isdir."""
171    if not path:
172        path = _os.getcwd()
173    return _path_is_mode_type(path, 0o040000)
174
175
176if _MS_WINDOWS:
177    def _path_isabs(path):
178        """Replacement for os.path.isabs."""
179        if not path:
180            return False
181        root = _os._path_splitroot(path)[0].replace('/', '\\')
182        return len(root) > 1 and (root.startswith('\\\\') or root.endswith('\\'))
183
184else:
185    def _path_isabs(path):
186        """Replacement for os.path.isabs."""
187        return path.startswith(path_separators)
188
189
190def _path_abspath(path):
191    """Replacement for os.path.abspath."""
192    if not _path_isabs(path):
193        for sep in path_separators:
194            path = path.removeprefix(f".{sep}")
195        return _path_join(_os.getcwd(), path)
196    else:
197        return path
198
199
200def _write_atomic(path, data, mode=0o666):
201    """Best-effort function to write data to a path atomically.
202    Be prepared to handle a FileExistsError if concurrent writing of the
203    temporary file is attempted."""
204    # id() is used to generate a pseudo-random filename.
205    path_tmp = f'{path}.{id(path)}'
206    fd = _os.open(path_tmp,
207                  _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
208    try:
209        # We first write data to a temporary file, and then use os.replace() to
210        # perform an atomic rename.
211        with _io.FileIO(fd, 'wb') as file:
212            bytes_written = file.write(data)
213        if bytes_written != len(data):
214            # Raise an OSError so the 'except' below cleans up the partially
215            # written file.
216            raise OSError("os.write() didn't write the full pyc file")
217        _os.replace(path_tmp, path)
218    except OSError:
219        try:
220            _os.unlink(path_tmp)
221        except OSError:
222            pass
223        raise
224
225
226_code_type = type(_write_atomic.__code__)
227
228
229# Finder/loader utility code ###############################################
230
231# Magic word to reject .pyc files generated by other Python versions.
232# It should change for each incompatible change to the bytecode.
233#
234# The value of CR and LF is incorporated so if you ever read or write
235# a .pyc file in text mode the magic number will be wrong; also, the
236# Apple MPW compiler swaps their values, botching string constants.
237#
238# There were a variety of old schemes for setting the magic number.
239# The current working scheme is to increment the previous value by
240# 10.
241#
242# Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
243# number also includes a new "magic tag", i.e. a human readable string used
244# to represent the magic number in __pycache__ directories.  When you change
245# the magic number, you must also set a new unique magic tag.  Generally this
246# can be named after the Python major version of the magic number bump, but
247# it can really be anything, as long as it's different than anything else
248# that's come before.  The tags are included in the following table, starting
249# with Python 3.2a0.
250#
251# Known values:
252#  Python 1.5:   20121
253#  Python 1.5.1: 20121
254#     Python 1.5.2: 20121
255#     Python 1.6:   50428
256#     Python 2.0:   50823
257#     Python 2.0.1: 50823
258#     Python 2.1:   60202
259#     Python 2.1.1: 60202
260#     Python 2.1.2: 60202
261#     Python 2.2:   60717
262#     Python 2.3a0: 62011
263#     Python 2.3a0: 62021
264#     Python 2.3a0: 62011 (!)
265#     Python 2.4a0: 62041
266#     Python 2.4a3: 62051
267#     Python 2.4b1: 62061
268#     Python 2.5a0: 62071
269#     Python 2.5a0: 62081 (ast-branch)
270#     Python 2.5a0: 62091 (with)
271#     Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
272#     Python 2.5b3: 62101 (fix wrong code: for x, in ...)
273#     Python 2.5b3: 62111 (fix wrong code: x += yield)
274#     Python 2.5c1: 62121 (fix wrong lnotab with for loops and
275#                          storing constants that should have been removed)
276#     Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
277#     Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
278#     Python 2.6a1: 62161 (WITH_CLEANUP optimization)
279#     Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
280#     Python 2.7a0: 62181 (optimize conditional branches:
281#                          introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
282#     Python 2.7a0  62191 (introduce SETUP_WITH)
283#     Python 2.7a0  62201 (introduce BUILD_SET)
284#     Python 2.7a0  62211 (introduce MAP_ADD and SET_ADD)
285#     Python 3000:   3000
286#                    3010 (removed UNARY_CONVERT)
287#                    3020 (added BUILD_SET)
288#                    3030 (added keyword-only parameters)
289#                    3040 (added signature annotations)
290#                    3050 (print becomes a function)
291#                    3060 (PEP 3115 metaclass syntax)
292#                    3061 (string literals become unicode)
293#                    3071 (PEP 3109 raise changes)
294#                    3081 (PEP 3137 make __file__ and __name__ unicode)
295#                    3091 (kill str8 interning)
296#                    3101 (merge from 2.6a0, see 62151)
297#                    3103 (__file__ points to source file)
298#     Python 3.0a4: 3111 (WITH_CLEANUP optimization).
299#     Python 3.0b1: 3131 (lexical exception stacking, including POP_EXCEPT
300                          #3021)
301#     Python 3.1a1: 3141 (optimize list, set and dict comprehensions:
302#                         change LIST_APPEND and SET_ADD, add MAP_ADD #2183)
303#     Python 3.1a1: 3151 (optimize conditional branches:
304#                         introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
305                          #4715)
306#     Python 3.2a1: 3160 (add SETUP_WITH #6101)
307#                   tag: cpython-32
308#     Python 3.2a2: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR #9225)
309#                   tag: cpython-32
310#     Python 3.2a3  3180 (add DELETE_DEREF #4617)
311#     Python 3.3a1  3190 (__class__ super closure changed)
312#     Python 3.3a1  3200 (PEP 3155 __qualname__ added #13448)
313#     Python 3.3a1  3210 (added size modulo 2**32 to the pyc header #13645)
314#     Python 3.3a2  3220 (changed PEP 380 implementation #14230)
315#     Python 3.3a4  3230 (revert changes to implicit __class__ closure #14857)
316#     Python 3.4a1  3250 (evaluate positional default arguments before
317#                        keyword-only defaults #16967)
318#     Python 3.4a1  3260 (add LOAD_CLASSDEREF; allow locals of class to override
319#                        free vars #17853)
320#     Python 3.4a1  3270 (various tweaks to the __class__ closure #12370)
321#     Python 3.4a1  3280 (remove implicit class argument)
322#     Python 3.4a4  3290 (changes to __qualname__ computation #19301)
323#     Python 3.4a4  3300 (more changes to __qualname__ computation #19301)
324#     Python 3.4rc2 3310 (alter __qualname__ computation #20625)
325#     Python 3.5a1  3320 (PEP 465: Matrix multiplication operator #21176)
326#     Python 3.5b1  3330 (PEP 448: Additional Unpacking Generalizations #2292)
327#     Python 3.5b2  3340 (fix dictionary display evaluation order #11205)
328#     Python 3.5b3  3350 (add GET_YIELD_FROM_ITER opcode #24400)
329#     Python 3.5.2  3351 (fix BUILD_MAP_UNPACK_WITH_CALL opcode #27286)
330#     Python 3.6a0  3360 (add FORMAT_VALUE opcode #25483)
331#     Python 3.6a1  3361 (lineno delta of code.co_lnotab becomes signed #26107)
332#     Python 3.6a2  3370 (16 bit wordcode #26647)
333#     Python 3.6a2  3371 (add BUILD_CONST_KEY_MAP opcode #27140)
334#     Python 3.6a2  3372 (MAKE_FUNCTION simplification, remove MAKE_CLOSURE
335#                         #27095)
336#     Python 3.6b1  3373 (add BUILD_STRING opcode #27078)
337#     Python 3.6b1  3375 (add SETUP_ANNOTATIONS and STORE_ANNOTATION opcodes
338#                         #27985)
339#     Python 3.6b1  3376 (simplify CALL_FUNCTIONs & BUILD_MAP_UNPACK_WITH_CALL
340                          #27213)
341#     Python 3.6b1  3377 (set __class__ cell from type.__new__ #23722)
342#     Python 3.6b2  3378 (add BUILD_TUPLE_UNPACK_WITH_CALL #28257)
343#     Python 3.6rc1 3379 (more thorough __class__ validation #23722)
344#     Python 3.7a1  3390 (add LOAD_METHOD and CALL_METHOD opcodes #26110)
345#     Python 3.7a2  3391 (update GET_AITER #31709)
346#     Python 3.7a4  3392 (PEP 552: Deterministic pycs #31650)
347#     Python 3.7b1  3393 (remove STORE_ANNOTATION opcode #32550)
348#     Python 3.7b5  3394 (restored docstring as the first stmt in the body;
349#                         this might affected the first line number #32911)
350#     Python 3.8a1  3400 (move frame block handling to compiler #17611)
351#     Python 3.8a1  3401 (add END_ASYNC_FOR #33041)
352#     Python 3.8a1  3410 (PEP570 Python Positional-Only Parameters #36540)
353#     Python 3.8b2  3411 (Reverse evaluation order of key: value in dict
354#                         comprehensions #35224)
355#     Python 3.8b2  3412 (Swap the position of positional args and positional
356#                         only args in ast.arguments #37593)
357#     Python 3.8b4  3413 (Fix "break" and "continue" in "finally" #37830)
358#     Python 3.9a0  3420 (add LOAD_ASSERTION_ERROR #34880)
359#     Python 3.9a0  3421 (simplified bytecode for with blocks #32949)
360#     Python 3.9a0  3422 (remove BEGIN_FINALLY, END_FINALLY, CALL_FINALLY, POP_FINALLY bytecodes #33387)
361#     Python 3.9a2  3423 (add IS_OP, CONTAINS_OP and JUMP_IF_NOT_EXC_MATCH bytecodes #39156)
362#     Python 3.9a2  3424 (simplify bytecodes for *value unpacking)
363#     Python 3.9a2  3425 (simplify bytecodes for **value unpacking)
364#     Python 3.10a1 3430 (Make 'annotations' future by default)
365#     Python 3.10a1 3431 (New line number table format -- PEP 626)
366#     Python 3.10a2 3432 (Function annotation for MAKE_FUNCTION is changed from dict to tuple bpo-42202)
367#     Python 3.10a2 3433 (RERAISE restores f_lasti if oparg != 0)
368#     Python 3.10a6 3434 (PEP 634: Structural Pattern Matching)
369#     Python 3.10a7 3435 Use instruction offsets (as opposed to byte offsets).
370#     Python 3.10b1 3436 (Add GEN_START bytecode #43683)
371#     Python 3.10b1 3437 (Undo making 'annotations' future by default - We like to dance among core devs!)
372#     Python 3.10b1 3438 Safer line number table handling.
373#     Python 3.10b1 3439 (Add ROT_N)
374#     Python 3.11a1 3450 Use exception table for unwinding ("zero cost" exception handling)
375#     Python 3.11a1 3451 (Add CALL_METHOD_KW)
376#     Python 3.11a1 3452 (drop nlocals from marshaled code objects)
377#     Python 3.11a1 3453 (add co_fastlocalnames and co_fastlocalkinds)
378#     Python 3.11a1 3454 (compute cell offsets relative to locals bpo-43693)
379#     Python 3.11a1 3455 (add MAKE_CELL bpo-43693)
380#     Python 3.11a1 3456 (interleave cell args bpo-43693)
381#     Python 3.11a1 3457 (Change localsplus to a bytes object bpo-43693)
382#     Python 3.11a1 3458 (imported objects now don't use LOAD_METHOD/CALL_METHOD)
383#     Python 3.11a1 3459 (PEP 657: add end line numbers and column offsets for instructions)
384#     Python 3.11a1 3460 (Add co_qualname field to PyCodeObject bpo-44530)
385#     Python 3.11a1 3461 (JUMP_ABSOLUTE must jump backwards)
386#     Python 3.11a2 3462 (bpo-44511: remove COPY_DICT_WITHOUT_KEYS, change
387#                         MATCH_CLASS and MATCH_KEYS, and add COPY)
388#     Python 3.11a3 3463 (bpo-45711: JUMP_IF_NOT_EXC_MATCH no longer pops the
389#                         active exception)
390#     Python 3.11a3 3464 (bpo-45636: Merge numeric BINARY_*/INPLACE_* into
391#                         BINARY_OP)
392#     Python 3.11a3 3465 (Add COPY_FREE_VARS opcode)
393#     Python 3.11a4 3466 (bpo-45292: PEP-654 except*)
394#     Python 3.11a4 3467 (Change CALL_xxx opcodes)
395#     Python 3.11a4 3468 (Add SEND opcode)
396#     Python 3.11a4 3469 (bpo-45711: remove type, traceback from exc_info)
397#     Python 3.11a4 3470 (bpo-46221: PREP_RERAISE_STAR no longer pushes lasti)
398#     Python 3.11a4 3471 (bpo-46202: remove pop POP_EXCEPT_AND_RERAISE)
399#     Python 3.11a4 3472 (bpo-46009: replace GEN_START with POP_TOP)
400#     Python 3.11a4 3473 (Add POP_JUMP_IF_NOT_NONE/POP_JUMP_IF_NONE opcodes)
401#     Python 3.11a4 3474 (Add RESUME opcode)
402#     Python 3.11a5 3475 (Add RETURN_GENERATOR opcode)
403#     Python 3.11a5 3476 (Add ASYNC_GEN_WRAP opcode)
404#     Python 3.11a5 3477 (Replace DUP_TOP/DUP_TOP_TWO with COPY and
405#                         ROT_TWO/ROT_THREE/ROT_FOUR/ROT_N with SWAP)
406#     Python 3.11a5 3478 (New CALL opcodes)
407#     Python 3.11a5 3479 (Add PUSH_NULL opcode)
408#     Python 3.11a5 3480 (New CALL opcodes, second iteration)
409#     Python 3.11a5 3481 (Use inline cache for BINARY_OP)
410#     Python 3.11a5 3482 (Use inline caching for UNPACK_SEQUENCE and LOAD_GLOBAL)
411#     Python 3.11a5 3483 (Use inline caching for COMPARE_OP and BINARY_SUBSCR)
412#     Python 3.11a5 3484 (Use inline caching for LOAD_ATTR, LOAD_METHOD, and
413#                         STORE_ATTR)
414#     Python 3.11a5 3485 (Add an oparg to GET_AWAITABLE)
415#     Python 3.11a6 3486 (Use inline caching for PRECALL and CALL)
416#     Python 3.11a6 3487 (Remove the adaptive "oparg counter" mechanism)
417#     Python 3.11a6 3488 (LOAD_GLOBAL can push additional NULL)
418#     Python 3.11a6 3489 (Add JUMP_BACKWARD, remove JUMP_ABSOLUTE)
419#     Python 3.11a6 3490 (remove JUMP_IF_NOT_EXC_MATCH, add CHECK_EXC_MATCH)
420#     Python 3.11a6 3491 (remove JUMP_IF_NOT_EG_MATCH, add CHECK_EG_MATCH,
421#                         add JUMP_BACKWARD_NO_INTERRUPT, make JUMP_NO_INTERRUPT virtual)
422#     Python 3.11a7 3492 (make POP_JUMP_IF_NONE/NOT_NONE/TRUE/FALSE relative)
423#     Python 3.11a7 3493 (Make JUMP_IF_TRUE_OR_POP/JUMP_IF_FALSE_OR_POP relative)
424#     Python 3.11a7 3494 (New location info table)
425#     Python 3.11b4 3495 (Set line number of module's RESUME instr to 0 per PEP 626)
426#     Python 3.12a1 3500 (Remove PRECALL opcode)
427#     Python 3.12a1 3501 (YIELD_VALUE oparg == stack_depth)
428#     Python 3.12a1 3502 (LOAD_FAST_CHECK, no NULL-check in LOAD_FAST)
429#     Python 3.12a1 3503 (Shrink LOAD_METHOD cache)
430#     Python 3.12a1 3504 (Merge LOAD_METHOD back into LOAD_ATTR)
431#     Python 3.12a1 3505 (Specialization/Cache for FOR_ITER)
432#     Python 3.12a1 3506 (Add BINARY_SLICE and STORE_SLICE instructions)
433#     Python 3.12a1 3507 (Set lineno of module's RESUME to 0)
434#     Python 3.12a1 3508 (Add CLEANUP_THROW)
435#     Python 3.12a1 3509 (Conditional jumps only jump forward)
436#     Python 3.12a2 3510 (FOR_ITER leaves iterator on the stack)
437#     Python 3.12a2 3511 (Add STOPITERATION_ERROR instruction)
438#     Python 3.12a2 3512 (Remove all unused consts from code objects)
439#     Python 3.12a4 3513 (Add CALL_INTRINSIC_1 instruction, removed STOPITERATION_ERROR, PRINT_EXPR, IMPORT_STAR)
440#     Python 3.12a4 3514 (Remove ASYNC_GEN_WRAP, LIST_TO_TUPLE, and UNARY_POSITIVE)
441#     Python 3.12a5 3515 (Embed jump mask in COMPARE_OP oparg)
442#     Python 3.12a5 3516 (Add COMPARE_AND_BRANCH instruction)
443#     Python 3.12a5 3517 (Change YIELD_VALUE oparg to exception block depth)
444#     Python 3.12a6 3518 (Add RETURN_CONST instruction)
445#     Python 3.12a6 3519 (Modify SEND instruction)
446#     Python 3.12a6 3520 (Remove PREP_RERAISE_STAR, add CALL_INTRINSIC_2)
447#     Python 3.12a7 3521 (Shrink the LOAD_GLOBAL caches)
448#     Python 3.12a7 3522 (Removed JUMP_IF_FALSE_OR_POP/JUMP_IF_TRUE_OR_POP)
449#     Python 3.12a7 3523 (Convert COMPARE_AND_BRANCH back to COMPARE_OP)
450#     Python 3.12a7 3524 (Shrink the BINARY_SUBSCR caches)
451#     Python 3.12b1 3525 (Shrink the CALL caches)
452#     Python 3.12b1 3526 (Add instrumentation support)
453#     Python 3.12b1 3527 (Add LOAD_SUPER_ATTR)
454#     Python 3.12b1 3528 (Add LOAD_SUPER_ATTR_METHOD specialization)
455#     Python 3.12b1 3529 (Inline list/dict/set comprehensions)
456#     Python 3.12b1 3530 (Shrink the LOAD_SUPER_ATTR caches)
457#     Python 3.12b1 3531 (Add PEP 695 changes)
458#     Python 3.13a1 3550 (Plugin optimizer support)
459#     Python 3.13a1 3551 (Compact superinstructions)
460#     Python 3.13a1 3552 (Remove LOAD_FAST__LOAD_CONST and LOAD_CONST__LOAD_FAST)
461#     Python 3.13a1 3553 (Add SET_FUNCTION_ATTRIBUTE)
462#     Python 3.13a1 3554 (more efficient bytecodes for f-strings)
463#     Python 3.13a1 3555 (generate specialized opcodes metadata from bytecodes.c)
464#     Python 3.13a1 3556 (Convert LOAD_CLOSURE to a pseudo-op)
465#     Python 3.13a1 3557 (Make the conversion to boolean in jumps explicit)
466#     Python 3.13a1 3558 (Reorder the stack items for CALL)
467#     Python 3.13a1 3559 (Generate opcode IDs from bytecodes.c)
468#     Python 3.13a1 3560 (Add RESUME_CHECK instruction)
469#     Python 3.13a1 3561 (Add cache entry to branch instructions)
470#     Python 3.13a1 3562 (Assign opcode IDs for internal ops in separate range)
471#     Python 3.13a1 3563 (Add CALL_KW and remove KW_NAMES)
472#     Python 3.13a1 3564 (Removed oparg from YIELD_VALUE, changed oparg values of RESUME)
473#     Python 3.13a1 3565 (Oparg of YIELD_VALUE indicates whether it is in a yield-from)
474#     Python 3.13a1 3566 (Emit JUMP_NO_INTERRUPT instead of JUMP for non-loop no-lineno cases)
475#     Python 3.13a1 3567 (Reimplement line number propagation by the compiler)
476#     Python 3.13a1 3568 (Change semantics of END_FOR)
477#     Python 3.13a5 3569 (Specialize CONTAINS_OP)
478#     Python 3.13a6 3570 (Add __firstlineno__ class attribute)
479#     Python 3.13b1 3571 (Fix miscompilation of private names in generic classes)
480
481#     Python 3.14 will start with 3600
482
483#     Please don't copy-paste the same pre-release tag for new entries above!!!
484#     You should always use the *upcoming* tag. For example, if 3.12a6 came out
485#     a week ago, I should put "Python 3.12a7" next to my new magic number.
486
487# MAGIC must change whenever the bytecode emitted by the compiler may no
488# longer be understood by older implementations of the eval loop (usually
489# due to the addition of new opcodes).
490#
491# Starting with Python 3.11, Python 3.n starts with magic number 2900+50n.
492#
493# Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array
494# in PC/launcher.c must also be updated.
495
496MAGIC_NUMBER = (3571).to_bytes(2, 'little') + b'\r\n'
497
498_RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little')  # For import.c
499
500_PYCACHE = '__pycache__'
501_OPT = 'opt-'
502
503SOURCE_SUFFIXES = ['.py']
504if _MS_WINDOWS:
505    SOURCE_SUFFIXES.append('.pyw')
506
507EXTENSION_SUFFIXES = _imp.extension_suffixes()
508
509BYTECODE_SUFFIXES = ['.pyc']
510# Deprecated.
511DEBUG_BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES = BYTECODE_SUFFIXES
512
513def cache_from_source(path, debug_override=None, *, optimization=None):
514    """Given the path to a .py file, return the path to its .pyc file.
515
516    The .py file does not need to exist; this simply returns the path to the
517    .pyc file calculated as if the .py file were imported.
518
519    The 'optimization' parameter controls the presumed optimization level of
520    the bytecode file. If 'optimization' is not None, the string representation
521    of the argument is taken and verified to be alphanumeric (else ValueError
522    is raised).
523
524    The debug_override parameter is deprecated. If debug_override is not None,
525    a True value is the same as setting 'optimization' to the empty string
526    while a False value is equivalent to setting 'optimization' to '1'.
527
528    If sys.implementation.cache_tag is None then NotImplementedError is raised.
529
530    """
531    if debug_override is not None:
532        _warnings.warn('the debug_override parameter is deprecated; use '
533                       "'optimization' instead", DeprecationWarning)
534        if optimization is not None:
535            message = 'debug_override or optimization must be set to None'
536            raise TypeError(message)
537        optimization = '' if debug_override else 1
538    path = _os.fspath(path)
539    head, tail = _path_split(path)
540    base, sep, rest = tail.rpartition('.')
541    tag = sys.implementation.cache_tag
542    if tag is None:
543        raise NotImplementedError('sys.implementation.cache_tag is None')
544    almost_filename = ''.join([(base if base else rest), sep, tag])
545    if optimization is None:
546        if sys.flags.optimize == 0:
547            optimization = ''
548        else:
549            optimization = sys.flags.optimize
550    optimization = str(optimization)
551    if optimization != '':
552        if not optimization.isalnum():
553            raise ValueError(f'{optimization!r} is not alphanumeric')
554        almost_filename = f'{almost_filename}.{_OPT}{optimization}'
555    filename = almost_filename + BYTECODE_SUFFIXES[0]
556    if sys.pycache_prefix is not None:
557        # We need an absolute path to the py file to avoid the possibility of
558        # collisions within sys.pycache_prefix, if someone has two different
559        # `foo/bar.py` on their system and they import both of them using the
560        # same sys.pycache_prefix. Let's say sys.pycache_prefix is
561        # `C:\Bytecode`; the idea here is that if we get `Foo\Bar`, we first
562        # make it absolute (`C:\Somewhere\Foo\Bar`), then make it root-relative
563        # (`Somewhere\Foo\Bar`), so we end up placing the bytecode file in an
564        # unambiguous `C:\Bytecode\Somewhere\Foo\Bar\`.
565        head = _path_abspath(head)
566
567        # Strip initial drive from a Windows path. We know we have an absolute
568        # path here, so the second part of the check rules out a POSIX path that
569        # happens to contain a colon at the second character.
570        if head[1] == ':' and head[0] not in path_separators:
571            head = head[2:]
572
573        # Strip initial path separator from `head` to complete the conversion
574        # back to a root-relative path before joining.
575        return _path_join(
576            sys.pycache_prefix,
577            head.lstrip(path_separators),
578            filename,
579        )
580    return _path_join(head, _PYCACHE, filename)
581
582
583def source_from_cache(path):
584    """Given the path to a .pyc. file, return the path to its .py file.
585
586    The .pyc file does not need to exist; this simply returns the path to
587    the .py file calculated to correspond to the .pyc file.  If path does
588    not conform to PEP 3147/488 format, ValueError will be raised. If
589    sys.implementation.cache_tag is None then NotImplementedError is raised.
590
591    """
592    if sys.implementation.cache_tag is None:
593        raise NotImplementedError('sys.implementation.cache_tag is None')
594    path = _os.fspath(path)
595    head, pycache_filename = _path_split(path)
596    found_in_pycache_prefix = False
597    if sys.pycache_prefix is not None:
598        stripped_path = sys.pycache_prefix.rstrip(path_separators)
599        if head.startswith(stripped_path + path_sep):
600            head = head[len(stripped_path):]
601            found_in_pycache_prefix = True
602    if not found_in_pycache_prefix:
603        head, pycache = _path_split(head)
604        if pycache != _PYCACHE:
605            raise ValueError(f'{_PYCACHE} not bottom-level directory in '
606                             f'{path!r}')
607    dot_count = pycache_filename.count('.')
608    if dot_count not in {2, 3}:
609        raise ValueError(f'expected only 2 or 3 dots in {pycache_filename!r}')
610    elif dot_count == 3:
611        optimization = pycache_filename.rsplit('.', 2)[-2]
612        if not optimization.startswith(_OPT):
613            raise ValueError("optimization portion of filename does not start "
614                             f"with {_OPT!r}")
615        opt_level = optimization[len(_OPT):]
616        if not opt_level.isalnum():
617            raise ValueError(f"optimization level {optimization!r} is not an "
618                             "alphanumeric value")
619    base_filename = pycache_filename.partition('.')[0]
620    return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
621
622
623def _get_sourcefile(bytecode_path):
624    """Convert a bytecode file path to a source path (if possible).
625
626    This function exists purely for backwards-compatibility for
627    PyImport_ExecCodeModuleWithFilenames() in the C API.
628
629    """
630    if len(bytecode_path) == 0:
631        return None
632    rest, _, extension = bytecode_path.rpartition('.')
633    if not rest or extension.lower()[-3:-1] != 'py':
634        return bytecode_path
635    try:
636        source_path = source_from_cache(bytecode_path)
637    except (NotImplementedError, ValueError):
638        source_path = bytecode_path[:-1]
639    return source_path if _path_isfile(source_path) else bytecode_path
640
641
642def _get_cached(filename):
643    if filename.endswith(tuple(SOURCE_SUFFIXES)):
644        try:
645            return cache_from_source(filename)
646        except NotImplementedError:
647            pass
648    elif filename.endswith(tuple(BYTECODE_SUFFIXES)):
649        return filename
650    else:
651        return None
652
653
654def _calc_mode(path):
655    """Calculate the mode permissions for a bytecode file."""
656    try:
657        mode = _path_stat(path).st_mode
658    except OSError:
659        mode = 0o666
660    # We always ensure write access so we can update cached files
661    # later even when the source files are read-only on Windows (#6074)
662    mode |= 0o200
663    return mode
664
665
666def _check_name(method):
667    """Decorator to verify that the module being requested matches the one the
668    loader can handle.
669
670    The first argument (self) must define _name which the second argument is
671    compared against. If the comparison fails then ImportError is raised.
672
673    """
674    def _check_name_wrapper(self, name=None, *args, **kwargs):
675        if name is None:
676            name = self.name
677        elif self.name != name:
678            raise ImportError('loader for %s cannot handle %s' %
679                                (self.name, name), name=name)
680        return method(self, name, *args, **kwargs)
681
682    # FIXME: @_check_name is used to define class methods before the
683    # _bootstrap module is set by _set_bootstrap_module().
684    if _bootstrap is not None:
685        _wrap = _bootstrap._wrap
686    else:
687        def _wrap(new, old):
688            for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
689                if hasattr(old, replace):
690                    setattr(new, replace, getattr(old, replace))
691            new.__dict__.update(old.__dict__)
692
693    _wrap(_check_name_wrapper, method)
694    return _check_name_wrapper
695
696
697def _classify_pyc(data, name, exc_details):
698    """Perform basic validity checking of a pyc header and return the flags field,
699    which determines how the pyc should be further validated against the source.
700
701    *data* is the contents of the pyc file. (Only the first 16 bytes are
702    required, though.)
703
704    *name* is the name of the module being imported. It is used for logging.
705
706    *exc_details* is a dictionary passed to ImportError if it raised for
707    improved debugging.
708
709    ImportError is raised when the magic number is incorrect or when the flags
710    field is invalid. EOFError is raised when the data is found to be truncated.
711
712    """
713    magic = data[:4]
714    if magic != MAGIC_NUMBER:
715        message = f'bad magic number in {name!r}: {magic!r}'
716        _bootstrap._verbose_message('{}', message)
717        raise ImportError(message, **exc_details)
718    if len(data) < 16:
719        message = f'reached EOF while reading pyc header of {name!r}'
720        _bootstrap._verbose_message('{}', message)
721        raise EOFError(message)
722    flags = _unpack_uint32(data[4:8])
723    # Only the first two flags are defined.
724    if flags & ~0b11:
725        message = f'invalid flags {flags!r} in {name!r}'
726        raise ImportError(message, **exc_details)
727    return flags
728
729
730def _validate_timestamp_pyc(data, source_mtime, source_size, name,
731                            exc_details):
732    """Validate a pyc against the source last-modified time.
733
734    *data* is the contents of the pyc file. (Only the first 16 bytes are
735    required.)
736
737    *source_mtime* is the last modified timestamp of the source file.
738
739    *source_size* is None or the size of the source file in bytes.
740
741    *name* is the name of the module being imported. It is used for logging.
742
743    *exc_details* is a dictionary passed to ImportError if it raised for
744    improved debugging.
745
746    An ImportError is raised if the bytecode is stale.
747
748    """
749    if _unpack_uint32(data[8:12]) != (source_mtime & 0xFFFFFFFF):
750        message = f'bytecode is stale for {name!r}'
751        _bootstrap._verbose_message('{}', message)
752        raise ImportError(message, **exc_details)
753    if (source_size is not None and
754        _unpack_uint32(data[12:16]) != (source_size & 0xFFFFFFFF)):
755        raise ImportError(f'bytecode is stale for {name!r}', **exc_details)
756
757
758def _validate_hash_pyc(data, source_hash, name, exc_details):
759    """Validate a hash-based pyc by checking the real source hash against the one in
760    the pyc header.
761
762    *data* is the contents of the pyc file. (Only the first 16 bytes are
763    required.)
764
765    *source_hash* is the importlib.util.source_hash() of the source file.
766
767    *name* is the name of the module being imported. It is used for logging.
768
769    *exc_details* is a dictionary passed to ImportError if it raised for
770    improved debugging.
771
772    An ImportError is raised if the bytecode is stale.
773
774    """
775    if data[8:16] != source_hash:
776        raise ImportError(
777            f'hash in bytecode doesn\'t match hash of source {name!r}',
778            **exc_details,
779        )
780
781
782def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
783    """Compile bytecode as found in a pyc."""
784    code = marshal.loads(data)
785    if isinstance(code, _code_type):
786        _bootstrap._verbose_message('code object from {!r}', bytecode_path)
787        if source_path is not None:
788            _imp._fix_co_filename(code, source_path)
789        return code
790    else:
791        raise ImportError(f'Non-code object in {bytecode_path!r}',
792                          name=name, path=bytecode_path)
793
794
795def _code_to_timestamp_pyc(code, mtime=0, source_size=0):
796    "Produce the data for a timestamp-based pyc."
797    data = bytearray(MAGIC_NUMBER)
798    data.extend(_pack_uint32(0))
799    data.extend(_pack_uint32(mtime))
800    data.extend(_pack_uint32(source_size))
801    data.extend(marshal.dumps(code))
802    return data
803
804
805def _code_to_hash_pyc(code, source_hash, checked=True):
806    "Produce the data for a hash-based pyc."
807    data = bytearray(MAGIC_NUMBER)
808    flags = 0b1 | checked << 1
809    data.extend(_pack_uint32(flags))
810    assert len(source_hash) == 8
811    data.extend(source_hash)
812    data.extend(marshal.dumps(code))
813    return data
814
815
816def decode_source(source_bytes):
817    """Decode bytes representing source code and return the string.
818
819    Universal newline support is used in the decoding.
820    """
821    import tokenize  # To avoid bootstrap issues.
822    source_bytes_readline = _io.BytesIO(source_bytes).readline
823    encoding = tokenize.detect_encoding(source_bytes_readline)
824    newline_decoder = _io.IncrementalNewlineDecoder(None, True)
825    return newline_decoder.decode(source_bytes.decode(encoding[0]))
826
827
828# Module specifications #######################################################
829
830_POPULATE = object()
831
832
833def spec_from_file_location(name, location=None, *, loader=None,
834                            submodule_search_locations=_POPULATE):
835    """Return a module spec based on a file location.
836
837    To indicate that the module is a package, set
838    submodule_search_locations to a list of directory paths.  An
839    empty list is sufficient, though its not otherwise useful to the
840    import system.
841
842    The loader must take a spec as its only __init__() arg.
843
844    """
845    if location is None:
846        # The caller may simply want a partially populated location-
847        # oriented spec.  So we set the location to a bogus value and
848        # fill in as much as we can.
849        location = '<unknown>'
850        if hasattr(loader, 'get_filename'):
851            # ExecutionLoader
852            try:
853                location = loader.get_filename(name)
854            except ImportError:
855                pass
856    else:
857        location = _os.fspath(location)
858        try:
859            location = _path_abspath(location)
860        except OSError:
861            pass
862
863    # If the location is on the filesystem, but doesn't actually exist,
864    # we could return None here, indicating that the location is not
865    # valid.  However, we don't have a good way of testing since an
866    # indirect location (e.g. a zip file or URL) will look like a
867    # non-existent file relative to the filesystem.
868
869    spec = _bootstrap.ModuleSpec(name, loader, origin=location)
870    spec._set_fileattr = True
871
872    # Pick a loader if one wasn't provided.
873    if loader is None:
874        for loader_class, suffixes in _get_supported_file_loaders():
875            if location.endswith(tuple(suffixes)):
876                loader = loader_class(name, location)
877                spec.loader = loader
878                break
879        else:
880            return None
881
882    # Set submodule_search_paths appropriately.
883    if submodule_search_locations is _POPULATE:
884        # Check the loader.
885        if hasattr(loader, 'is_package'):
886            try:
887                is_package = loader.is_package(name)
888            except ImportError:
889                pass
890            else:
891                if is_package:
892                    spec.submodule_search_locations = []
893    else:
894        spec.submodule_search_locations = submodule_search_locations
895    if spec.submodule_search_locations == []:
896        if location:
897            dirname = _path_split(location)[0]
898            spec.submodule_search_locations.append(dirname)
899
900    return spec
901
902
903def _bless_my_loader(module_globals):
904    """Helper function for _warnings.c
905
906    See GH#97850 for details.
907    """
908    # 2022-10-06(warsaw): For now, this helper is only used in _warnings.c and
909    # that use case only has the module globals.  This function could be
910    # extended to accept either that or a module object.  However, in the
911    # latter case, it would be better to raise certain exceptions when looking
912    # at a module, which should have either a __loader__ or __spec__.loader.
913    # For backward compatibility, it is possible that we'll get an empty
914    # dictionary for the module globals, and that cannot raise an exception.
915    if not isinstance(module_globals, dict):
916        return None
917
918    missing = object()
919    loader = module_globals.get('__loader__', None)
920    spec = module_globals.get('__spec__', missing)
921
922    if loader is None:
923        if spec is missing:
924            # If working with a module:
925            # raise AttributeError('Module globals is missing a __spec__')
926            return None
927        elif spec is None:
928            raise ValueError('Module globals is missing a __spec__.loader')
929
930    spec_loader = getattr(spec, 'loader', missing)
931
932    if spec_loader in (missing, None):
933        if loader is None:
934            exc = AttributeError if spec_loader is missing else ValueError
935            raise exc('Module globals is missing a __spec__.loader')
936        _warnings.warn(
937            'Module globals is missing a __spec__.loader',
938            DeprecationWarning)
939        spec_loader = loader
940
941    assert spec_loader is not None
942    if loader is not None and loader != spec_loader:
943        _warnings.warn(
944            'Module globals; __loader__ != __spec__.loader',
945            DeprecationWarning)
946        return loader
947
948    return spec_loader
949
950
951# Loaders #####################################################################
952
953class WindowsRegistryFinder:
954
955    """Meta path finder for modules declared in the Windows registry."""
956
957    REGISTRY_KEY = (
958        'Software\\Python\\PythonCore\\{sys_version}'
959        '\\Modules\\{fullname}')
960    REGISTRY_KEY_DEBUG = (
961        'Software\\Python\\PythonCore\\{sys_version}'
962        '\\Modules\\{fullname}\\Debug')
963    DEBUG_BUILD = (_MS_WINDOWS and '_d.pyd' in EXTENSION_SUFFIXES)
964
965    @staticmethod
966    def _open_registry(key):
967        try:
968            return winreg.OpenKey(winreg.HKEY_CURRENT_USER, key)
969        except OSError:
970            return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key)
971
972    @classmethod
973    def _search_registry(cls, fullname):
974        if cls.DEBUG_BUILD:
975            registry_key = cls.REGISTRY_KEY_DEBUG
976        else:
977            registry_key = cls.REGISTRY_KEY
978        key = registry_key.format(fullname=fullname,
979                                  sys_version='%d.%d' % sys.version_info[:2])
980        try:
981            with cls._open_registry(key) as hkey:
982                filepath = winreg.QueryValue(hkey, '')
983        except OSError:
984            return None
985        return filepath
986
987    @classmethod
988    def find_spec(cls, fullname, path=None, target=None):
989        filepath = cls._search_registry(fullname)
990        if filepath is None:
991            return None
992        try:
993            _path_stat(filepath)
994        except OSError:
995            return None
996        for loader, suffixes in _get_supported_file_loaders():
997            if filepath.endswith(tuple(suffixes)):
998                spec = _bootstrap.spec_from_loader(fullname,
999                                                   loader(fullname, filepath),
1000                                                   origin=filepath)
1001                return spec
1002
1003
1004class _LoaderBasics:
1005
1006    """Base class of common code needed by both SourceLoader and
1007    SourcelessFileLoader."""
1008
1009    def is_package(self, fullname):
1010        """Concrete implementation of InspectLoader.is_package by checking if
1011        the path returned by get_filename has a filename of '__init__.py'."""
1012        filename = _path_split(self.get_filename(fullname))[1]
1013        filename_base = filename.rsplit('.', 1)[0]
1014        tail_name = fullname.rpartition('.')[2]
1015        return filename_base == '__init__' and tail_name != '__init__'
1016
1017    def create_module(self, spec):
1018        """Use default semantics for module creation."""
1019
1020    def exec_module(self, module):
1021        """Execute the module."""
1022        code = self.get_code(module.__name__)
1023        if code is None:
1024            raise ImportError(f'cannot load module {module.__name__!r} when '
1025                              'get_code() returns None')
1026        _bootstrap._call_with_frames_removed(exec, code, module.__dict__)
1027
1028    def load_module(self, fullname):
1029        """This method is deprecated."""
1030        # Warning implemented in _load_module_shim().
1031        return _bootstrap._load_module_shim(self, fullname)
1032
1033
1034class SourceLoader(_LoaderBasics):
1035
1036    def path_mtime(self, path):
1037        """Optional method that returns the modification time (an int) for the
1038        specified path (a str).
1039
1040        Raises OSError when the path cannot be handled.
1041        """
1042        raise OSError
1043
1044    def path_stats(self, path):
1045        """Optional method returning a metadata dict for the specified
1046        path (a str).
1047
1048        Possible keys:
1049        - 'mtime' (mandatory) is the numeric timestamp of last source
1050          code modification;
1051        - 'size' (optional) is the size in bytes of the source code.
1052
1053        Implementing this method allows the loader to read bytecode files.
1054        Raises OSError when the path cannot be handled.
1055        """
1056        return {'mtime': self.path_mtime(path)}
1057
1058    def _cache_bytecode(self, source_path, cache_path, data):
1059        """Optional method which writes data (bytes) to a file path (a str).
1060
1061        Implementing this method allows for the writing of bytecode files.
1062
1063        The source path is needed in order to correctly transfer permissions
1064        """
1065        # For backwards compatibility, we delegate to set_data()
1066        return self.set_data(cache_path, data)
1067
1068    def set_data(self, path, data):
1069        """Optional method which writes data (bytes) to a file path (a str).
1070
1071        Implementing this method allows for the writing of bytecode files.
1072        """
1073
1074
1075    def get_source(self, fullname):
1076        """Concrete implementation of InspectLoader.get_source."""
1077        path = self.get_filename(fullname)
1078        try:
1079            source_bytes = self.get_data(path)
1080        except OSError as exc:
1081            raise ImportError('source not available through get_data()',
1082                              name=fullname) from exc
1083        return decode_source(source_bytes)
1084
1085    def source_to_code(self, data, path, *, _optimize=-1):
1086        """Return the code object compiled from source.
1087
1088        The 'data' argument can be any object type that compile() supports.
1089        """
1090        return _bootstrap._call_with_frames_removed(compile, data, path, 'exec',
1091                                        dont_inherit=True, optimize=_optimize)
1092
1093    def get_code(self, fullname):
1094        """Concrete implementation of InspectLoader.get_code.
1095
1096        Reading of bytecode requires path_stats to be implemented. To write
1097        bytecode, set_data must also be implemented.
1098
1099        """
1100        source_path = self.get_filename(fullname)
1101        source_mtime = None
1102        source_bytes = None
1103        source_hash = None
1104        hash_based = False
1105        check_source = True
1106        try:
1107            bytecode_path = cache_from_source(source_path)
1108        except NotImplementedError:
1109            bytecode_path = None
1110        else:
1111            try:
1112                st = self.path_stats(source_path)
1113            except OSError:
1114                pass
1115            else:
1116                source_mtime = int(st['mtime'])
1117                try:
1118                    data = self.get_data(bytecode_path)
1119                except OSError:
1120                    pass
1121                else:
1122                    exc_details = {
1123                        'name': fullname,
1124                        'path': bytecode_path,
1125                    }
1126                    try:
1127                        flags = _classify_pyc(data, fullname, exc_details)
1128                        bytes_data = memoryview(data)[16:]
1129                        hash_based = flags & 0b1 != 0
1130                        if hash_based:
1131                            check_source = flags & 0b10 != 0
1132                            if (_imp.check_hash_based_pycs != 'never' and
1133                                (check_source or
1134                                 _imp.check_hash_based_pycs == 'always')):
1135                                source_bytes = self.get_data(source_path)
1136                                source_hash = _imp.source_hash(
1137                                    _RAW_MAGIC_NUMBER,
1138                                    source_bytes,
1139                                )
1140                                _validate_hash_pyc(data, source_hash, fullname,
1141                                                   exc_details)
1142                        else:
1143                            _validate_timestamp_pyc(
1144                                data,
1145                                source_mtime,
1146                                st['size'],
1147                                fullname,
1148                                exc_details,
1149                            )
1150                    except (ImportError, EOFError):
1151                        pass
1152                    else:
1153                        _bootstrap._verbose_message('{} matches {}', bytecode_path,
1154                                                    source_path)
1155                        return _compile_bytecode(bytes_data, name=fullname,
1156                                                 bytecode_path=bytecode_path,
1157                                                 source_path=source_path)
1158        if source_bytes is None:
1159            source_bytes = self.get_data(source_path)
1160        code_object = self.source_to_code(source_bytes, source_path)
1161        _bootstrap._verbose_message('code object from {}', source_path)
1162        if (not sys.dont_write_bytecode and bytecode_path is not None and
1163                source_mtime is not None):
1164            if hash_based:
1165                if source_hash is None:
1166                    source_hash = _imp.source_hash(_RAW_MAGIC_NUMBER,
1167                                                   source_bytes)
1168                data = _code_to_hash_pyc(code_object, source_hash, check_source)
1169            else:
1170                data = _code_to_timestamp_pyc(code_object, source_mtime,
1171                                              len(source_bytes))
1172            try:
1173                self._cache_bytecode(source_path, bytecode_path, data)
1174            except NotImplementedError:
1175                pass
1176        return code_object
1177
1178
1179class FileLoader:
1180
1181    """Base file loader class which implements the loader protocol methods that
1182    require file system usage."""
1183
1184    def __init__(self, fullname, path):
1185        """Cache the module name and the path to the file found by the
1186        finder."""
1187        self.name = fullname
1188        self.path = path
1189
1190    def __eq__(self, other):
1191        return (self.__class__ == other.__class__ and
1192                self.__dict__ == other.__dict__)
1193
1194    def __hash__(self):
1195        return hash(self.name) ^ hash(self.path)
1196
1197    @_check_name
1198    def load_module(self, fullname):
1199        """Load a module from a file.
1200
1201        This method is deprecated.  Use exec_module() instead.
1202
1203        """
1204        # The only reason for this method is for the name check.
1205        # Issue #14857: Avoid the zero-argument form of super so the implementation
1206        # of that form can be updated without breaking the frozen module.
1207        return super(FileLoader, self).load_module(fullname)
1208
1209    @_check_name
1210    def get_filename(self, fullname):
1211        """Return the path to the source file as found by the finder."""
1212        return self.path
1213
1214    def get_data(self, path):
1215        """Return the data from path as raw bytes."""
1216        if isinstance(self, (SourceLoader, ExtensionFileLoader)):
1217            with _io.open_code(str(path)) as file:
1218                return file.read()
1219        else:
1220            with _io.FileIO(path, 'r') as file:
1221                return file.read()
1222
1223    @_check_name
1224    def get_resource_reader(self, module):
1225        from importlib.readers import FileReader
1226        return FileReader(self)
1227
1228
1229class SourceFileLoader(FileLoader, SourceLoader):
1230
1231    """Concrete implementation of SourceLoader using the file system."""
1232
1233    def path_stats(self, path):
1234        """Return the metadata for the path."""
1235        st = _path_stat(path)
1236        return {'mtime': st.st_mtime, 'size': st.st_size}
1237
1238    def _cache_bytecode(self, source_path, bytecode_path, data):
1239        # Adapt between the two APIs
1240        mode = _calc_mode(source_path)
1241        return self.set_data(bytecode_path, data, _mode=mode)
1242
1243    def set_data(self, path, data, *, _mode=0o666):
1244        """Write bytes data to a file."""
1245        parent, filename = _path_split(path)
1246        path_parts = []
1247        # Figure out what directories are missing.
1248        while parent and not _path_isdir(parent):
1249            parent, part = _path_split(parent)
1250            path_parts.append(part)
1251        # Create needed directories.
1252        for part in reversed(path_parts):
1253            parent = _path_join(parent, part)
1254            try:
1255                _os.mkdir(parent)
1256            except FileExistsError:
1257                # Probably another Python process already created the dir.
1258                continue
1259            except OSError as exc:
1260                # Could be a permission error, read-only filesystem: just forget
1261                # about writing the data.
1262                _bootstrap._verbose_message('could not create {!r}: {!r}',
1263                                            parent, exc)
1264                return
1265        try:
1266            _write_atomic(path, data, _mode)
1267            _bootstrap._verbose_message('created {!r}', path)
1268        except OSError as exc:
1269            # Same as above: just don't write the bytecode.
1270            _bootstrap._verbose_message('could not create {!r}: {!r}', path,
1271                                        exc)
1272
1273
1274class SourcelessFileLoader(FileLoader, _LoaderBasics):
1275
1276    """Loader which handles sourceless file imports."""
1277
1278    def get_code(self, fullname):
1279        path = self.get_filename(fullname)
1280        data = self.get_data(path)
1281        # Call _classify_pyc to do basic validation of the pyc but ignore the
1282        # result. There's no source to check against.
1283        exc_details = {
1284            'name': fullname,
1285            'path': path,
1286        }
1287        _classify_pyc(data, fullname, exc_details)
1288        return _compile_bytecode(
1289            memoryview(data)[16:],
1290            name=fullname,
1291            bytecode_path=path,
1292        )
1293
1294    def get_source(self, fullname):
1295        """Return None as there is no source code."""
1296        return None
1297
1298
1299class ExtensionFileLoader(FileLoader, _LoaderBasics):
1300
1301    """Loader for extension modules.
1302
1303    The constructor is designed to work with FileFinder.
1304
1305    """
1306
1307    def __init__(self, name, path):
1308        self.name = name
1309        self.path = path
1310
1311    def __eq__(self, other):
1312        return (self.__class__ == other.__class__ and
1313                self.__dict__ == other.__dict__)
1314
1315    def __hash__(self):
1316        return hash(self.name) ^ hash(self.path)
1317
1318    def create_module(self, spec):
1319        """Create an uninitialized extension module"""
1320        module = _bootstrap._call_with_frames_removed(
1321            _imp.create_dynamic, spec)
1322        _bootstrap._verbose_message('extension module {!r} loaded from {!r}',
1323                         spec.name, self.path)
1324        return module
1325
1326    def exec_module(self, module):
1327        """Initialize an extension module"""
1328        _bootstrap._call_with_frames_removed(_imp.exec_dynamic, module)
1329        _bootstrap._verbose_message('extension module {!r} executed from {!r}',
1330                         self.name, self.path)
1331
1332    def is_package(self, fullname):
1333        """Return True if the extension module is a package."""
1334        file_name = _path_split(self.path)[1]
1335        return any(file_name == '__init__' + suffix
1336                   for suffix in EXTENSION_SUFFIXES)
1337
1338    def get_code(self, fullname):
1339        """Return None as an extension module cannot create a code object."""
1340        return None
1341
1342    def get_source(self, fullname):
1343        """Return None as extension modules have no source code."""
1344        return None
1345
1346    @_check_name
1347    def get_filename(self, fullname):
1348        """Return the path to the source file as found by the finder."""
1349        return self.path
1350
1351
1352class _NamespacePath:
1353    """Represents a namespace package's path.  It uses the module name
1354    to find its parent module, and from there it looks up the parent's
1355    __path__.  When this changes, the module's own path is recomputed,
1356    using path_finder.  For top-level modules, the parent module's path
1357    is sys.path."""
1358
1359    # When invalidate_caches() is called, this epoch is incremented
1360    # https://bugs.python.org/issue45703
1361    _epoch = 0
1362
1363    def __init__(self, name, path, path_finder):
1364        self._name = name
1365        self._path = path
1366        self._last_parent_path = tuple(self._get_parent_path())
1367        self._last_epoch = self._epoch
1368        self._path_finder = path_finder
1369
1370    def _find_parent_path_names(self):
1371        """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
1372        parent, dot, me = self._name.rpartition('.')
1373        if dot == '':
1374            # This is a top-level module. sys.path contains the parent path.
1375            return 'sys', 'path'
1376        # Not a top-level module. parent-module.__path__ contains the
1377        #  parent path.
1378        return parent, '__path__'
1379
1380    def _get_parent_path(self):
1381        parent_module_name, path_attr_name = self._find_parent_path_names()
1382        return getattr(sys.modules[parent_module_name], path_attr_name)
1383
1384    def _recalculate(self):
1385        # If the parent's path has changed, recalculate _path
1386        parent_path = tuple(self._get_parent_path()) # Make a copy
1387        if parent_path != self._last_parent_path or self._epoch != self._last_epoch:
1388            spec = self._path_finder(self._name, parent_path)
1389            # Note that no changes are made if a loader is returned, but we
1390            #  do remember the new parent path
1391            if spec is not None and spec.loader is None:
1392                if spec.submodule_search_locations:
1393                    self._path = spec.submodule_search_locations
1394            self._last_parent_path = parent_path     # Save the copy
1395            self._last_epoch = self._epoch
1396        return self._path
1397
1398    def __iter__(self):
1399        return iter(self._recalculate())
1400
1401    def __getitem__(self, index):
1402        return self._recalculate()[index]
1403
1404    def __setitem__(self, index, path):
1405        self._path[index] = path
1406
1407    def __len__(self):
1408        return len(self._recalculate())
1409
1410    def __repr__(self):
1411        return f'_NamespacePath({self._path!r})'
1412
1413    def __contains__(self, item):
1414        return item in self._recalculate()
1415
1416    def append(self, item):
1417        self._path.append(item)
1418
1419
1420# This class is actually exposed publicly in a namespace package's __loader__
1421# attribute, so it should be available through a non-private name.
1422# https://github.com/python/cpython/issues/92054
1423class NamespaceLoader:
1424    def __init__(self, name, path, path_finder):
1425        self._path = _NamespacePath(name, path, path_finder)
1426
1427    def is_package(self, fullname):
1428        return True
1429
1430    def get_source(self, fullname):
1431        return ''
1432
1433    def get_code(self, fullname):
1434        return compile('', '<string>', 'exec', dont_inherit=True)
1435
1436    def create_module(self, spec):
1437        """Use default semantics for module creation."""
1438
1439    def exec_module(self, module):
1440        pass
1441
1442    def load_module(self, fullname):
1443        """Load a namespace module.
1444
1445        This method is deprecated.  Use exec_module() instead.
1446
1447        """
1448        # The import system never calls this method.
1449        _bootstrap._verbose_message('namespace module loaded with path {!r}',
1450                                    self._path)
1451        # Warning implemented in _load_module_shim().
1452        return _bootstrap._load_module_shim(self, fullname)
1453
1454    def get_resource_reader(self, module):
1455        from importlib.readers import NamespaceReader
1456        return NamespaceReader(self._path)
1457
1458
1459# We use this exclusively in module_from_spec() for backward-compatibility.
1460_NamespaceLoader = NamespaceLoader
1461
1462
1463# Finders #####################################################################
1464
1465class PathFinder:
1466
1467    """Meta path finder for sys.path and package __path__ attributes."""
1468
1469    @staticmethod
1470    def invalidate_caches():
1471        """Call the invalidate_caches() method on all path entry finders
1472        stored in sys.path_importer_cache (where implemented)."""
1473        for name, finder in list(sys.path_importer_cache.items()):
1474            # Drop entry if finder name is a relative path. The current
1475            # working directory may have changed.
1476            if finder is None or not _path_isabs(name):
1477                del sys.path_importer_cache[name]
1478            elif hasattr(finder, 'invalidate_caches'):
1479                finder.invalidate_caches()
1480        # Also invalidate the caches of _NamespacePaths
1481        # https://bugs.python.org/issue45703
1482        _NamespacePath._epoch += 1
1483
1484        from importlib.metadata import MetadataPathFinder
1485        MetadataPathFinder.invalidate_caches()
1486
1487    @staticmethod
1488    def _path_hooks(path):
1489        """Search sys.path_hooks for a finder for 'path'."""
1490        if sys.path_hooks is not None and not sys.path_hooks:
1491            _warnings.warn('sys.path_hooks is empty', ImportWarning)
1492        for hook in sys.path_hooks:
1493            try:
1494                return hook(path)
1495            except ImportError:
1496                continue
1497        else:
1498            return None
1499
1500    @classmethod
1501    def _path_importer_cache(cls, path):
1502        """Get the finder for the path entry from sys.path_importer_cache.
1503
1504        If the path entry is not in the cache, find the appropriate finder
1505        and cache it. If no finder is available, store None.
1506
1507        """
1508        if path == '':
1509            try:
1510                path = _os.getcwd()
1511            except FileNotFoundError:
1512                # Don't cache the failure as the cwd can easily change to
1513                # a valid directory later on.
1514                return None
1515        try:
1516            finder = sys.path_importer_cache[path]
1517        except KeyError:
1518            finder = cls._path_hooks(path)
1519            sys.path_importer_cache[path] = finder
1520        return finder
1521
1522    @classmethod
1523    def _get_spec(cls, fullname, path, target=None):
1524        """Find the loader or namespace_path for this module/package name."""
1525        # If this ends up being a namespace package, namespace_path is
1526        #  the list of paths that will become its __path__
1527        namespace_path = []
1528        for entry in path:
1529            if not isinstance(entry, str):
1530                continue
1531            finder = cls._path_importer_cache(entry)
1532            if finder is not None:
1533                spec = finder.find_spec(fullname, target)
1534                if spec is None:
1535                    continue
1536                if spec.loader is not None:
1537                    return spec
1538                portions = spec.submodule_search_locations
1539                if portions is None:
1540                    raise ImportError('spec missing loader')
1541                # This is possibly part of a namespace package.
1542                #  Remember these path entries (if any) for when we
1543                #  create a namespace package, and continue iterating
1544                #  on path.
1545                namespace_path.extend(portions)
1546        else:
1547            spec = _bootstrap.ModuleSpec(fullname, None)
1548            spec.submodule_search_locations = namespace_path
1549            return spec
1550
1551    @classmethod
1552    def find_spec(cls, fullname, path=None, target=None):
1553        """Try to find a spec for 'fullname' on sys.path or 'path'.
1554
1555        The search is based on sys.path_hooks and sys.path_importer_cache.
1556        """
1557        if path is None:
1558            path = sys.path
1559        spec = cls._get_spec(fullname, path, target)
1560        if spec is None:
1561            return None
1562        elif spec.loader is None:
1563            namespace_path = spec.submodule_search_locations
1564            if namespace_path:
1565                # We found at least one namespace path.  Return a spec which
1566                # can create the namespace package.
1567                spec.origin = None
1568                spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
1569                return spec
1570            else:
1571                return None
1572        else:
1573            return spec
1574
1575    @staticmethod
1576    def find_distributions(*args, **kwargs):
1577        """
1578        Find distributions.
1579
1580        Return an iterable of all Distribution instances capable of
1581        loading the metadata for packages matching ``context.name``
1582        (or all names if ``None`` indicated) along the paths in the list
1583        of directories ``context.path``.
1584        """
1585        from importlib.metadata import MetadataPathFinder
1586        return MetadataPathFinder.find_distributions(*args, **kwargs)
1587
1588
1589class FileFinder:
1590
1591    """File-based finder.
1592
1593    Interactions with the file system are cached for performance, being
1594    refreshed when the directory the finder is handling has been modified.
1595
1596    """
1597
1598    def __init__(self, path, *loader_details):
1599        """Initialize with the path to search on and a variable number of
1600        2-tuples containing the loader and the file suffixes the loader
1601        recognizes."""
1602        loaders = []
1603        for loader, suffixes in loader_details:
1604            loaders.extend((suffix, loader) for suffix in suffixes)
1605        self._loaders = loaders
1606        # Base (directory) path
1607        if not path or path == '.':
1608            self.path = _os.getcwd()
1609        else:
1610            self.path = _path_abspath(path)
1611        self._path_mtime = -1
1612        self._path_cache = set()
1613        self._relaxed_path_cache = set()
1614
1615    def invalidate_caches(self):
1616        """Invalidate the directory mtime."""
1617        self._path_mtime = -1
1618
1619    def _get_spec(self, loader_class, fullname, path, smsl, target):
1620        loader = loader_class(fullname, path)
1621        return spec_from_file_location(fullname, path, loader=loader,
1622                                       submodule_search_locations=smsl)
1623
1624    def find_spec(self, fullname, target=None):
1625        """Try to find a spec for the specified module.
1626
1627        Returns the matching spec, or None if not found.
1628        """
1629        is_namespace = False
1630        tail_module = fullname.rpartition('.')[2]
1631        try:
1632            mtime = _path_stat(self.path or _os.getcwd()).st_mtime
1633        except OSError:
1634            mtime = -1
1635        if mtime != self._path_mtime:
1636            self._fill_cache()
1637            self._path_mtime = mtime
1638        # tail_module keeps the original casing, for __file__ and friends
1639        if _relax_case():
1640            cache = self._relaxed_path_cache
1641            cache_module = tail_module.lower()
1642        else:
1643            cache = self._path_cache
1644            cache_module = tail_module
1645        # Check if the module is the name of a directory (and thus a package).
1646        if cache_module in cache:
1647            base_path = _path_join(self.path, tail_module)
1648            for suffix, loader_class in self._loaders:
1649                init_filename = '__init__' + suffix
1650                full_path = _path_join(base_path, init_filename)
1651                if _path_isfile(full_path):
1652                    return self._get_spec(loader_class, fullname, full_path, [base_path], target)
1653            else:
1654                # If a namespace package, return the path if we don't
1655                #  find a module in the next section.
1656                is_namespace = _path_isdir(base_path)
1657        # Check for a file w/ a proper suffix exists.
1658        for suffix, loader_class in self._loaders:
1659            try:
1660                full_path = _path_join(self.path, tail_module + suffix)
1661            except ValueError:
1662                return None
1663            _bootstrap._verbose_message('trying {}', full_path, verbosity=2)
1664            if cache_module + suffix in cache:
1665                if _path_isfile(full_path):
1666                    return self._get_spec(loader_class, fullname, full_path,
1667                                          None, target)
1668        if is_namespace:
1669            _bootstrap._verbose_message('possible namespace for {}', base_path)
1670            spec = _bootstrap.ModuleSpec(fullname, None)
1671            spec.submodule_search_locations = [base_path]
1672            return spec
1673        return None
1674
1675    def _fill_cache(self):
1676        """Fill the cache of potential modules and packages for this directory."""
1677        path = self.path
1678        try:
1679            contents = _os.listdir(path or _os.getcwd())
1680        except (FileNotFoundError, PermissionError, NotADirectoryError):
1681            # Directory has either been removed, turned into a file, or made
1682            # unreadable.
1683            contents = []
1684        # We store two cached versions, to handle runtime changes of the
1685        # PYTHONCASEOK environment variable.
1686        if not sys.platform.startswith('win'):
1687            self._path_cache = set(contents)
1688        else:
1689            # Windows users can import modules with case-insensitive file
1690            # suffixes (for legacy reasons). Make the suffix lowercase here
1691            # so it's done once instead of for every import. This is safe as
1692            # the specified suffixes to check against are always specified in a
1693            # case-sensitive manner.
1694            lower_suffix_contents = set()
1695            for item in contents:
1696                name, dot, suffix = item.partition('.')
1697                if dot:
1698                    new_name = f'{name}.{suffix.lower()}'
1699                else:
1700                    new_name = name
1701                lower_suffix_contents.add(new_name)
1702            self._path_cache = lower_suffix_contents
1703        if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
1704            self._relaxed_path_cache = {fn.lower() for fn in contents}
1705
1706    @classmethod
1707    def path_hook(cls, *loader_details):
1708        """A class method which returns a closure to use on sys.path_hook
1709        which will return an instance using the specified loaders and the path
1710        called on the closure.
1711
1712        If the path called on the closure is not a directory, ImportError is
1713        raised.
1714
1715        """
1716        def path_hook_for_FileFinder(path):
1717            """Path hook for importlib.machinery.FileFinder."""
1718            if not _path_isdir(path):
1719                raise ImportError('only directories are supported', path=path)
1720            return cls(path, *loader_details)
1721
1722        return path_hook_for_FileFinder
1723
1724    def __repr__(self):
1725        return f'FileFinder({self.path!r})'
1726
1727
1728class AppleFrameworkLoader(ExtensionFileLoader):
1729    """A loader for modules that have been packaged as frameworks for
1730    compatibility with Apple's iOS App Store policies.
1731    """
1732    def create_module(self, spec):
1733        # If the ModuleSpec has been created by the FileFinder, it will have
1734        # been created with an origin pointing to the .fwork file. We need to
1735        # redirect this to the location in the Frameworks folder, using the
1736        # content of the .fwork file.
1737        if spec.origin.endswith(".fwork"):
1738            with _io.FileIO(spec.origin, 'r') as file:
1739                framework_binary = file.read().decode().strip()
1740            bundle_path = _path_split(sys.executable)[0]
1741            spec.origin = _path_join(bundle_path, framework_binary)
1742
1743        # If the loader is created based on the spec for a loaded module, the
1744        # path will be pointing at the Framework location. If this occurs,
1745        # get the original .fwork location to use as the module's __file__.
1746        if self.path.endswith(".fwork"):
1747            path = self.path
1748        else:
1749            with _io.FileIO(self.path + ".origin", 'r') as file:
1750                origin = file.read().decode().strip()
1751                bundle_path = _path_split(sys.executable)[0]
1752                path = _path_join(bundle_path, origin)
1753
1754        module = _bootstrap._call_with_frames_removed(_imp.create_dynamic, spec)
1755
1756        _bootstrap._verbose_message(
1757            "Apple framework extension module {!r} loaded from {!r} (path {!r})",
1758            spec.name,
1759            spec.origin,
1760            path,
1761        )
1762
1763        # Ensure that the __file__ points at the .fwork location
1764        module.__file__ = path
1765
1766        return module
1767
1768# Import setup ###############################################################
1769
1770def _fix_up_module(ns, name, pathname, cpathname=None):
1771    # This function is used by PyImport_ExecCodeModuleObject().
1772    loader = ns.get('__loader__')
1773    spec = ns.get('__spec__')
1774    if not loader:
1775        if spec:
1776            loader = spec.loader
1777        elif pathname == cpathname:
1778            loader = SourcelessFileLoader(name, pathname)
1779        else:
1780            loader = SourceFileLoader(name, pathname)
1781    if not spec:
1782        spec = spec_from_file_location(name, pathname, loader=loader)
1783        if cpathname:
1784            spec.cached = _path_abspath(cpathname)
1785    try:
1786        ns['__spec__'] = spec
1787        ns['__loader__'] = loader
1788        ns['__file__'] = pathname
1789        ns['__cached__'] = cpathname
1790    except Exception:
1791        # Not important enough to report.
1792        pass
1793
1794
1795def _get_supported_file_loaders():
1796    """Returns a list of file-based module loaders.
1797
1798    Each item is a tuple (loader, suffixes).
1799    """
1800    extension_loaders = []
1801    if hasattr(_imp, 'create_dynamic'):
1802        if sys.platform in {"ios", "tvos", "watchos"}:
1803            extension_loaders = [(AppleFrameworkLoader, [
1804                suffix.replace(".so", ".fwork")
1805                for suffix in _imp.extension_suffixes()
1806            ])]
1807        extension_loaders.append((ExtensionFileLoader, _imp.extension_suffixes()))
1808    source = SourceFileLoader, SOURCE_SUFFIXES
1809    bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
1810    return extension_loaders + [source, bytecode]
1811
1812
1813def _set_bootstrap_module(_bootstrap_module):
1814    global _bootstrap
1815    _bootstrap = _bootstrap_module
1816
1817
1818def _install(_bootstrap_module):
1819    """Install the path-based import components."""
1820    _set_bootstrap_module(_bootstrap_module)
1821    supported_loaders = _get_supported_file_loaders()
1822    sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
1823    sys.meta_path.append(PathFinder)
1824