Coverage Report

Created: 2025-08-26 06:26

/src/cpython/Python/import.c
Line
Count
Source (jump to first uncovered line)
1
/* Module definition and import implementation */
2
3
#include "Python.h"
4
#include "pycore_audit.h"         // _PySys_Audit()
5
#include "pycore_ceval.h"
6
#include "pycore_hashtable.h"     // _Py_hashtable_new_full()
7
#include "pycore_import.h"        // _PyImport_BootstrapImp()
8
#include "pycore_initconfig.h"    // _PyStatus_OK()
9
#include "pycore_interp.h"        // struct _import_runtime_state
10
#include "pycore_magic_number.h"  // PYC_MAGIC_NUMBER_TOKEN
11
#include "pycore_moduleobject.h"  // _PyModule_GetDef()
12
#include "pycore_namespace.h"     // _PyNamespace_Type
13
#include "pycore_object.h"        // _Py_SetImmortal()
14
#include "pycore_pyerrors.h"      // _PyErr_SetString()
15
#include "pycore_pyhash.h"        // _Py_KeyedHash()
16
#include "pycore_pylifecycle.h"
17
#include "pycore_pymem.h"         // _PyMem_DefaultRawFree()
18
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
19
#include "pycore_sysmodule.h"     // _PySys_ClearAttrString()
20
#include "pycore_time.h"          // _PyTime_AsMicroseconds()
21
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
22
#include "pycore_weakref.h"       // _PyWeakref_GET_REF()
23
24
#include "marshal.h"              // PyMarshal_ReadObjectFromString()
25
#include "pycore_importdl.h"      // _PyImport_DynLoadFiletab
26
#include "pydtrace.h"             // PyDTrace_IMPORT_FIND_LOAD_START_ENABLED()
27
#include <stdbool.h>              // bool
28
29
#ifdef HAVE_FCNTL_H
30
#include <fcntl.h>
31
#endif
32
33
34
/*[clinic input]
35
module _imp
36
[clinic start generated code]*/
37
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
38
39
#include "clinic/import.c.h"
40
41
42
#ifndef NDEBUG
43
static bool
44
is_interpreter_isolated(PyInterpreterState *interp)
45
{
46
    return !_Py_IsMainInterpreter(interp)
47
        && !(interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC)
48
        && interp->ceval.own_gil;
49
}
50
#endif
51
52
53
/*******************************/
54
/* process-global import state */
55
/*******************************/
56
57
/* This table is defined in config.c: */
58
extern struct _inittab _PyImport_Inittab[];
59
60
// This is not used after Py_Initialize() is called.
61
// (See _PyRuntimeState.imports.inittab.)
62
struct _inittab *PyImport_Inittab = _PyImport_Inittab;
63
// When we dynamically allocate a larger table for PyImport_ExtendInittab(),
64
// we track the pointer here so we can deallocate it during finalization.
65
static struct _inittab *inittab_copy = NULL;
66
67
68
/*******************************/
69
/* runtime-global import state */
70
/*******************************/
71
72
3.06k
#define INITTAB _PyRuntime.imports.inittab
73
447
#define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
74
974
#define EXTENSIONS _PyRuntime.imports.extensions
75
76
#define PKGCONTEXT (_PyRuntime.imports.pkgcontext)
77
78
79
/*******************************/
80
/* interpreter import state */
81
/*******************************/
82
83
#define MODULES(interp) \
84
57.1k
    (interp)->imports.modules
85
#define MODULES_BY_INDEX(interp) \
86
176
    (interp)->imports.modules_by_index
87
#define IMPORTLIB(interp) \
88
3.06k
    (interp)->imports.importlib
89
#define OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) \
90
0
    (interp)->imports.override_multi_interp_extensions_check
91
#define OVERRIDE_FROZEN_MODULES(interp) \
92
2.53k
    (interp)->imports.override_frozen_modules
93
#ifdef HAVE_DLOPEN
94
#  define DLOPENFLAGS(interp) \
95
73
        (interp)->imports.dlopenflags
96
#endif
97
#define IMPORT_FUNC(interp) \
98
11.6k
    (interp)->imports.import_func
99
100
#define IMPORT_LOCK(interp) \
101
38.4k
    (interp)->imports.lock
102
103
#define FIND_AND_LOAD(interp) \
104
2.66k
    (interp)->imports.find_and_load
105
106
#define _IMPORT_TIME_HEADER(interp)                                           \
107
0
    do {                                                                      \
108
0
        if (FIND_AND_LOAD((interp)).header) {                                 \
109
0
            fputs("import time: self [us] | cumulative | imported package\n", \
110
0
                  stderr);                                                    \
111
0
            FIND_AND_LOAD((interp)).header = 0;                               \
112
0
        }                                                                     \
113
0
    } while (0)
114
115
116
/*******************/
117
/* the import lock */
118
/*******************/
119
120
/* Locking primitives to prevent parallel imports of the same module
121
   in different threads to return with a partially loaded module.
122
   These calls are serialized by the global interpreter lock. */
123
124
void
125
_PyImport_AcquireLock(PyInterpreterState *interp)
126
12.8k
{
127
12.8k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
128
12.8k
}
129
130
void
131
_PyImport_ReleaseLock(PyInterpreterState *interp)
132
12.8k
{
133
12.8k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
134
12.8k
}
135
136
void
137
_PyImport_ReInitLock(PyInterpreterState *interp)
138
0
{
139
    // gh-126688: Thread id may change after fork() on some operating systems.
140
0
    IMPORT_LOCK(interp).thread = PyThread_get_thread_ident_ex();
141
0
}
142
143
144
/***************/
145
/* sys.modules */
146
/***************/
147
148
PyObject *
149
_PyImport_InitModules(PyInterpreterState *interp)
150
16
{
151
16
    assert(MODULES(interp) == NULL);
152
16
    MODULES(interp) = PyDict_New();
153
16
    if (MODULES(interp) == NULL) {
154
0
        return NULL;
155
0
    }
156
16
    return MODULES(interp);
157
16
}
158
159
PyObject *
160
_PyImport_GetModules(PyInterpreterState *interp)
161
16.0k
{
162
16.0k
    return MODULES(interp);
163
16.0k
}
164
165
PyObject *
166
_PyImport_GetModulesRef(PyInterpreterState *interp)
167
0
{
168
0
    _PyImport_AcquireLock(interp);
169
0
    PyObject *modules = MODULES(interp);
170
0
    if (modules == NULL) {
171
        /* The interpreter hasn't been initialized yet. */
172
0
        modules = Py_None;
173
0
    }
174
0
    Py_INCREF(modules);
175
0
    _PyImport_ReleaseLock(interp);
176
0
    return modules;
177
0
}
178
179
void
180
_PyImport_ClearModules(PyInterpreterState *interp)
181
0
{
182
0
    Py_SETREF(MODULES(interp), NULL);
183
0
}
184
185
static inline PyObject *
186
get_modules_dict(PyThreadState *tstate, bool fatal)
187
41.1k
{
188
    /* Technically, it would make sense to incref the dict,
189
     * since sys.modules could be swapped out and decref'ed to 0
190
     * before the caller is done using it.  However, that is highly
191
     * unlikely, especially since we can rely on a global lock
192
     * (i.e. the GIL) for thread-safety. */
193
41.1k
    PyObject *modules = MODULES(tstate->interp);
194
41.1k
    if (modules == NULL) {
195
0
        if (fatal) {
196
0
            Py_FatalError("interpreter has no modules dictionary");
197
0
        }
198
0
        _PyErr_SetString(tstate, PyExc_RuntimeError,
199
0
                         "unable to get sys.modules");
200
0
        return NULL;
201
0
    }
202
41.1k
    return modules;
203
41.1k
}
204
205
PyObject *
206
PyImport_GetModuleDict(void)
207
0
{
208
0
    PyThreadState *tstate = _PyThreadState_GET();
209
0
    return get_modules_dict(tstate, true);
210
0
}
211
212
int
213
_PyImport_SetModule(PyObject *name, PyObject *m)
214
0
{
215
0
    PyThreadState *tstate = _PyThreadState_GET();
216
0
    PyObject *modules = get_modules_dict(tstate, true);
217
0
    return PyObject_SetItem(modules, name, m);
218
0
}
219
220
int
221
_PyImport_SetModuleString(const char *name, PyObject *m)
222
16
{
223
16
    PyThreadState *tstate = _PyThreadState_GET();
224
16
    PyObject *modules = get_modules_dict(tstate, true);
225
16
    return PyMapping_SetItemString(modules, name, m);
226
16
}
227
228
static PyObject *
229
import_get_module(PyThreadState *tstate, PyObject *name)
230
40.6k
{
231
40.6k
    PyObject *modules = get_modules_dict(tstate, false);
232
40.6k
    if (modules == NULL) {
233
0
        return NULL;
234
0
    }
235
236
40.6k
    PyObject *m;
237
40.6k
    Py_INCREF(modules);
238
40.6k
    (void)PyMapping_GetOptionalItem(modules, name, &m);
239
40.6k
    Py_DECREF(modules);
240
40.6k
    return m;
241
40.6k
}
242
243
static int
244
import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
245
32.4k
{
246
32.4k
    PyObject *spec;
247
248
    /* Optimization: only call _bootstrap._lock_unlock_module() if
249
       __spec__._initializing is true.
250
       NOTE: because of this, initializing must be set *before*
251
       stuffing the new module in sys.modules.
252
    */
253
32.4k
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
254
32.4k
    if (rc > 0) {
255
32.4k
        rc = _PyModuleSpec_IsInitializing(spec);
256
32.4k
        Py_DECREF(spec);
257
32.4k
    }
258
32.4k
    if (rc == 0) {
259
32.2k
        goto done;
260
32.2k
    }
261
188
    else if (rc < 0) {
262
0
        return rc;
263
0
    }
264
265
    /* Wait until module is done importing. */
266
188
    PyObject *value = PyObject_CallMethodOneArg(
267
188
        IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
268
188
    if (value == NULL) {
269
0
        return -1;
270
0
    }
271
188
    Py_DECREF(value);
272
273
32.4k
done:
274
    /* When -X importtime=2, print an import time entry even if an
275
       imported module has already been loaded.
276
     */
277
32.4k
    if (_PyInterpreterState_GetConfig(interp)->import_time == 2) {
278
0
        _IMPORT_TIME_HEADER(interp);
279
0
#define import_level FIND_AND_LOAD(interp).import_level
280
0
        fprintf(stderr, "import time: cached    | cached     | %*s\n",
281
0
                import_level*2, PyUnicode_AsUTF8(name));
282
0
#undef import_level
283
0
    }
284
285
32.4k
    return 0;
286
188
}
287
288
static void remove_importlib_frames(PyThreadState *tstate);
289
290
PyObject *
291
PyImport_GetModule(PyObject *name)
292
16.0k
{
293
16.0k
    PyThreadState *tstate = _PyThreadState_GET();
294
16.0k
    PyObject *mod;
295
296
16.0k
    mod = import_get_module(tstate, name);
297
16.0k
    if (mod != NULL && mod != Py_None) {
298
16.0k
        if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
299
0
            Py_DECREF(mod);
300
0
            remove_importlib_frames(tstate);
301
0
            return NULL;
302
0
        }
303
16.0k
    }
304
16.0k
    return mod;
305
16.0k
}
306
307
/* Get the module object corresponding to a module name.
308
   First check the modules dictionary if there's one there,
309
   if not, create a new one and insert it in the modules dictionary. */
310
311
static PyObject *
312
import_add_module(PyThreadState *tstate, PyObject *name)
313
80
{
314
80
    PyObject *modules = get_modules_dict(tstate, false);
315
80
    if (modules == NULL) {
316
0
        return NULL;
317
0
    }
318
319
80
    PyObject *m;
320
80
    if (PyMapping_GetOptionalItem(modules, name, &m) < 0) {
321
0
        return NULL;
322
0
    }
323
80
    if (m != NULL && PyModule_Check(m)) {
324
48
        return m;
325
48
    }
326
32
    Py_XDECREF(m);
327
32
    m = PyModule_NewObject(name);
328
32
    if (m == NULL)
329
0
        return NULL;
330
32
    if (PyObject_SetItem(modules, name, m) != 0) {
331
0
        Py_DECREF(m);
332
0
        return NULL;
333
0
    }
334
335
32
    return m;
336
32
}
337
338
PyObject *
339
PyImport_AddModuleRef(const char *name)
340
48
{
341
48
    PyObject *name_obj = PyUnicode_FromString(name);
342
48
    if (name_obj == NULL) {
343
0
        return NULL;
344
0
    }
345
48
    PyThreadState *tstate = _PyThreadState_GET();
346
48
    PyObject *module = import_add_module(tstate, name_obj);
347
48
    Py_DECREF(name_obj);
348
48
    return module;
349
48
}
350
351
352
PyObject *
353
PyImport_AddModuleObject(PyObject *name)
354
16
{
355
16
    PyThreadState *tstate = _PyThreadState_GET();
356
16
    PyObject *mod = import_add_module(tstate, name);
357
16
    if (!mod) {
358
0
        return NULL;
359
0
    }
360
361
    // gh-86160: PyImport_AddModuleObject() returns a borrowed reference.
362
    // Create a weak reference to produce a borrowed reference, since it can
363
    // become NULL. sys.modules type can be different than dict and it is not
364
    // guaranteed that it keeps a strong reference to the module. It can be a
365
    // custom mapping with __getitem__() which returns a new object or removes
366
    // returned object, or __setitem__ which does nothing. There is so much
367
    // unknown.  With weakref we can be sure that we get either a reference to
368
    // live object or NULL.
369
    //
370
    // Use PyImport_AddModuleRef() to avoid these issues.
371
16
    PyObject *ref = PyWeakref_NewRef(mod, NULL);
372
16
    Py_DECREF(mod);
373
16
    if (ref == NULL) {
374
0
        return NULL;
375
0
    }
376
16
    mod = _PyWeakref_GET_REF(ref);
377
16
    Py_DECREF(ref);
378
16
    Py_XDECREF(mod);
379
380
16
    if (mod == NULL && !PyErr_Occurred()) {
381
0
        PyErr_SetString(PyExc_RuntimeError,
382
0
                        "sys.modules does not hold a strong reference "
383
0
                        "to the module");
384
0
    }
385
16
    return mod; /* borrowed reference */
386
16
}
387
388
389
PyObject *
390
PyImport_AddModule(const char *name)
391
0
{
392
0
    PyObject *nameobj = PyUnicode_FromString(name);
393
0
    if (nameobj == NULL) {
394
0
        return NULL;
395
0
    }
396
0
    PyObject *module = PyImport_AddModuleObject(nameobj);
397
0
    Py_DECREF(nameobj);
398
0
    return module;
399
0
}
400
401
402
/* Remove name from sys.modules, if it's there.
403
 * Can be called with an exception raised.
404
 * If fail to remove name a new exception will be chained with the old
405
 * exception, otherwise the old exception is preserved.
406
 */
407
static void
408
remove_module(PyThreadState *tstate, PyObject *name)
409
0
{
410
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
411
412
0
    PyObject *modules = get_modules_dict(tstate, true);
413
0
    if (PyDict_CheckExact(modules)) {
414
        // Error is reported to the caller
415
0
        (void)PyDict_Pop(modules, name, NULL);
416
0
    }
417
0
    else if (PyMapping_DelItem(modules, name) < 0) {
418
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
419
0
            _PyErr_Clear(tstate);
420
0
        }
421
0
    }
422
423
0
    _PyErr_ChainExceptions1(exc);
424
0
}
425
426
427
/************************************/
428
/* per-interpreter modules-by-index */
429
/************************************/
430
431
Py_ssize_t
432
_PyImport_GetNextModuleIndex(void)
433
447
{
434
447
    return _Py_atomic_add_ssize(&LAST_MODULE_INDEX, 1) + 1;
435
447
}
436
437
#ifndef NDEBUG
438
struct extensions_cache_value;
439
static struct extensions_cache_value * _find_cached_def(PyModuleDef *);
440
static Py_ssize_t _get_cached_module_index(struct extensions_cache_value *);
441
#endif
442
443
static Py_ssize_t
444
_get_module_index_from_def(PyModuleDef *def)
445
0
{
446
0
    Py_ssize_t index = def->m_base.m_index;
447
#ifndef NDEBUG
448
    struct extensions_cache_value *cached = _find_cached_def(def);
449
    assert(cached == NULL || index == _get_cached_module_index(cached));
450
#endif
451
0
    return index;
452
0
}
453
454
static void
455
_set_module_index(PyModuleDef *def, Py_ssize_t index)
456
32
{
457
32
    assert(index > 0);
458
32
    if (index == def->m_base.m_index) {
459
        /* There's nothing to do. */
460
32
    }
461
0
    else if (def->m_base.m_index == 0) {
462
        /* It should have been initialized by PyModuleDef_Init().
463
         * We assert here to catch this in dev, but keep going otherwise. */
464
0
        assert(def->m_base.m_index != 0);
465
0
        def->m_base.m_index = index;
466
0
    }
467
0
    else {
468
        /* It was already set for a different module.
469
         * We replace the old value. */
470
0
        assert(def->m_base.m_index > 0);
471
0
        def->m_base.m_index = index;
472
0
    }
473
32
}
474
475
static const char *
476
_modules_by_index_check(PyInterpreterState *interp, Py_ssize_t index)
477
0
{
478
0
    if (index <= 0) {
479
0
        return "invalid module index";
480
0
    }
481
0
    if (MODULES_BY_INDEX(interp) == NULL) {
482
0
        return "Interpreters module-list not accessible.";
483
0
    }
484
0
    if (index >= PyList_GET_SIZE(MODULES_BY_INDEX(interp))) {
485
0
        return "Module index out of bounds.";
486
0
    }
487
0
    return NULL;
488
0
}
489
490
static PyObject *
491
_modules_by_index_get(PyInterpreterState *interp, Py_ssize_t index)
492
0
{
493
0
    if (_modules_by_index_check(interp, index) != NULL) {
494
0
        return NULL;
495
0
    }
496
0
    PyObject *res = PyList_GET_ITEM(MODULES_BY_INDEX(interp), index);
497
0
    return res==Py_None ? NULL : res;
498
0
}
499
500
static int
501
_modules_by_index_set(PyInterpreterState *interp,
502
                      Py_ssize_t index, PyObject *module)
503
32
{
504
32
    assert(index > 0);
505
506
32
    if (MODULES_BY_INDEX(interp) == NULL) {
507
16
        MODULES_BY_INDEX(interp) = PyList_New(0);
508
16
        if (MODULES_BY_INDEX(interp) == NULL) {
509
0
            return -1;
510
0
        }
511
16
    }
512
513
112
    while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
514
80
        if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
515
0
            return -1;
516
0
        }
517
80
    }
518
519
32
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
520
32
}
521
522
static int
523
_modules_by_index_clear_one(PyInterpreterState *interp, Py_ssize_t index)
524
0
{
525
0
    const char *err = _modules_by_index_check(interp, index);
526
0
    if (err != NULL) {
527
0
        Py_FatalError(err);
528
0
        return -1;
529
0
    }
530
0
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(Py_None));
531
0
}
532
533
534
PyObject*
535
PyState_FindModule(PyModuleDef* module)
536
0
{
537
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
538
0
    if (module->m_slots) {
539
0
        return NULL;
540
0
    }
541
0
    Py_ssize_t index = _get_module_index_from_def(module);
542
0
    return _modules_by_index_get(interp, index);
543
0
}
544
545
/* _PyState_AddModule() has been completely removed from the C-API
546
   (and was removed from the limited API in 3.6).  However, we're
547
   playing it safe and keeping it around for any stable ABI extensions
548
   built against 3.2-3.5. */
549
int
550
_PyState_AddModule(PyThreadState *tstate, PyObject* module, PyModuleDef* def)
551
0
{
552
0
    if (!def) {
553
0
        assert(_PyErr_Occurred(tstate));
554
0
        return -1;
555
0
    }
556
0
    if (def->m_slots) {
557
0
        _PyErr_SetString(tstate,
558
0
                         PyExc_SystemError,
559
0
                         "PyState_AddModule called on module with slots");
560
0
        return -1;
561
0
    }
562
0
    assert(def->m_slots == NULL);
563
0
    Py_ssize_t index = _get_module_index_from_def(def);
564
0
    return _modules_by_index_set(tstate->interp, index, module);
565
0
}
566
567
int
568
PyState_AddModule(PyObject* module, PyModuleDef* def)
569
0
{
570
0
    if (!def) {
571
0
        Py_FatalError("module definition is NULL");
572
0
        return -1;
573
0
    }
574
575
0
    PyThreadState *tstate = _PyThreadState_GET();
576
0
    if (def->m_slots) {
577
0
        _PyErr_SetString(tstate,
578
0
                         PyExc_SystemError,
579
0
                         "PyState_AddModule called on module with slots");
580
0
        return -1;
581
0
    }
582
583
0
    PyInterpreterState *interp = tstate->interp;
584
0
    Py_ssize_t index = _get_module_index_from_def(def);
585
0
    if (MODULES_BY_INDEX(interp) &&
586
0
        index < PyList_GET_SIZE(MODULES_BY_INDEX(interp)) &&
587
0
        module == PyList_GET_ITEM(MODULES_BY_INDEX(interp), index))
588
0
    {
589
0
        _Py_FatalErrorFormat(__func__, "module %p already added", module);
590
0
        return -1;
591
0
    }
592
593
0
    assert(def->m_slots == NULL);
594
0
    return _modules_by_index_set(interp, index, module);
595
0
}
596
597
int
598
PyState_RemoveModule(PyModuleDef* def)
599
0
{
600
0
    PyThreadState *tstate = _PyThreadState_GET();
601
0
    if (def->m_slots) {
602
0
        _PyErr_SetString(tstate,
603
0
                         PyExc_SystemError,
604
0
                         "PyState_RemoveModule called on module with slots");
605
0
        return -1;
606
0
    }
607
0
    Py_ssize_t index = _get_module_index_from_def(def);
608
0
    return _modules_by_index_clear_one(tstate->interp, index);
609
0
}
610
611
612
// Used by finalize_modules()
613
void
614
_PyImport_ClearModulesByIndex(PyInterpreterState *interp)
615
0
{
616
0
    if (!MODULES_BY_INDEX(interp)) {
617
0
        return;
618
0
    }
619
620
0
    Py_ssize_t i;
621
0
    for (i = 0; i < PyList_GET_SIZE(MODULES_BY_INDEX(interp)); i++) {
622
0
        PyObject *m = PyList_GET_ITEM(MODULES_BY_INDEX(interp), i);
623
0
        if (PyModule_Check(m)) {
624
            /* cleanup the saved copy of module dicts */
625
0
            PyModuleDef *md = PyModule_GetDef(m);
626
0
            if (md) {
627
                // XXX Do this more carefully.  The dict might be owned
628
                // by another interpreter.
629
0
                Py_CLEAR(md->m_base.m_copy);
630
0
            }
631
0
        }
632
0
    }
633
634
    /* Setting modules_by_index to NULL could be dangerous, so we
635
       clear the list instead. */
636
0
    if (PyList_SetSlice(MODULES_BY_INDEX(interp),
637
0
                        0, PyList_GET_SIZE(MODULES_BY_INDEX(interp)),
638
0
                        NULL)) {
639
0
        PyErr_FormatUnraisable("Exception ignored while "
640
0
                               "clearing interpreters module list");
641
0
    }
642
0
}
643
644
645
/*********************/
646
/* extension modules */
647
/*********************/
648
649
/*
650
    It may help to have a big picture view of what happens
651
    when an extension is loaded.  This includes when it is imported
652
    for the first time.
653
654
    Here's a summary, using importlib._bootstrap._load() as a starting point.
655
656
    1.  importlib._bootstrap._load()
657
    2.    _load():  acquire import lock
658
    3.    _load() -> importlib._bootstrap._load_unlocked()
659
    4.      _load_unlocked() -> importlib._bootstrap.module_from_spec()
660
    5.        module_from_spec() -> ExtensionFileLoader.create_module()
661
    6.          create_module() -> _imp.create_dynamic()
662
                    (see below)
663
    7.        module_from_spec() -> importlib._bootstrap._init_module_attrs()
664
    8.      _load_unlocked():  sys.modules[name] = module
665
    9.      _load_unlocked() -> ExtensionFileLoader.exec_module()
666
    10.       exec_module() -> _imp.exec_dynamic()
667
                  (see below)
668
    11.   _load():  release import lock
669
670
671
    ...for single-phase init modules, where m_size == -1:
672
673
    (6). first time  (not found in _PyRuntime.imports.extensions):
674
       A. _imp_create_dynamic_impl() -> import_find_extension()
675
       B. _imp_create_dynamic_impl() -> _PyImport_GetModInitFunc()
676
       C.   _PyImport_GetModInitFunc():  load <module init func>
677
       D. _imp_create_dynamic_impl() -> import_run_extension()
678
       E.   import_run_extension() -> _PyImport_RunModInitFunc()
679
       F.     _PyImport_RunModInitFunc():  call <module init func>
680
       G.       <module init func> -> PyModule_Create() -> PyModule_Create2()
681
                                          -> PyModule_CreateInitialized()
682
       H.         PyModule_CreateInitialized() -> PyModule_New()
683
       I.         PyModule_CreateInitialized():  allocate mod->md_state
684
       J.         PyModule_CreateInitialized() -> PyModule_AddFunctions()
685
       K.         PyModule_CreateInitialized() -> PyModule_SetDocString()
686
       L.       PyModule_CreateInitialized():  set mod->md_def
687
       M.       <module init func>:  initialize the module, etc.
688
       N.   import_run_extension()
689
                -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
690
       O.   import_run_extension():  set __file__
691
       P.   import_run_extension() -> update_global_state_for_extension()
692
       Q.     update_global_state_for_extension():
693
                      copy __dict__ into def->m_base.m_copy
694
       R.     update_global_state_for_extension():
695
                      add it to _PyRuntime.imports.extensions
696
       S.   import_run_extension() -> finish_singlephase_extension()
697
       T.     finish_singlephase_extension():
698
                      add it to interp->imports.modules_by_index
699
       U.     finish_singlephase_extension():  add it to sys.modules
700
701
       Step (Q) is skipped for core modules (sys/builtins).
702
703
    (6). subsequent times  (found in _PyRuntime.imports.extensions):
704
       A. _imp_create_dynamic_impl() -> import_find_extension()
705
       B.   import_find_extension() -> reload_singlephase_extension()
706
       C.     reload_singlephase_extension()
707
                  -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
708
       D.     reload_singlephase_extension() -> import_add_module()
709
       E.       if name in sys.modules:  use that module
710
       F.       else:
711
                  1. import_add_module() -> PyModule_NewObject()
712
                  2. import_add_module():  set it on sys.modules
713
       G.     reload_singlephase_extension():  copy the "m_copy" dict into __dict__
714
       H.     reload_singlephase_extension():  add to modules_by_index
715
716
    (10). (every time):
717
       A. noop
718
719
720
    ...for single-phase init modules, where m_size >= 0:
721
722
    (6). not main interpreter and never loaded there - every time  (not found in _PyRuntime.imports.extensions):
723
       A-P. (same as for m_size == -1)
724
       Q.     _PyImport_RunModInitFunc():  set def->m_base.m_init
725
       R. (skipped)
726
       S-U. (same as for m_size == -1)
727
728
    (6). main interpreter - first time  (not found in _PyRuntime.imports.extensions):
729
       A-P. (same as for m_size == -1)
730
       Q.     _PyImport_RunModInitFunc():  set def->m_base.m_init
731
       R-U. (same as for m_size == -1)
732
733
    (6). subsequent times  (found in _PyRuntime.imports.extensions):
734
       A. _imp_create_dynamic_impl() -> import_find_extension()
735
       B.   import_find_extension() -> reload_singlephase_extension()
736
       C.     reload_singlephase_extension()
737
                  -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
738
       D.     reload_singlephase_extension():  call def->m_base.m_init  (see above)
739
       E.     reload_singlephase_extension():  add the module to sys.modules
740
       F.     reload_singlephase_extension():  add to modules_by_index
741
742
    (10). every time:
743
       A. noop
744
745
746
    ...for multi-phase init modules:
747
748
    (6). every time:
749
       A. _imp_create_dynamic_impl() -> import_find_extension()  (not found)
750
       B. _imp_create_dynamic_impl() -> _PyImport_GetModInitFunc()
751
       C.   _PyImport_GetModInitFunc():  load <module init func>
752
       D. _imp_create_dynamic_impl() -> import_run_extension()
753
       E.   import_run_extension() -> _PyImport_RunModInitFunc()
754
       F.     _PyImport_RunModInitFunc():  call <module init func>
755
       G.   import_run_extension() -> PyModule_FromDefAndSpec()
756
       H.      PyModule_FromDefAndSpec(): gather/check moduledef slots
757
       I.      if there's a Py_mod_create slot:
758
                 1. PyModule_FromDefAndSpec():  call its function
759
       J.      else:
760
                 1. PyModule_FromDefAndSpec() -> PyModule_NewObject()
761
       K:      PyModule_FromDefAndSpec():  set mod->md_def
762
       L.      PyModule_FromDefAndSpec() -> _add_methods_to_object()
763
       M.      PyModule_FromDefAndSpec() -> PyModule_SetDocString()
764
765
    (10). every time:
766
       A. _imp_exec_dynamic_impl() -> exec_builtin_or_dynamic()
767
       B.   if mod->md_state == NULL (including if m_size == 0):
768
            1. exec_builtin_or_dynamic() -> PyModule_ExecDef()
769
            2.   PyModule_ExecDef():  allocate mod->md_state
770
            3.   if there's a Py_mod_exec slot:
771
                 1. PyModule_ExecDef():  call its function
772
 */
773
774
775
/* Make sure name is fully qualified.
776
777
   This is a bit of a hack: when the shared library is loaded,
778
   the module name is "package.module", but the module calls
779
   PyModule_Create*() with just "module" for the name.  The shared
780
   library loader squirrels away the true name of the module in
781
   _PyRuntime.imports.pkgcontext, and PyModule_Create*() will
782
   substitute this (if the name actually matches).
783
*/
784
785
#ifdef HAVE_THREAD_LOCAL
786
_Py_thread_local const char *pkgcontext = NULL;
787
# undef PKGCONTEXT
788
1.59k
# define PKGCONTEXT pkgcontext
789
#endif
790
791
const char *
792
_PyImport_ResolveNameWithPackageContext(const char *name)
793
64
{
794
#ifndef HAVE_THREAD_LOCAL
795
    PyMutex_Lock(&EXTENSIONS.mutex);
796
#endif
797
64
    if (PKGCONTEXT != NULL) {
798
0
        const char *p = strrchr(PKGCONTEXT, '.');
799
0
        if (p != NULL && strcmp(name, p+1) == 0) {
800
0
            name = PKGCONTEXT;
801
0
            PKGCONTEXT = NULL;
802
0
        }
803
0
    }
804
#ifndef HAVE_THREAD_LOCAL
805
    PyMutex_Unlock(&EXTENSIONS.mutex);
806
#endif
807
64
    return name;
808
64
}
809
810
const char *
811
_PyImport_SwapPackageContext(const char *newcontext)
812
766
{
813
#ifndef HAVE_THREAD_LOCAL
814
    PyMutex_Lock(&EXTENSIONS.mutex);
815
#endif
816
766
    const char *oldcontext = PKGCONTEXT;
817
766
    PKGCONTEXT = newcontext;
818
#ifndef HAVE_THREAD_LOCAL
819
    PyMutex_Unlock(&EXTENSIONS.mutex);
820
#endif
821
766
    return oldcontext;
822
766
}
823
824
#ifdef HAVE_DLOPEN
825
int
826
_PyImport_GetDLOpenFlags(PyInterpreterState *interp)
827
73
{
828
73
    return DLOPENFLAGS(interp);
829
73
}
830
831
void
832
_PyImport_SetDLOpenFlags(PyInterpreterState *interp, int new_val)
833
0
{
834
0
    DLOPENFLAGS(interp) = new_val;
835
0
}
836
#endif  // HAVE_DLOPEN
837
838
839
/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
840
static int
841
383
exec_builtin_or_dynamic(PyObject *mod) {
842
383
    PyModuleDef *def;
843
383
    void *state;
844
845
383
    if (!PyModule_Check(mod)) {
846
0
        return 0;
847
0
    }
848
849
383
    def = PyModule_GetDef(mod);
850
383
    if (def == NULL) {
851
0
        return 0;
852
0
    }
853
854
383
    state = PyModule_GetState(mod);
855
383
    if (state) {
856
        /* Already initialized; skip reload */
857
0
        return 0;
858
0
    }
859
860
383
    return PyModule_ExecDef(mod, def);
861
383
}
862
863
864
static int clear_singlephase_extension(PyInterpreterState *interp,
865
                                       PyObject *name, PyObject *filename);
866
867
// Currently, this is only used for testing.
868
// (See _testinternalcapi.clear_extension().)
869
// If adding another use, be careful about modules that import themselves
870
// recursively (see gh-123880).
871
int
872
_PyImport_ClearExtension(PyObject *name, PyObject *filename)
873
0
{
874
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
875
876
    /* Clearing a module's C globals is up to the module. */
877
0
    if (clear_singlephase_extension(interp, name, filename) < 0) {
878
0
        return -1;
879
0
    }
880
881
    // In the future we'll probably also make sure the extension's
882
    // file handle (and DL handle) is closed (requires saving it).
883
884
0
    return 0;
885
0
}
886
887
888
/*****************************/
889
/* single-phase init modules */
890
/*****************************/
891
892
/*
893
We support a number of kinds of single-phase init builtin/extension modules:
894
895
* "basic"
896
    * no module state (PyModuleDef.m_size == -1)
897
    * does not support repeated init (we use PyModuleDef.m_base.m_copy)
898
    * may have process-global state
899
    * the module's def is cached in _PyRuntime.imports.extensions,
900
      by (name, filename)
901
* "reinit"
902
    * no module state (PyModuleDef.m_size == 0)
903
    * supports repeated init (m_copy is never used)
904
    * should not have any process-global state
905
    * its def is never cached in _PyRuntime.imports.extensions
906
      (except, currently, under the main interpreter, for some reason)
907
* "with state"  (almost the same as reinit)
908
    * has module state (PyModuleDef.m_size > 0)
909
    * supports repeated init (m_copy is never used)
910
    * should not have any process-global state
911
    * its def is never cached in _PyRuntime.imports.extensions
912
      (except, currently, under the main interpreter, for some reason)
913
914
There are also variants within those classes:
915
916
* two or more modules share a PyModuleDef
917
    * a module's init func uses another module's PyModuleDef
918
    * a module's init func calls another's module's init func
919
    * a module's init "func" is actually a variable statically initialized
920
      to another module's init func
921
* two or modules share "methods"
922
    * a module's init func copies another module's PyModuleDef
923
      (with a different name)
924
* (basic-only) two or modules share process-global state
925
926
In the first case, where modules share a PyModuleDef, the following
927
notable weirdness happens:
928
929
* the module's __name__ matches the def, not the requested name
930
* the last module (with the same def) to be imported for the first time wins
931
    * returned by PyState_Find_Module() (via interp->modules_by_index)
932
    * (non-basic-only) its init func is used when re-loading any of them
933
      (via the def's m_init)
934
    * (basic-only) the copy of its __dict__ is used when re-loading any of them
935
      (via the def's m_copy)
936
937
However, the following happens as expected:
938
939
* a new module object (with its own __dict__) is created for each request
940
* the module's __spec__ has the requested name
941
* the loaded module is cached in sys.modules under the requested name
942
* the m_index field of the shared def is not changed,
943
  so at least PyState_FindModule() will always look in the same place
944
945
For "basic" modules there are other quirks:
946
947
* (whether sharing a def or not) when loaded the first time,
948
  m_copy is set before _init_module_attrs() is called
949
  in importlib._bootstrap.module_from_spec(),
950
  so when the module is re-loaded, the previous value
951
  for __wpec__ (and others) is reset, possibly unexpectedly.
952
953
Generally, when multiple interpreters are involved, some of the above
954
gets even messier.
955
*/
956
957
static inline void
958
extensions_lock_acquire(void)
959
447
{
960
447
    PyMutex_Lock(&_PyRuntime.imports.extensions.mutex);
961
447
}
962
963
static inline void
964
extensions_lock_release(void)
965
447
{
966
447
    PyMutex_Unlock(&_PyRuntime.imports.extensions.mutex);
967
447
}
968
969
970
/* Magic for extension modules (built-in as well as dynamically
971
   loaded).  To prevent initializing an extension module more than
972
   once, we keep a static dictionary 'extensions' keyed by the tuple
973
   (module name, module name)  (for built-in modules) or by
974
   (filename, module name) (for dynamically loaded modules), containing these
975
   modules.  A copy of the module's dictionary is stored by calling
976
   fix_up_extension() immediately after the module initialization
977
   function succeeds.  A copy can be retrieved from there by calling
978
   import_find_extension().
979
980
   Modules which do support multiple initialization set their m_size
981
   field to a non-negative number (indicating the size of the
982
   module-specific state). They are still recorded in the extensions
983
   dictionary, to avoid loading shared libraries twice.
984
*/
985
986
typedef struct cached_m_dict {
987
    /* A shallow copy of the original module's __dict__. */
988
    PyObject *copied;
989
    /* The interpreter that owns the copy. */
990
    int64_t interpid;
991
} *cached_m_dict_t;
992
993
struct extensions_cache_value {
994
    PyModuleDef *def;
995
996
    /* The function used to re-initialize the module.
997
       This is only set for legacy (single-phase init) extension modules
998
       and only used for those that support multiple initializations
999
       (m_size >= 0).
1000
       It is set by update_global_state_for_extension(). */
1001
    PyModInitFunction m_init;
1002
1003
    /* The module's index into its interpreter's modules_by_index cache.
1004
       This is set for all extension modules but only used for legacy ones.
1005
       (See PyInterpreterState.modules_by_index for more info.) */
1006
    Py_ssize_t m_index;
1007
1008
    /* A copy of the module's __dict__ after the first time it was loaded.
1009
       This is only set/used for legacy modules that do not support
1010
       multiple initializations.
1011
       It is set exclusively by fixup_cached_def(). */
1012
    cached_m_dict_t m_dict;
1013
    struct cached_m_dict _m_dict;
1014
1015
    _Py_ext_module_origin origin;
1016
1017
#ifdef Py_GIL_DISABLED
1018
    /* The module's md_gil slot, for legacy modules that are reinitialized from
1019
       m_dict rather than calling their initialization function again. */
1020
    void *md_gil;
1021
#endif
1022
};
1023
1024
static struct extensions_cache_value *
1025
alloc_extensions_cache_value(void)
1026
32
{
1027
32
    struct extensions_cache_value *value
1028
32
            = PyMem_RawMalloc(sizeof(struct extensions_cache_value));
1029
32
    if (value == NULL) {
1030
0
        PyErr_NoMemory();
1031
0
        return NULL;
1032
0
    }
1033
32
    *value = (struct extensions_cache_value){0};
1034
32
    return value;
1035
32
}
1036
1037
static void
1038
free_extensions_cache_value(struct extensions_cache_value *value)
1039
0
{
1040
0
    PyMem_RawFree(value);
1041
0
}
1042
1043
static Py_ssize_t
1044
_get_cached_module_index(struct extensions_cache_value *cached)
1045
32
{
1046
32
    assert(cached->m_index > 0);
1047
32
    return cached->m_index;
1048
32
}
1049
1050
static void
1051
fixup_cached_def(struct extensions_cache_value *value)
1052
32
{
1053
    /* For the moment, the values in the def's m_base may belong
1054
     * to another module, and we're replacing them here.  This can
1055
     * cause problems later if the old module is reloaded.
1056
     *
1057
     * Also, we don't decref any old cached values first when we
1058
     * replace them here, in case we need to restore them in the
1059
     * near future.  Instead, the caller is responsible for wrapping
1060
     * this up by calling cleanup_old_cached_def() or
1061
     * restore_old_cached_def() if there was an error. */
1062
32
    PyModuleDef *def = value->def;
1063
32
    assert(def != NULL);
1064
1065
    /* We assume that all module defs are statically allocated
1066
       and will never be freed.  Otherwise, we would incref here. */
1067
32
    _Py_SetImmortalUntracked((PyObject *)def);
1068
1069
32
    def->m_base.m_init = value->m_init;
1070
1071
32
    assert(value->m_index > 0);
1072
32
    _set_module_index(def, value->m_index);
1073
1074
    /* Different modules can share the same def, so we can't just
1075
     * expect m_copy to be NULL. */
1076
32
    assert(def->m_base.m_copy == NULL
1077
32
           || def->m_base.m_init == NULL
1078
32
           || value->m_dict != NULL);
1079
32
    if (value->m_dict != NULL) {
1080
0
        assert(value->m_dict->copied != NULL);
1081
        /* As noted above, we don't first decref the old value, if any. */
1082
0
        def->m_base.m_copy = Py_NewRef(value->m_dict->copied);
1083
0
    }
1084
32
}
1085
1086
static void
1087
restore_old_cached_def(PyModuleDef *def, PyModuleDef_Base *oldbase)
1088
0
{
1089
0
    def->m_base = *oldbase;
1090
0
}
1091
1092
static void
1093
cleanup_old_cached_def(PyModuleDef_Base *oldbase)
1094
32
{
1095
32
    Py_XDECREF(oldbase->m_copy);
1096
32
}
1097
1098
static void
1099
del_cached_def(struct extensions_cache_value *value)
1100
0
{
1101
    /* If we hadn't made the stored defs immortal, we would decref here.
1102
       However, this decref would be problematic if the module def were
1103
       dynamically allocated, it were the last ref, and this function
1104
       were called with an interpreter other than the def's owner. */
1105
0
    assert(value->def == NULL || _Py_IsImmortal(value->def));
1106
1107
0
    Py_XDECREF(value->def->m_base.m_copy);
1108
0
    value->def->m_base.m_copy = NULL;
1109
0
}
1110
1111
static int
1112
init_cached_m_dict(struct extensions_cache_value *value, PyObject *m_dict)
1113
32
{
1114
32
    assert(value != NULL);
1115
    /* This should only have been called without an m_dict already set. */
1116
32
    assert(value->m_dict == NULL);
1117
32
    if (m_dict == NULL) {
1118
32
        return 0;
1119
32
    }
1120
0
    assert(PyDict_Check(m_dict));
1121
0
    assert(value->origin != _Py_ext_module_origin_CORE);
1122
1123
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1124
0
    assert(!is_interpreter_isolated(interp));
1125
1126
    /* XXX gh-88216: The copied dict is owned by the current
1127
     * interpreter.  That's a problem if the interpreter has
1128
     * its own obmalloc state or if the module is successfully
1129
     * imported into such an interpreter.  If the interpreter
1130
     * has its own GIL then there may be data races and
1131
     * PyImport_ClearModulesByIndex() can crash.  Normally,
1132
     * a single-phase init module cannot be imported in an
1133
     * isolated interpreter, but there are ways around that.
1134
     * Hence, heere be dragons!  Ideally we would instead do
1135
     * something like make a read-only, immortal copy of the
1136
     * dict using PyMem_RawMalloc() and store *that* in m_copy.
1137
     * Then we'd need to make sure to clear that when the
1138
     * runtime is finalized, rather than in
1139
     * PyImport_ClearModulesByIndex(). */
1140
0
    PyObject *copied = PyDict_Copy(m_dict);
1141
0
    if (copied == NULL) {
1142
        /* We expect this can only be "out of memory". */
1143
0
        return -1;
1144
0
    }
1145
    // XXX We may want to make the copy immortal.
1146
1147
0
    value->_m_dict = (struct cached_m_dict){
1148
0
        .copied=copied,
1149
0
        .interpid=PyInterpreterState_GetID(interp),
1150
0
    };
1151
1152
0
    value->m_dict = &value->_m_dict;
1153
0
    return 0;
1154
0
}
1155
1156
static void
1157
del_cached_m_dict(struct extensions_cache_value *value)
1158
0
{
1159
0
    if (value->m_dict != NULL) {
1160
0
        assert(value->m_dict == &value->_m_dict);
1161
0
        assert(value->m_dict->copied != NULL);
1162
        /* In the future we can take advantage of m_dict->interpid
1163
         * to decref the dict using the owning interpreter. */
1164
0
        Py_XDECREF(value->m_dict->copied);
1165
0
        value->m_dict = NULL;
1166
0
    }
1167
0
}
1168
1169
static PyObject * get_core_module_dict(
1170
        PyInterpreterState *interp, PyObject *name, PyObject *path);
1171
1172
static PyObject *
1173
get_cached_m_dict(struct extensions_cache_value *value,
1174
                  PyObject *name, PyObject *path)
1175
0
{
1176
0
    assert(value != NULL);
1177
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1178
    /* It might be a core module (e.g. sys & builtins),
1179
       for which we don't cache m_dict. */
1180
0
    if (value->origin == _Py_ext_module_origin_CORE) {
1181
0
        return get_core_module_dict(interp, name, path);
1182
0
    }
1183
0
    assert(value->def != NULL);
1184
    // XXX Switch to value->m_dict.
1185
0
    PyObject *m_dict = value->def->m_base.m_copy;
1186
0
    Py_XINCREF(m_dict);
1187
0
    return m_dict;
1188
0
}
1189
1190
static void
1191
del_extensions_cache_value(void *raw)
1192
0
{
1193
0
    struct extensions_cache_value *value = raw;
1194
0
    if (value != NULL) {
1195
0
        del_cached_m_dict(value);
1196
0
        del_cached_def(value);
1197
0
        free_extensions_cache_value(value);
1198
0
    }
1199
0
}
1200
1201
static void *
1202
hashtable_key_from_2_strings(PyObject *str1, PyObject *str2, const char sep)
1203
431
{
1204
431
    const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1205
431
    const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1206
431
    if (str1_data == NULL || str2_data == NULL) {
1207
0
        return NULL;
1208
0
    }
1209
431
    Py_ssize_t str1_len = strlen(str1_data);
1210
431
    Py_ssize_t str2_len = strlen(str2_data);
1211
1212
    /* Make sure sep and the NULL byte won't cause an overflow. */
1213
431
    assert(SIZE_MAX - str1_len - str2_len > 2);
1214
431
    size_t size = str1_len + 1 + str2_len + 1;
1215
1216
    // XXX Use a buffer if it's a temp value (every case but "set").
1217
431
    char *key = PyMem_RawMalloc(size);
1218
431
    if (key == NULL) {
1219
0
        PyErr_NoMemory();
1220
0
        return NULL;
1221
0
    }
1222
1223
431
    memcpy(key, str1_data, str1_len);
1224
431
    key[str1_len] = sep;
1225
431
    memcpy(key + str1_len + 1, str2_data, str2_len);
1226
431
    key[size - 1] = '\0';
1227
431
    assert(strlen(key) == size - 1);
1228
431
    return key;
1229
431
}
1230
1231
static Py_uhash_t
1232
hashtable_hash_str(const void *key)
1233
463
{
1234
463
    return Py_HashBuffer(key, strlen((const char *)key));
1235
463
}
1236
1237
static int
1238
hashtable_compare_str(const void *key1, const void *key2)
1239
0
{
1240
0
    return strcmp((const char *)key1, (const char *)key2) == 0;
1241
0
}
1242
1243
static void
1244
hashtable_destroy_str(void *ptr)
1245
399
{
1246
399
    PyMem_RawFree(ptr);
1247
399
}
1248
1249
#ifndef NDEBUG
1250
struct hashtable_next_match_def_data {
1251
    PyModuleDef *def;
1252
    struct extensions_cache_value *matched;
1253
};
1254
1255
static int
1256
hashtable_next_match_def(_Py_hashtable_t *ht,
1257
                         const void *key, const void *value, void *user_data)
1258
{
1259
    if (value == NULL) {
1260
        /* It was previously deleted. */
1261
        return 0;
1262
    }
1263
    struct hashtable_next_match_def_data *data
1264
            = (struct hashtable_next_match_def_data *)user_data;
1265
    struct extensions_cache_value *cur
1266
            = (struct extensions_cache_value *)value;
1267
    if (cur->def == data->def) {
1268
        data->matched = cur;
1269
        return 1;
1270
    }
1271
    return 0;
1272
}
1273
1274
static struct extensions_cache_value *
1275
_find_cached_def(PyModuleDef *def)
1276
{
1277
    struct hashtable_next_match_def_data data = {0};
1278
    (void)_Py_hashtable_foreach(
1279
            EXTENSIONS.hashtable, hashtable_next_match_def, &data);
1280
    return data.matched;
1281
}
1282
#endif
1283
1284
431
#define HTSEP ':'
1285
1286
static int
1287
_extensions_cache_init(void)
1288
16
{
1289
16
    _Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
1290
16
    EXTENSIONS.hashtable = _Py_hashtable_new_full(
1291
16
        hashtable_hash_str,
1292
16
        hashtable_compare_str,
1293
16
        hashtable_destroy_str,  // key
1294
16
        del_extensions_cache_value,  // value
1295
16
        &alloc
1296
16
    );
1297
16
    if (EXTENSIONS.hashtable == NULL) {
1298
0
        PyErr_NoMemory();
1299
0
        return -1;
1300
0
    }
1301
16
    return 0;
1302
16
}
1303
1304
static _Py_hashtable_entry_t *
1305
_extensions_cache_find_unlocked(PyObject *path, PyObject *name,
1306
                                void **p_key)
1307
447
{
1308
447
    if (EXTENSIONS.hashtable == NULL) {
1309
16
        return NULL;
1310
16
    }
1311
431
    void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1312
431
    if (key == NULL) {
1313
0
        return NULL;
1314
0
    }
1315
431
    _Py_hashtable_entry_t *entry =
1316
431
            _Py_hashtable_get_entry(EXTENSIONS.hashtable, key);
1317
431
    if (p_key != NULL) {
1318
32
        *p_key = key;
1319
32
    }
1320
399
    else {
1321
399
        hashtable_destroy_str(key);
1322
399
    }
1323
431
    return entry;
1324
431
}
1325
1326
/* This can only fail with "out of memory". */
1327
static struct extensions_cache_value *
1328
_extensions_cache_get(PyObject *path, PyObject *name)
1329
415
{
1330
415
    struct extensions_cache_value *value = NULL;
1331
415
    extensions_lock_acquire();
1332
1333
415
    _Py_hashtable_entry_t *entry =
1334
415
            _extensions_cache_find_unlocked(path, name, NULL);
1335
415
    if (entry == NULL) {
1336
        /* It was never added. */
1337
415
        goto finally;
1338
415
    }
1339
0
    value = (struct extensions_cache_value *)entry->value;
1340
1341
415
finally:
1342
415
    extensions_lock_release();
1343
415
    return value;
1344
0
}
1345
1346
/* This can only fail with "out of memory". */
1347
static struct extensions_cache_value *
1348
_extensions_cache_set(PyObject *path, PyObject *name,
1349
                      PyModuleDef *def, PyModInitFunction m_init,
1350
                      Py_ssize_t m_index, PyObject *m_dict,
1351
                      _Py_ext_module_origin origin, void *md_gil)
1352
32
{
1353
32
    struct extensions_cache_value *value = NULL;
1354
32
    void *key = NULL;
1355
32
    struct extensions_cache_value *newvalue = NULL;
1356
32
    PyModuleDef_Base olddefbase = def->m_base;
1357
1358
32
    assert(def != NULL);
1359
32
    assert(m_init == NULL || m_dict == NULL);
1360
    /* We expect the same symbol to be used and the shared object file
1361
     * to have remained loaded, so it must be the same pointer. */
1362
32
    assert(def->m_base.m_init == NULL || def->m_base.m_init == m_init);
1363
    /* For now we don't worry about comparing value->m_copy. */
1364
32
    assert(def->m_base.m_copy == NULL || m_dict != NULL);
1365
32
    assert((origin == _Py_ext_module_origin_DYNAMIC) == (name != path));
1366
32
    assert(origin != _Py_ext_module_origin_CORE || m_dict == NULL);
1367
1368
32
    extensions_lock_acquire();
1369
1370
32
    if (EXTENSIONS.hashtable == NULL) {
1371
16
        if (_extensions_cache_init() < 0) {
1372
0
            goto finally;
1373
0
        }
1374
16
    }
1375
1376
    /* Create a cached value to populate for the module. */
1377
32
    _Py_hashtable_entry_t *entry =
1378
32
            _extensions_cache_find_unlocked(path, name, &key);
1379
32
    value = entry == NULL
1380
32
        ? NULL
1381
32
        : (struct extensions_cache_value *)entry->value;
1382
32
    if (value != NULL) {
1383
        /* gh-123880: If there's an existing cache value, it means a module is
1384
         * being imported recursively from its PyInit_* or Py_mod_* function.
1385
         * (That function presumably handles returning a partially
1386
         *  constructed module in such a case.)
1387
         * We can reuse the existing cache value; it is owned by the cache.
1388
         * (Entries get removed from it in exceptional circumstances,
1389
         *  after interpreter shutdown, and in runtime shutdown.)
1390
         */
1391
0
        goto finally_oldvalue;
1392
0
    }
1393
32
    newvalue = alloc_extensions_cache_value();
1394
32
    if (newvalue == NULL) {
1395
0
        goto finally;
1396
0
    }
1397
1398
    /* Populate the new cache value data. */
1399
32
    *newvalue = (struct extensions_cache_value){
1400
32
        .def=def,
1401
32
        .m_init=m_init,
1402
32
        .m_index=m_index,
1403
        /* m_dict is set by set_cached_m_dict(). */
1404
32
        .origin=origin,
1405
#ifdef Py_GIL_DISABLED
1406
        .md_gil=md_gil,
1407
#endif
1408
32
    };
1409
32
#ifndef Py_GIL_DISABLED
1410
32
    (void)md_gil;
1411
32
#endif
1412
32
    if (init_cached_m_dict(newvalue, m_dict) < 0) {
1413
0
        goto finally;
1414
0
    }
1415
32
    fixup_cached_def(newvalue);
1416
1417
32
    if (entry == NULL) {
1418
        /* It was never added. */
1419
32
        if (_Py_hashtable_set(EXTENSIONS.hashtable, key, newvalue) < 0) {
1420
0
            PyErr_NoMemory();
1421
0
            goto finally;
1422
0
        }
1423
        /* The hashtable owns the key now. */
1424
32
        key = NULL;
1425
32
    }
1426
0
    else if (value == NULL) {
1427
        /* It was previously deleted. */
1428
0
        entry->value = newvalue;
1429
0
    }
1430
0
    else {
1431
        /* We are updating the entry for an existing module. */
1432
        /* We expect def to be static, so it must be the same pointer. */
1433
0
        assert(value->def == def);
1434
        /* We expect the same symbol to be used and the shared object file
1435
         * to have remained loaded, so it must be the same pointer. */
1436
0
        assert(value->m_init == m_init);
1437
        /* The same module can't switch between caching __dict__ and not. */
1438
0
        assert((value->m_dict == NULL) == (m_dict == NULL));
1439
        /* This shouldn't ever happen. */
1440
0
        Py_UNREACHABLE();
1441
0
    }
1442
1443
32
    value = newvalue;
1444
1445
32
finally:
1446
32
    if (value == NULL) {
1447
0
        restore_old_cached_def(def, &olddefbase);
1448
0
        if (newvalue != NULL) {
1449
0
            del_extensions_cache_value(newvalue);
1450
0
        }
1451
0
    }
1452
32
    else {
1453
32
        cleanup_old_cached_def(&olddefbase);
1454
32
    }
1455
1456
32
finally_oldvalue:
1457
32
    extensions_lock_release();
1458
32
    if (key != NULL) {
1459
0
        hashtable_destroy_str(key);
1460
0
    }
1461
1462
32
    return value;
1463
32
}
1464
1465
static void
1466
_extensions_cache_delete(PyObject *path, PyObject *name)
1467
0
{
1468
0
    extensions_lock_acquire();
1469
1470
0
    if (EXTENSIONS.hashtable == NULL) {
1471
        /* It was never added. */
1472
0
        goto finally;
1473
0
    }
1474
1475
0
    _Py_hashtable_entry_t *entry =
1476
0
            _extensions_cache_find_unlocked(path, name, NULL);
1477
0
    if (entry == NULL) {
1478
        /* It was never added. */
1479
0
        goto finally;
1480
0
    }
1481
0
    if (entry->value == NULL) {
1482
        /* It was already removed. */
1483
0
        goto finally;
1484
0
    }
1485
0
    struct extensions_cache_value *value = entry->value;
1486
0
    entry->value = NULL;
1487
1488
0
    del_extensions_cache_value(value);
1489
1490
0
finally:
1491
0
    extensions_lock_release();
1492
0
}
1493
1494
static void
1495
_extensions_cache_clear_all(void)
1496
0
{
1497
    /* The runtime (i.e. main interpreter) must be finalizing,
1498
       so we don't need to worry about the lock. */
1499
0
    _Py_hashtable_destroy(EXTENSIONS.hashtable);
1500
0
    EXTENSIONS.hashtable = NULL;
1501
0
}
1502
1503
#undef HTSEP
1504
1505
1506
static bool
1507
check_multi_interp_extensions(PyInterpreterState *interp)
1508
0
{
1509
0
    int override = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
1510
0
    if (override < 0) {
1511
0
        return false;
1512
0
    }
1513
0
    else if (override > 0) {
1514
0
        return true;
1515
0
    }
1516
0
    else if (_PyInterpreterState_HasFeature(
1517
0
                interp, Py_RTFLAGS_MULTI_INTERP_EXTENSIONS)) {
1518
0
        return true;
1519
0
    }
1520
0
    return false;
1521
0
}
1522
1523
int
1524
_PyImport_CheckSubinterpIncompatibleExtensionAllowed(const char *name)
1525
0
{
1526
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1527
0
    if (check_multi_interp_extensions(interp)) {
1528
0
        assert(!_Py_IsMainInterpreter(interp));
1529
0
        PyErr_Format(PyExc_ImportError,
1530
0
                     "module %s does not support loading in subinterpreters",
1531
0
                     name);
1532
0
        return -1;
1533
0
    }
1534
0
    return 0;
1535
0
}
1536
1537
#ifdef Py_GIL_DISABLED
1538
int
1539
_PyImport_CheckGILForModule(PyObject* module, PyObject *module_name)
1540
{
1541
    PyThreadState *tstate = _PyThreadState_GET();
1542
    if (module == NULL) {
1543
        _PyEval_DisableGIL(tstate);
1544
        return 0;
1545
    }
1546
1547
    if (!PyModule_Check(module) ||
1548
        ((PyModuleObject *)module)->md_gil == Py_MOD_GIL_USED) {
1549
        if (_PyEval_EnableGILPermanent(tstate)) {
1550
            int warn_result = PyErr_WarnFormat(
1551
                PyExc_RuntimeWarning,
1552
                1,
1553
                "The global interpreter lock (GIL) has been enabled to load "
1554
                "module '%U', which has not declared that it can run safely "
1555
                "without the GIL. To override this behavior and keep the GIL "
1556
                "disabled (at your own risk), run with PYTHON_GIL=0 or -Xgil=0.",
1557
                module_name
1558
            );
1559
            if (warn_result < 0) {
1560
                return warn_result;
1561
            }
1562
        }
1563
1564
        const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
1565
        if (config->enable_gil == _PyConfig_GIL_DEFAULT && config->verbose) {
1566
            PySys_FormatStderr("# loading module '%U', which requires the GIL\n",
1567
                               module_name);
1568
        }
1569
    }
1570
    else {
1571
        _PyEval_DisableGIL(tstate);
1572
    }
1573
1574
    return 0;
1575
}
1576
#endif
1577
1578
static PyThreadState *
1579
switch_to_main_interpreter(PyThreadState *tstate)
1580
383
{
1581
383
    if (_Py_IsMainInterpreter(tstate->interp)) {
1582
383
        return tstate;
1583
383
    }
1584
0
    PyThreadState *main_tstate = _PyThreadState_NewBound(
1585
0
            _PyInterpreterState_Main(), _PyThreadState_WHENCE_EXEC);
1586
0
    if (main_tstate == NULL) {
1587
0
        return NULL;
1588
0
    }
1589
#ifndef NDEBUG
1590
    PyThreadState *old_tstate = PyThreadState_Swap(main_tstate);
1591
    assert(old_tstate == tstate);
1592
#else
1593
0
    (void)PyThreadState_Swap(main_tstate);
1594
0
#endif
1595
0
    return main_tstate;
1596
0
}
1597
1598
static void
1599
switch_back_from_main_interpreter(PyThreadState *tstate,
1600
                                  PyThreadState *main_tstate,
1601
                                  PyObject *tempobj)
1602
0
{
1603
0
    assert(main_tstate == PyThreadState_GET());
1604
0
    assert(_Py_IsMainInterpreter(main_tstate->interp));
1605
0
    assert(tstate->interp != main_tstate->interp);
1606
1607
    /* Handle any exceptions, which we cannot propagate directly
1608
     * to the subinterpreter. */
1609
0
    if (PyErr_Occurred()) {
1610
0
        if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
1611
            /* We trust it will be caught again soon. */
1612
0
            PyErr_Clear();
1613
0
        }
1614
0
        else {
1615
            /* Printing the exception should be sufficient. */
1616
0
            PyErr_PrintEx(0);
1617
0
        }
1618
0
    }
1619
1620
0
    Py_XDECREF(tempobj);
1621
1622
0
    PyThreadState_Clear(main_tstate);
1623
0
    (void)PyThreadState_Swap(tstate);
1624
0
    PyThreadState_Delete(main_tstate);
1625
0
}
1626
1627
static PyObject *
1628
get_core_module_dict(PyInterpreterState *interp,
1629
                     PyObject *name, PyObject *path)
1630
0
{
1631
    /* Only builtin modules are core. */
1632
0
    if (path == name) {
1633
0
        assert(!PyErr_Occurred());
1634
0
        if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
1635
0
            return Py_NewRef(interp->sysdict_copy);
1636
0
        }
1637
0
        assert(!PyErr_Occurred());
1638
0
        if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
1639
0
            return Py_NewRef(interp->builtins_copy);
1640
0
        }
1641
0
        assert(!PyErr_Occurred());
1642
0
    }
1643
0
    return NULL;
1644
0
}
1645
1646
#ifndef NDEBUG
1647
static inline int
1648
is_core_module(PyInterpreterState *interp, PyObject *name, PyObject *path)
1649
{
1650
    /* This might be called before the core dict copies are in place,
1651
       so we can't rely on get_core_module_dict() here. */
1652
    if (path == name) {
1653
        if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
1654
            return 1;
1655
        }
1656
        if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
1657
            return 1;
1658
        }
1659
    }
1660
    return 0;
1661
}
1662
1663
1664
static _Py_ext_module_kind
1665
_get_extension_kind(PyModuleDef *def, bool check_size)
1666
{
1667
    _Py_ext_module_kind kind;
1668
    if (def == NULL) {
1669
        /* It must be a module created by reload_singlephase_extension()
1670
         * from m_copy.  Ideally we'd do away with this case. */
1671
        kind = _Py_ext_module_kind_SINGLEPHASE;
1672
    }
1673
    else if (def->m_slots != NULL) {
1674
        kind = _Py_ext_module_kind_MULTIPHASE;
1675
    }
1676
    else if (check_size && def->m_size == -1) {
1677
        kind = _Py_ext_module_kind_SINGLEPHASE;
1678
    }
1679
    else if (def->m_base.m_init != NULL) {
1680
        kind = _Py_ext_module_kind_SINGLEPHASE;
1681
    }
1682
    else {
1683
        // This is probably single-phase init, but a multi-phase
1684
        // module *can* have NULL m_slots.
1685
        kind = _Py_ext_module_kind_UNKNOWN;
1686
    }
1687
    return kind;
1688
}
1689
1690
/* The module might not be fully initialized yet
1691
 * and PyModule_FromDefAndSpec() checks m_size
1692
 * so we skip m_size. */
1693
#define assert_multiphase_def(def)                                  \
1694
    do {                                                            \
1695
        _Py_ext_module_kind kind = _get_extension_kind(def, false); \
1696
        assert(kind == _Py_ext_module_kind_MULTIPHASE               \
1697
                /* m_slots can be NULL. */                          \
1698
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1699
    } while (0)
1700
1701
#define assert_singlephase_def(def)                                 \
1702
    do {                                                            \
1703
        _Py_ext_module_kind kind = _get_extension_kind(def, true);  \
1704
        assert(kind == _Py_ext_module_kind_SINGLEPHASE              \
1705
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1706
    } while (0)
1707
1708
#define assert_singlephase(cached)                                          \
1709
    do {                                                                    \
1710
        _Py_ext_module_kind kind = _get_extension_kind(cached->def, true);  \
1711
        assert(kind == _Py_ext_module_kind_SINGLEPHASE);                    \
1712
    } while (0)
1713
1714
#else  /* defined(NDEBUG) */
1715
#define assert_multiphase_def(def)
1716
#define assert_singlephase_def(def)
1717
#define assert_singlephase(cached)
1718
#endif
1719
1720
1721
struct singlephase_global_update {
1722
    PyModInitFunction m_init;
1723
    Py_ssize_t m_index;
1724
    PyObject *m_dict;
1725
    _Py_ext_module_origin origin;
1726
    void *md_gil;
1727
};
1728
1729
static struct extensions_cache_value *
1730
update_global_state_for_extension(PyThreadState *tstate,
1731
                                  PyObject *path, PyObject *name,
1732
                                  PyModuleDef *def,
1733
                                  struct singlephase_global_update *singlephase)
1734
32
{
1735
32
    struct extensions_cache_value *cached = NULL;
1736
32
    PyModInitFunction m_init = NULL;
1737
32
    PyObject *m_dict = NULL;
1738
1739
    /* Set up for _extensions_cache_set(). */
1740
32
    if (singlephase == NULL) {
1741
0
        assert(def->m_base.m_init == NULL);
1742
0
        assert(def->m_base.m_copy == NULL);
1743
0
    }
1744
32
    else {
1745
32
        if (singlephase->m_init != NULL) {
1746
0
            assert(singlephase->m_dict == NULL);
1747
0
            assert(def->m_base.m_copy == NULL);
1748
0
            assert(def->m_size >= 0);
1749
            /* Remember pointer to module init function. */
1750
            // XXX If two modules share a def then def->m_base will
1751
            // reflect the last one added (here) to the global cache.
1752
            // We should prevent this somehow.  The simplest solution
1753
            // is probably to store m_copy/m_init in the cache along
1754
            // with the def, rather than within the def.
1755
0
            m_init = singlephase->m_init;
1756
0
        }
1757
32
        else if (singlephase->m_dict == NULL) {
1758
            /* It must be a core builtin module. */
1759
32
            assert(is_core_module(tstate->interp, name, path));
1760
32
            assert(def->m_size == -1);
1761
32
            assert(def->m_base.m_copy == NULL);
1762
32
            assert(def->m_base.m_init == NULL);
1763
32
        }
1764
0
        else {
1765
0
            assert(PyDict_Check(singlephase->m_dict));
1766
            // gh-88216: Extensions and def->m_base.m_copy can be updated
1767
            // when the extension module doesn't support sub-interpreters.
1768
0
            assert(def->m_size == -1);
1769
0
            assert(!is_core_module(tstate->interp, name, path));
1770
0
            assert(PyUnicode_CompareWithASCIIString(name, "sys") != 0);
1771
0
            assert(PyUnicode_CompareWithASCIIString(name, "builtins") != 0);
1772
0
            m_dict = singlephase->m_dict;
1773
0
        }
1774
32
    }
1775
1776
    /* Add the module's def to the global cache. */
1777
    // XXX Why special-case the main interpreter?
1778
32
    if (_Py_IsMainInterpreter(tstate->interp) || def->m_size == -1) {
1779
#ifndef NDEBUG
1780
        cached = _extensions_cache_get(path, name);
1781
        assert(cached == NULL || cached->def == def);
1782
#endif
1783
32
        cached = _extensions_cache_set(
1784
32
                path, name, def, m_init, singlephase->m_index, m_dict,
1785
32
                singlephase->origin, singlephase->md_gil);
1786
32
        if (cached == NULL) {
1787
            // XXX Ignore this error?  Doing so would effectively
1788
            // mark the module as not loadable.
1789
0
            return NULL;
1790
0
        }
1791
32
    }
1792
1793
32
    return cached;
1794
32
}
1795
1796
/* For multi-phase init modules, the module is finished
1797
 * by PyModule_FromDefAndSpec(). */
1798
static int
1799
finish_singlephase_extension(PyThreadState *tstate, PyObject *mod,
1800
                             struct extensions_cache_value *cached,
1801
                             PyObject *name, PyObject *modules)
1802
32
{
1803
32
    assert(mod != NULL && PyModule_Check(mod));
1804
32
    assert(cached->def == _PyModule_GetDef(mod));
1805
1806
32
    Py_ssize_t index = _get_cached_module_index(cached);
1807
32
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1808
0
        return -1;
1809
0
    }
1810
1811
32
    if (modules != NULL) {
1812
32
        if (PyObject_SetItem(modules, name, mod) < 0) {
1813
0
            return -1;
1814
0
        }
1815
32
    }
1816
1817
32
    return 0;
1818
32
}
1819
1820
1821
static PyObject *
1822
reload_singlephase_extension(PyThreadState *tstate,
1823
                             struct extensions_cache_value *cached,
1824
                             struct _Py_ext_module_loader_info *info)
1825
0
{
1826
0
    PyModuleDef *def = cached->def;
1827
0
    assert(def != NULL);
1828
0
    assert_singlephase(cached);
1829
0
    PyObject *mod = NULL;
1830
1831
    /* It may have been successfully imported previously
1832
       in an interpreter that allows legacy modules
1833
       but is not allowed in the current interpreter. */
1834
0
    const char *name_buf = PyUnicode_AsUTF8(info->name);
1835
0
    assert(name_buf != NULL);
1836
0
    if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
1837
0
        return NULL;
1838
0
    }
1839
1840
0
    PyObject *modules = get_modules_dict(tstate, true);
1841
0
    if (def->m_size == -1) {
1842
        /* Module does not support repeated initialization */
1843
0
        assert(cached->m_init == NULL);
1844
0
        assert(def->m_base.m_init == NULL);
1845
        // XXX Copying the cached dict may break interpreter isolation.
1846
        // We could solve this by temporarily acquiring the original
1847
        // interpreter's GIL.
1848
0
        PyObject *m_copy = get_cached_m_dict(cached, info->name, info->path);
1849
0
        if (m_copy == NULL) {
1850
0
            assert(!PyErr_Occurred());
1851
0
            return NULL;
1852
0
        }
1853
0
        mod = import_add_module(tstate, info->name);
1854
0
        if (mod == NULL) {
1855
0
            Py_DECREF(m_copy);
1856
0
            return NULL;
1857
0
        }
1858
0
        PyObject *mdict = PyModule_GetDict(mod);
1859
0
        if (mdict == NULL) {
1860
0
            Py_DECREF(m_copy);
1861
0
            Py_DECREF(mod);
1862
0
            return NULL;
1863
0
        }
1864
0
        int rc = PyDict_Update(mdict, m_copy);
1865
0
        Py_DECREF(m_copy);
1866
0
        if (rc < 0) {
1867
0
            Py_DECREF(mod);
1868
0
            return NULL;
1869
0
        }
1870
#ifdef Py_GIL_DISABLED
1871
        if (def->m_base.m_copy != NULL) {
1872
            // For non-core modules, fetch the GIL slot that was stored by
1873
            // import_run_extension().
1874
            ((PyModuleObject *)mod)->md_gil = cached->md_gil;
1875
        }
1876
#endif
1877
        /* We can't set mod->md_def if it's missing,
1878
         * because _PyImport_ClearModulesByIndex() might break
1879
         * due to violating interpreter isolation.
1880
         * See the note in set_cached_m_dict().
1881
         * Until that is solved, we leave md_def set to NULL. */
1882
0
        assert(_PyModule_GetDef(mod) == NULL
1883
0
               || _PyModule_GetDef(mod) == def);
1884
0
    }
1885
0
    else {
1886
0
        assert(cached->m_dict == NULL);
1887
0
        assert(def->m_base.m_copy == NULL);
1888
        // XXX Use cached->m_init.
1889
0
        PyModInitFunction p0 = def->m_base.m_init;
1890
0
        if (p0 == NULL) {
1891
0
            assert(!PyErr_Occurred());
1892
0
            return NULL;
1893
0
        }
1894
0
        struct _Py_ext_module_loader_result res;
1895
0
        if (_PyImport_RunModInitFunc(p0, info, &res) < 0) {
1896
0
            _Py_ext_module_loader_result_apply_error(&res, name_buf);
1897
0
            return NULL;
1898
0
        }
1899
0
        assert(!PyErr_Occurred());
1900
0
        assert(res.err == NULL);
1901
0
        assert(res.kind == _Py_ext_module_kind_SINGLEPHASE);
1902
0
        mod = res.module;
1903
        /* Tchnically, the init function could return a different module def.
1904
         * Then we would probably need to update the global cache.
1905
         * However, we don't expect anyone to change the def. */
1906
0
        assert(res.def == def);
1907
0
        _Py_ext_module_loader_result_clear(&res);
1908
1909
        /* Remember the filename as the __file__ attribute */
1910
0
        if (info->filename != NULL) {
1911
0
            if (PyModule_AddObjectRef(mod, "__file__", info->filename) < 0) {
1912
0
                PyErr_Clear(); /* Not important enough to report */
1913
0
            }
1914
0
        }
1915
1916
0
        if (PyObject_SetItem(modules, info->name, mod) == -1) {
1917
0
            Py_DECREF(mod);
1918
0
            return NULL;
1919
0
        }
1920
0
    }
1921
1922
0
    Py_ssize_t index = _get_cached_module_index(cached);
1923
0
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1924
0
        PyMapping_DelItem(modules, info->name);
1925
0
        Py_DECREF(mod);
1926
0
        return NULL;
1927
0
    }
1928
1929
0
    return mod;
1930
0
}
1931
1932
static PyObject *
1933
import_find_extension(PyThreadState *tstate,
1934
                      struct _Py_ext_module_loader_info *info,
1935
                      struct extensions_cache_value **p_cached)
1936
383
{
1937
    /* Only single-phase init modules will be in the cache. */
1938
383
    struct extensions_cache_value *cached
1939
383
            = _extensions_cache_get(info->path, info->name);
1940
383
    if (cached == NULL) {
1941
383
        return NULL;
1942
383
    }
1943
0
    assert(cached->def != NULL);
1944
0
    assert_singlephase(cached);
1945
0
    *p_cached = cached;
1946
1947
    /* It may have been successfully imported previously
1948
       in an interpreter that allows legacy modules
1949
       but is not allowed in the current interpreter. */
1950
0
    const char *name_buf = PyUnicode_AsUTF8(info->name);
1951
0
    assert(name_buf != NULL);
1952
0
    if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
1953
0
        return NULL;
1954
0
    }
1955
1956
0
    PyObject *mod = reload_singlephase_extension(tstate, cached, info);
1957
0
    if (mod == NULL) {
1958
0
        return NULL;
1959
0
    }
1960
1961
0
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
1962
0
    if (verbose) {
1963
0
        PySys_FormatStderr("import %U # previously loaded (%R)\n",
1964
0
                           info->name, info->path);
1965
0
    }
1966
1967
0
    return mod;
1968
0
}
1969
1970
static PyObject *
1971
import_run_extension(PyThreadState *tstate, PyModInitFunction p0,
1972
                     struct _Py_ext_module_loader_info *info,
1973
                     PyObject *spec, PyObject *modules)
1974
383
{
1975
    /* Core modules go through _PyImport_FixupBuiltin(). */
1976
383
    assert(!is_core_module(tstate->interp, info->name, info->path));
1977
1978
383
    PyObject *mod = NULL;
1979
383
    PyModuleDef *def = NULL;
1980
383
    struct extensions_cache_value *cached = NULL;
1981
383
    const char *name_buf = PyBytes_AS_STRING(info->name_encoded);
1982
1983
    /* We cannot know if the module is single-phase init or
1984
     * multi-phase init until after we call its init function. Even
1985
     * in isolated interpreters (that do not support single-phase init),
1986
     * the init function will run without restriction.  For multi-phase
1987
     * init modules that isn't a problem because the init function only
1988
     * runs PyModuleDef_Init() on the module's def and then returns it.
1989
     *
1990
     * However, for single-phase init the module's init function will
1991
     * create the module, create other objects (and allocate other
1992
     * memory), populate it and its module state, and initialize static
1993
     * types.  Some modules store other objects and data in global C
1994
     * variables and register callbacks with the runtime/stdlib or
1995
     * even external libraries (which is part of why we can't just
1996
     * dlclose() the module in the error case).  That's a problem
1997
     * for isolated interpreters since all of the above happens
1998
     * and only then * will the import fail.  Memory will leak,
1999
     * callbacks will still get used, and sometimes there
2000
     * will be crashes (memory access violations
2001
     * and use-after-free).
2002
     *
2003
     * To put it another way, if the module is single-phase init
2004
     * then the import will probably break interpreter isolation
2005
     * and should fail ASAP.  However, the module's init function
2006
     * will still get run.  That means it may still store state
2007
     * in the shared-object/DLL address space (which never gets
2008
     * closed/cleared), including objects (e.g. static types).
2009
     * This is a problem for isolated subinterpreters since each
2010
     * has its own object allocator.  If the loaded shared-object
2011
     * still holds a reference to an object after the corresponding
2012
     * interpreter has finalized then either we must let it leak
2013
     * or else any later use of that object by another interpreter
2014
     * (or across multiple init-fini cycles) will crash the process.
2015
     *
2016
     * To avoid all of that, we make sure the module's init function
2017
     * is always run first with the main interpreter active.  If it was
2018
     * already the main interpreter then we can continue loading the
2019
     * module like normal.  Otherwise, right after the init function,
2020
     * we take care of some import state bookkeeping, switch back
2021
     * to the subinterpreter, check for single-phase init,
2022
     * and then continue loading like normal. */
2023
2024
383
    bool switched = false;
2025
    /* We *could* leave in place a legacy interpreter here
2026
     * (one that shares obmalloc/GIL with main interp),
2027
     * but there isn't a big advantage, we anticipate
2028
     * such interpreters will be increasingly uncommon,
2029
     * and the code is a bit simpler if we always switch
2030
     * to the main interpreter. */
2031
383
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2032
383
    if (main_tstate == NULL) {
2033
0
        return NULL;
2034
0
    }
2035
383
    else if (main_tstate != tstate) {
2036
0
        switched = true;
2037
        /* In the switched case, we could play it safe
2038
         * by getting the main interpreter's import lock here.
2039
         * It's unlikely to matter though. */
2040
0
    }
2041
2042
383
    struct _Py_ext_module_loader_result res;
2043
383
    int rc = _PyImport_RunModInitFunc(p0, info, &res);
2044
383
    if (rc < 0) {
2045
        /* We discard res.def. */
2046
0
        assert(res.module == NULL);
2047
0
    }
2048
383
    else {
2049
383
        assert(!PyErr_Occurred());
2050
383
        assert(res.err == NULL);
2051
2052
383
        mod = res.module;
2053
383
        res.module = NULL;
2054
383
        def = res.def;
2055
383
        assert(def != NULL);
2056
2057
        /* Do anything else that should be done
2058
         * while still using the main interpreter. */
2059
383
        if (res.kind == _Py_ext_module_kind_SINGLEPHASE) {
2060
            /* Remember the filename as the __file__ attribute */
2061
0
            if (info->filename != NULL) {
2062
0
                PyObject *filename = NULL;
2063
0
                if (switched) {
2064
                    // The original filename may be allocated by subinterpreter's
2065
                    // obmalloc, so we create a copy here.
2066
0
                    filename = _PyUnicode_Copy(info->filename);
2067
0
                    if (filename == NULL) {
2068
0
                        return NULL;
2069
0
                    }
2070
0
                } else {
2071
0
                    filename = Py_NewRef(info->filename);
2072
0
                }
2073
                // XXX There's a refleak somewhere with the filename.
2074
                // Until we can track it down, we immortalize it.
2075
0
                PyInterpreterState *interp = _PyInterpreterState_GET();
2076
0
                _PyUnicode_InternImmortal(interp, &filename);
2077
2078
0
                if (PyModule_AddObjectRef(mod, "__file__", filename) < 0) {
2079
0
                    PyErr_Clear(); /* Not important enough to report */
2080
0
                }
2081
0
            }
2082
2083
            /* Update global import state. */
2084
0
            assert(def->m_base.m_index != 0);
2085
0
            struct singlephase_global_update singlephase = {
2086
                // XXX Modules that share a def should each get their own index,
2087
                // whereas currently they share (which means the per-interpreter
2088
                // cache is less reliable than it should be).
2089
0
                .m_index=def->m_base.m_index,
2090
0
                .origin=info->origin,
2091
#ifdef Py_GIL_DISABLED
2092
                .md_gil=((PyModuleObject *)mod)->md_gil,
2093
#endif
2094
0
            };
2095
            // gh-88216: Extensions and def->m_base.m_copy can be updated
2096
            // when the extension module doesn't support sub-interpreters.
2097
0
            if (def->m_size == -1) {
2098
                /* We will reload from m_copy. */
2099
0
                assert(def->m_base.m_init == NULL);
2100
0
                singlephase.m_dict = PyModule_GetDict(mod);
2101
0
                assert(singlephase.m_dict != NULL);
2102
0
            }
2103
0
            else {
2104
                /* We will reload via the init function. */
2105
0
                assert(def->m_size >= 0);
2106
0
                assert(def->m_base.m_copy == NULL);
2107
0
                singlephase.m_init = p0;
2108
0
            }
2109
0
            cached = update_global_state_for_extension(
2110
0
                    main_tstate, info->path, info->name, def, &singlephase);
2111
0
            if (cached == NULL) {
2112
0
                assert(PyErr_Occurred());
2113
0
                goto main_finally;
2114
0
            }
2115
0
        }
2116
383
    }
2117
2118
383
main_finally:
2119
    /* Switch back to the subinterpreter. */
2120
383
    if (switched) {
2121
0
        assert(main_tstate != tstate);
2122
0
        switch_back_from_main_interpreter(tstate, main_tstate, mod);
2123
        /* Any module we got from the init function will have to be
2124
         * reloaded in the subinterpreter. */
2125
0
        mod = NULL;
2126
0
    }
2127
2128
    /*****************************************************************/
2129
    /* At this point we are back to the interpreter we started with. */
2130
    /*****************************************************************/
2131
2132
    /* Finally we handle the error return from _PyImport_RunModInitFunc(). */
2133
383
    if (rc < 0) {
2134
0
        _Py_ext_module_loader_result_apply_error(&res, name_buf);
2135
0
        goto error;
2136
0
    }
2137
2138
383
    if (res.kind == _Py_ext_module_kind_MULTIPHASE) {
2139
383
        assert_multiphase_def(def);
2140
383
        assert(mod == NULL);
2141
        /* Note that we cheat a little by not repeating the calls
2142
         * to _PyImport_GetModInitFunc() and _PyImport_RunModInitFunc(). */
2143
383
        mod = PyModule_FromDefAndSpec(def, spec);
2144
383
        if (mod == NULL) {
2145
0
            goto error;
2146
0
        }
2147
383
    }
2148
0
    else {
2149
0
        assert(res.kind == _Py_ext_module_kind_SINGLEPHASE);
2150
0
        assert_singlephase_def(def);
2151
2152
0
        if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
2153
0
            goto error;
2154
0
        }
2155
0
        assert(!PyErr_Occurred());
2156
2157
0
        if (switched) {
2158
            /* We switched to the main interpreter to run the init
2159
             * function, so now we will "reload" the module from the
2160
             * cached data using the original subinterpreter. */
2161
0
            assert(mod == NULL);
2162
0
            mod = reload_singlephase_extension(tstate, cached, info);
2163
0
            if (mod == NULL) {
2164
0
                goto error;
2165
0
            }
2166
0
            assert(!PyErr_Occurred());
2167
0
            assert(PyModule_Check(mod));
2168
0
        }
2169
0
        else {
2170
0
            assert(mod != NULL);
2171
0
            assert(PyModule_Check(mod));
2172
2173
            /* Update per-interpreter import state. */
2174
0
            PyObject *modules = get_modules_dict(tstate, true);
2175
0
            if (finish_singlephase_extension(
2176
0
                    tstate, mod, cached, info->name, modules) < 0)
2177
0
            {
2178
0
                goto error;
2179
0
            }
2180
0
        }
2181
0
    }
2182
2183
383
    _Py_ext_module_loader_result_clear(&res);
2184
383
    return mod;
2185
2186
0
error:
2187
0
    Py_XDECREF(mod);
2188
0
    _Py_ext_module_loader_result_clear(&res);
2189
0
    return NULL;
2190
383
}
2191
2192
2193
// Used in _PyImport_ClearExtension; see notes there.
2194
static int
2195
clear_singlephase_extension(PyInterpreterState *interp,
2196
                            PyObject *name, PyObject *path)
2197
0
{
2198
0
    struct extensions_cache_value *cached = _extensions_cache_get(path, name);
2199
0
    if (cached == NULL) {
2200
0
        if (PyErr_Occurred()) {
2201
0
            return -1;
2202
0
        }
2203
0
        return 0;
2204
0
    }
2205
0
    PyModuleDef *def = cached->def;
2206
2207
    /* Clear data set when the module was initially loaded. */
2208
0
    def->m_base.m_init = NULL;
2209
0
    Py_CLEAR(def->m_base.m_copy);
2210
0
    def->m_base.m_index = 0;
2211
2212
    /* Clear the PyState_*Module() cache entry. */
2213
0
    Py_ssize_t index = _get_cached_module_index(cached);
2214
0
    if (_modules_by_index_check(interp, index) == NULL) {
2215
0
        if (_modules_by_index_clear_one(interp, index) < 0) {
2216
0
            return -1;
2217
0
        }
2218
0
    }
2219
2220
    /* We must use the main interpreter to clean up the cache.
2221
     * See the note in import_run_extension(). */
2222
0
    PyThreadState *tstate = PyThreadState_GET();
2223
0
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2224
0
    if (main_tstate == NULL) {
2225
0
        return -1;
2226
0
    }
2227
2228
    /* Clear the cached module def. */
2229
0
    _extensions_cache_delete(path, name);
2230
2231
0
    if (main_tstate != tstate) {
2232
0
        switch_back_from_main_interpreter(tstate, main_tstate, NULL);
2233
0
    }
2234
2235
0
    return 0;
2236
0
}
2237
2238
2239
/*******************/
2240
/* builtin modules */
2241
/*******************/
2242
2243
int
2244
_PyImport_FixupBuiltin(PyThreadState *tstate, PyObject *mod, const char *name,
2245
                       PyObject *modules)
2246
32
{
2247
32
    int res = -1;
2248
32
    assert(mod != NULL && PyModule_Check(mod));
2249
2250
32
    PyObject *nameobj;
2251
32
    nameobj = PyUnicode_InternFromString(name);
2252
32
    if (nameobj == NULL) {
2253
0
        return -1;
2254
0
    }
2255
2256
32
    PyModuleDef *def = PyModule_GetDef(mod);
2257
32
    if (def == NULL) {
2258
0
        PyErr_BadInternalCall();
2259
0
        goto finally;
2260
0
    }
2261
2262
    /* We only use _PyImport_FixupBuiltin() for the core builtin modules
2263
     * (sys and builtins).  These modules are single-phase init with no
2264
     * module state, but we also don't populate def->m_base.m_copy
2265
     * for them. */
2266
32
    assert(is_core_module(tstate->interp, nameobj, nameobj));
2267
32
    assert_singlephase_def(def);
2268
32
    assert(def->m_size == -1);
2269
32
    assert(def->m_base.m_copy == NULL);
2270
32
    assert(def->m_base.m_index >= 0);
2271
2272
    /* We aren't using import_find_extension() for core modules,
2273
     * so we have to do the extra check to make sure the module
2274
     * isn't already in the global cache before calling
2275
     * update_global_state_for_extension(). */
2276
32
    struct extensions_cache_value *cached
2277
32
            = _extensions_cache_get(nameobj, nameobj);
2278
32
    if (cached == NULL) {
2279
32
        struct singlephase_global_update singlephase = {
2280
32
            .m_index=def->m_base.m_index,
2281
            /* We don't want def->m_base.m_copy populated. */
2282
32
            .m_dict=NULL,
2283
32
            .origin=_Py_ext_module_origin_CORE,
2284
#ifdef Py_GIL_DISABLED
2285
            /* Unused when m_dict == NULL. */
2286
            .md_gil=NULL,
2287
#endif
2288
32
        };
2289
32
        cached = update_global_state_for_extension(
2290
32
                tstate, nameobj, nameobj, def, &singlephase);
2291
32
        if (cached == NULL) {
2292
0
            goto finally;
2293
0
        }
2294
32
    }
2295
2296
32
    if (finish_singlephase_extension(tstate, mod, cached, nameobj, modules) < 0) {
2297
0
        goto finally;
2298
0
    }
2299
2300
32
    res = 0;
2301
2302
32
finally:
2303
32
    Py_DECREF(nameobj);
2304
32
    return res;
2305
32
}
2306
2307
/* Helper to test for built-in module */
2308
2309
static int
2310
is_builtin(PyObject *name)
2311
2.70k
{
2312
2.70k
    int i;
2313
2.70k
    struct _inittab *inittab = INITTAB;
2314
99.4k
    for (i = 0; inittab[i].name != NULL; i++) {
2315
97.0k
        if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
2316
294
            if (inittab[i].initfunc == NULL)
2317
0
                return -1;
2318
294
            else
2319
294
                return 1;
2320
294
        }
2321
97.0k
    }
2322
2.41k
    return 0;
2323
2.70k
}
2324
2325
static PyObject*
2326
create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
2327
310
{
2328
310
    struct _Py_ext_module_loader_info info;
2329
310
    if (_Py_ext_module_loader_info_init_for_builtin(&info, name) < 0) {
2330
0
        return NULL;
2331
0
    }
2332
2333
310
    struct extensions_cache_value *cached = NULL;
2334
310
    PyObject *mod = import_find_extension(tstate, &info, &cached);
2335
310
    if (mod != NULL) {
2336
0
        assert(!_PyErr_Occurred(tstate));
2337
0
        assert(cached != NULL);
2338
        /* The module might not have md_def set in certain reload cases. */
2339
0
        assert(_PyModule_GetDef(mod) == NULL
2340
0
                || cached->def == _PyModule_GetDef(mod));
2341
0
        assert_singlephase(cached);
2342
0
        goto finally;
2343
0
    }
2344
310
    else if (_PyErr_Occurred(tstate)) {
2345
0
        goto finally;
2346
0
    }
2347
2348
    /* If the module was added to the global cache
2349
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
2350
     * then we have to do a little dance here. */
2351
310
    if (cached != NULL) {
2352
0
        assert(cached->def->m_base.m_copy == NULL);
2353
        /* For now we clear the cache and move on. */
2354
0
        _extensions_cache_delete(info.path, info.name);
2355
0
    }
2356
2357
310
    struct _inittab *found = NULL;
2358
12.0k
    for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
2359
11.7k
        if (_PyUnicode_EqualToASCIIString(info.name, p->name)) {
2360
310
            found = p;
2361
310
        }
2362
11.7k
    }
2363
310
    if (found == NULL) {
2364
        // not found
2365
0
        mod = Py_NewRef(Py_None);
2366
0
        goto finally;
2367
0
    }
2368
2369
310
    PyModInitFunction p0 = (PyModInitFunction)found->initfunc;
2370
310
    if (p0 == NULL) {
2371
        /* Cannot re-init internal module ("sys" or "builtins") */
2372
0
        assert(is_core_module(tstate->interp, info.name, info.path));
2373
0
        mod = import_add_module(tstate, info.name);
2374
0
        goto finally;
2375
0
    }
2376
2377
#ifdef Py_GIL_DISABLED
2378
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
2379
    // would ideally be inside import_run_extension(). They are kept in the
2380
    // callers for now because that would complicate the control flow inside
2381
    // import_run_extension(). It should be possible to restructure
2382
    // import_run_extension() to address this.
2383
    _PyEval_EnableGILTransient(tstate);
2384
#endif
2385
    /* Now load it. */
2386
310
    mod = import_run_extension(
2387
310
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
2388
#ifdef Py_GIL_DISABLED
2389
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
2390
        Py_CLEAR(mod);
2391
        goto finally;
2392
    }
2393
#endif
2394
2395
310
finally:
2396
310
    _Py_ext_module_loader_info_clear(&info);
2397
310
    return mod;
2398
310
}
2399
2400
2401
/*****************************/
2402
/* the builtin modules table */
2403
/*****************************/
2404
2405
/* API for embedding applications that want to add their own entries
2406
   to the table of built-in modules.  This should normally be called
2407
   *before* Py_Initialize().  When the table resize fails, -1 is
2408
   returned and the existing table is unchanged.
2409
2410
   After a similar function by Just van Rossum. */
2411
2412
int
2413
PyImport_ExtendInittab(struct _inittab *newtab)
2414
0
{
2415
0
    struct _inittab *p;
2416
0
    size_t i, n;
2417
0
    int res = 0;
2418
2419
0
    if (INITTAB != NULL) {
2420
0
        Py_FatalError("PyImport_ExtendInittab() may not be called after Py_Initialize()");
2421
0
    }
2422
2423
    /* Count the number of entries in both tables */
2424
0
    for (n = 0; newtab[n].name != NULL; n++)
2425
0
        ;
2426
0
    if (n == 0)
2427
0
        return 0; /* Nothing to do */
2428
0
    for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2429
0
        ;
2430
2431
    /* Force default raw memory allocator to get a known allocator to be able
2432
       to release the memory in _PyImport_Fini2() */
2433
    /* Allocate new memory for the combined table */
2434
0
    p = NULL;
2435
0
    if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
2436
0
        size_t size = sizeof(struct _inittab) * (i + n + 1);
2437
0
        p = _PyMem_DefaultRawRealloc(inittab_copy, size);
2438
0
    }
2439
0
    if (p == NULL) {
2440
0
        res = -1;
2441
0
        goto done;
2442
0
    }
2443
2444
    /* Copy the tables into the new memory at the first call
2445
       to PyImport_ExtendInittab(). */
2446
0
    if (inittab_copy != PyImport_Inittab) {
2447
0
        memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2448
0
    }
2449
0
    memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2450
0
    PyImport_Inittab = inittab_copy = p;
2451
0
done:
2452
0
    return res;
2453
0
}
2454
2455
/* Shorthand to add a single entry given a name and a function */
2456
2457
int
2458
PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
2459
0
{
2460
0
    struct _inittab newtab[2];
2461
2462
0
    if (INITTAB != NULL) {
2463
0
        Py_FatalError("PyImport_AppendInittab() may not be called after Py_Initialize()");
2464
0
    }
2465
2466
0
    memset(newtab, '\0', sizeof newtab);
2467
2468
0
    newtab[0].name = name;
2469
0
    newtab[0].initfunc = initfunc;
2470
2471
0
    return PyImport_ExtendInittab(newtab);
2472
0
}
2473
2474
2475
/* the internal table */
2476
2477
static int
2478
init_builtin_modules_table(void)
2479
16
{
2480
16
    size_t size;
2481
624
    for (size = 0; PyImport_Inittab[size].name != NULL; size++)
2482
608
        ;
2483
16
    size++;
2484
2485
    /* Make the copy. */
2486
16
    struct _inittab *copied = _PyMem_DefaultRawMalloc(size * sizeof(struct _inittab));
2487
16
    if (copied == NULL) {
2488
0
        return -1;
2489
0
    }
2490
16
    memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
2491
16
    INITTAB = copied;
2492
16
    return 0;
2493
16
}
2494
2495
static void
2496
fini_builtin_modules_table(void)
2497
0
{
2498
0
    struct _inittab *inittab = INITTAB;
2499
0
    INITTAB = NULL;
2500
0
    _PyMem_DefaultRawFree(inittab);
2501
0
}
2502
2503
PyObject *
2504
_PyImport_GetBuiltinModuleNames(void)
2505
16
{
2506
16
    PyObject *list = PyList_New(0);
2507
16
    if (list == NULL) {
2508
0
        return NULL;
2509
0
    }
2510
16
    struct _inittab *inittab = INITTAB;
2511
624
    for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
2512
608
        PyObject *name = PyUnicode_FromString(inittab[i].name);
2513
608
        if (name == NULL) {
2514
0
            Py_DECREF(list);
2515
0
            return NULL;
2516
0
        }
2517
608
        if (PyList_Append(list, name) < 0) {
2518
0
            Py_DECREF(name);
2519
0
            Py_DECREF(list);
2520
0
            return NULL;
2521
0
        }
2522
608
        Py_DECREF(name);
2523
608
    }
2524
16
    return list;
2525
16
}
2526
2527
2528
/********************/
2529
/* the magic number */
2530
/********************/
2531
2532
/* Helper for pythonrun.c -- return magic number and tag. */
2533
2534
long
2535
PyImport_GetMagicNumber(void)
2536
0
{
2537
0
    return PYC_MAGIC_NUMBER_TOKEN;
2538
0
}
2539
2540
extern const char * _PySys_ImplCacheTag;
2541
2542
const char *
2543
PyImport_GetMagicTag(void)
2544
0
{
2545
0
    return _PySys_ImplCacheTag;
2546
0
}
2547
2548
2549
/*********************************/
2550
/* a Python module's code object */
2551
/*********************************/
2552
2553
/* Execute a code object in a module and return the module object
2554
 * WITH INCREMENTED REFERENCE COUNT.  If an error occurs, name is
2555
 * removed from sys.modules, to avoid leaving damaged module objects
2556
 * in sys.modules.  The caller may wish to restore the original
2557
 * module object (if any) in this case; PyImport_ReloadModule is an
2558
 * example.
2559
 *
2560
 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
2561
 * interface.  The other two exist primarily for backward compatibility.
2562
 */
2563
PyObject *
2564
PyImport_ExecCodeModule(const char *name, PyObject *co)
2565
0
{
2566
0
    return PyImport_ExecCodeModuleWithPathnames(
2567
0
        name, co, (char *)NULL, (char *)NULL);
2568
0
}
2569
2570
PyObject *
2571
PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
2572
0
{
2573
0
    return PyImport_ExecCodeModuleWithPathnames(
2574
0
        name, co, pathname, (char *)NULL);
2575
0
}
2576
2577
PyObject *
2578
PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
2579
                                     const char *pathname,
2580
                                     const char *cpathname)
2581
0
{
2582
0
    PyObject *m = NULL;
2583
0
    PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
2584
2585
0
    nameobj = PyUnicode_FromString(name);
2586
0
    if (nameobj == NULL)
2587
0
        return NULL;
2588
2589
0
    if (cpathname != NULL) {
2590
0
        cpathobj = PyUnicode_DecodeFSDefault(cpathname);
2591
0
        if (cpathobj == NULL)
2592
0
            goto error;
2593
0
    }
2594
0
    else
2595
0
        cpathobj = NULL;
2596
2597
0
    if (pathname != NULL) {
2598
0
        pathobj = PyUnicode_DecodeFSDefault(pathname);
2599
0
        if (pathobj == NULL)
2600
0
            goto error;
2601
0
    }
2602
0
    else if (cpathobj != NULL) {
2603
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
2604
2605
0
        if (interp == NULL) {
2606
0
            Py_FatalError("no current interpreter");
2607
0
        }
2608
2609
0
        external= PyObject_GetAttrString(IMPORTLIB(interp),
2610
0
                                         "_bootstrap_external");
2611
0
        if (external != NULL) {
2612
0
            pathobj = PyObject_CallMethodOneArg(
2613
0
                external, &_Py_ID(_get_sourcefile), cpathobj);
2614
0
            Py_DECREF(external);
2615
0
        }
2616
0
        if (pathobj == NULL)
2617
0
            PyErr_Clear();
2618
0
    }
2619
0
    else
2620
0
        pathobj = NULL;
2621
2622
0
    m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
2623
0
error:
2624
0
    Py_DECREF(nameobj);
2625
0
    Py_XDECREF(pathobj);
2626
0
    Py_XDECREF(cpathobj);
2627
0
    return m;
2628
0
}
2629
2630
static PyObject *
2631
module_dict_for_exec(PyThreadState *tstate, PyObject *name)
2632
16
{
2633
16
    PyObject *m, *d;
2634
2635
16
    m = import_add_module(tstate, name);
2636
16
    if (m == NULL)
2637
0
        return NULL;
2638
    /* If the module is being reloaded, we get the old module back
2639
       and re-use its dict to exec the new code. */
2640
16
    d = PyModule_GetDict(m);
2641
16
    int r = PyDict_Contains(d, &_Py_ID(__builtins__));
2642
16
    if (r == 0) {
2643
16
        r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
2644
16
    }
2645
16
    if (r < 0) {
2646
0
        remove_module(tstate, name);
2647
0
        Py_DECREF(m);
2648
0
        return NULL;
2649
0
    }
2650
2651
16
    Py_INCREF(d);
2652
16
    Py_DECREF(m);
2653
16
    return d;
2654
16
}
2655
2656
static PyObject *
2657
exec_code_in_module(PyThreadState *tstate, PyObject *name,
2658
                    PyObject *module_dict, PyObject *code_object)
2659
16
{
2660
16
    PyObject *v, *m;
2661
2662
16
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
2663
16
    if (v == NULL) {
2664
0
        remove_module(tstate, name);
2665
0
        return NULL;
2666
0
    }
2667
16
    Py_DECREF(v);
2668
2669
16
    m = import_get_module(tstate, name);
2670
16
    if (m == NULL && !_PyErr_Occurred(tstate)) {
2671
0
        _PyErr_Format(tstate, PyExc_ImportError,
2672
0
                      "Loaded module %R not found in sys.modules",
2673
0
                      name);
2674
0
    }
2675
2676
16
    return m;
2677
16
}
2678
2679
PyObject*
2680
PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
2681
                              PyObject *cpathname)
2682
0
{
2683
0
    PyThreadState *tstate = _PyThreadState_GET();
2684
0
    PyObject *d, *external, *res;
2685
2686
0
    d = module_dict_for_exec(tstate, name);
2687
0
    if (d == NULL) {
2688
0
        return NULL;
2689
0
    }
2690
2691
0
    if (pathname == NULL) {
2692
0
        pathname = ((PyCodeObject *)co)->co_filename;
2693
0
    }
2694
0
    external = PyObject_GetAttrString(IMPORTLIB(tstate->interp),
2695
0
                                      "_bootstrap_external");
2696
0
    if (external == NULL) {
2697
0
        Py_DECREF(d);
2698
0
        return NULL;
2699
0
    }
2700
0
    res = PyObject_CallMethodObjArgs(external, &_Py_ID(_fix_up_module),
2701
0
                                     d, name, pathname, cpathname, NULL);
2702
0
    Py_DECREF(external);
2703
0
    if (res != NULL) {
2704
0
        Py_DECREF(res);
2705
0
        res = exec_code_in_module(tstate, name, d, co);
2706
0
    }
2707
0
    Py_DECREF(d);
2708
0
    return res;
2709
0
}
2710
2711
2712
static void
2713
update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
2714
0
{
2715
0
    PyObject *constants, *tmp;
2716
0
    Py_ssize_t i, n;
2717
2718
0
    if (PyUnicode_Compare(co->co_filename, oldname))
2719
0
        return;
2720
2721
0
    Py_XSETREF(co->co_filename, Py_NewRef(newname));
2722
2723
0
    constants = co->co_consts;
2724
0
    n = PyTuple_GET_SIZE(constants);
2725
0
    for (i = 0; i < n; i++) {
2726
0
        tmp = PyTuple_GET_ITEM(constants, i);
2727
0
        if (PyCode_Check(tmp))
2728
0
            update_code_filenames((PyCodeObject *)tmp,
2729
0
                                  oldname, newname);
2730
0
    }
2731
0
}
2732
2733
static void
2734
update_compiled_module(PyCodeObject *co, PyObject *newname)
2735
531
{
2736
531
    PyObject *oldname;
2737
2738
531
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2739
531
        return;
2740
2741
0
    oldname = co->co_filename;
2742
0
    Py_INCREF(oldname);
2743
0
    update_code_filenames(co, oldname, newname);
2744
0
    Py_DECREF(oldname);
2745
0
}
2746
2747
2748
/******************/
2749
/* frozen modules */
2750
/******************/
2751
2752
/* Return true if the name is an alias.  In that case, "alias" is set
2753
   to the original module name.  If it is an alias but the original
2754
   module isn't known then "alias" is set to NULL while true is returned. */
2755
static bool
2756
resolve_module_alias(const char *name, const struct _module_alias *aliases,
2757
                     const char **alias)
2758
428
{
2759
428
    const struct _module_alias *entry;
2760
3.24k
    for (entry = aliases; ; entry++) {
2761
3.24k
        if (entry->name == NULL) {
2762
            /* It isn't an alias. */
2763
348
            return false;
2764
348
        }
2765
2.89k
        if (strcmp(name, entry->name) == 0) {
2766
80
            if (alias != NULL) {
2767
80
                *alias = entry->orig;
2768
80
            }
2769
80
            return true;
2770
80
        }
2771
2.89k
    }
2772
428
}
2773
2774
static bool
2775
use_frozen(void)
2776
2.53k
{
2777
2.53k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2778
2.53k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2779
2.53k
    if (override > 0) {
2780
0
        return true;
2781
0
    }
2782
2.53k
    else if (override < 0) {
2783
0
        return false;
2784
0
    }
2785
2.53k
    else {
2786
2.53k
        return interp->config.use_frozen_modules;
2787
2.53k
    }
2788
2.53k
}
2789
2790
static PyObject *
2791
list_frozen_module_names(void)
2792
0
{
2793
0
    PyObject *names = PyList_New(0);
2794
0
    if (names == NULL) {
2795
0
        return NULL;
2796
0
    }
2797
0
    bool enabled = use_frozen();
2798
0
    const struct _frozen *p;
2799
0
#define ADD_MODULE(name) \
2800
0
    do { \
2801
0
        PyObject *nameobj = PyUnicode_FromString(name); \
2802
0
        if (nameobj == NULL) { \
2803
0
            goto error; \
2804
0
        } \
2805
0
        int res = PyList_Append(names, nameobj); \
2806
0
        Py_DECREF(nameobj); \
2807
0
        if (res != 0) { \
2808
0
            goto error; \
2809
0
        } \
2810
0
    } while(0)
2811
    // We always use the bootstrap modules.
2812
0
    for (p = _PyImport_FrozenBootstrap; ; p++) {
2813
0
        if (p->name == NULL) {
2814
0
            break;
2815
0
        }
2816
0
        ADD_MODULE(p->name);
2817
0
    }
2818
    // Frozen stdlib modules may be disabled.
2819
0
    for (p = _PyImport_FrozenStdlib; ; p++) {
2820
0
        if (p->name == NULL) {
2821
0
            break;
2822
0
        }
2823
0
        if (enabled) {
2824
0
            ADD_MODULE(p->name);
2825
0
        }
2826
0
    }
2827
0
    for (p = _PyImport_FrozenTest; ; p++) {
2828
0
        if (p->name == NULL) {
2829
0
            break;
2830
0
        }
2831
0
        if (enabled) {
2832
0
            ADD_MODULE(p->name);
2833
0
        }
2834
0
    }
2835
0
#undef ADD_MODULE
2836
    // Add any custom modules.
2837
0
    if (PyImport_FrozenModules != NULL) {
2838
0
        for (p = PyImport_FrozenModules; ; p++) {
2839
0
            if (p->name == NULL) {
2840
0
                break;
2841
0
            }
2842
0
            PyObject *nameobj = PyUnicode_FromString(p->name);
2843
0
            if (nameobj == NULL) {
2844
0
                goto error;
2845
0
            }
2846
0
            int found = PySequence_Contains(names, nameobj);
2847
0
            if (found < 0) {
2848
0
                Py_DECREF(nameobj);
2849
0
                goto error;
2850
0
            }
2851
0
            else if (found) {
2852
0
                Py_DECREF(nameobj);
2853
0
            }
2854
0
            else {
2855
0
                int res = PyList_Append(names, nameobj);
2856
0
                Py_DECREF(nameobj);
2857
0
                if (res != 0) {
2858
0
                    goto error;
2859
0
                }
2860
0
            }
2861
0
        }
2862
0
    }
2863
0
    return names;
2864
2865
0
error:
2866
0
    Py_DECREF(names);
2867
0
    return NULL;
2868
0
}
2869
2870
typedef enum {
2871
    FROZEN_OKAY,
2872
    FROZEN_BAD_NAME,    // The given module name wasn't valid.
2873
    FROZEN_NOT_FOUND,   // It wasn't in PyImport_FrozenModules.
2874
    FROZEN_DISABLED,    // -X frozen_modules=off (and not essential)
2875
    FROZEN_EXCLUDED,    /* The PyImport_FrozenModules entry has NULL "code"
2876
                           (module is present but marked as unimportable, stops search). */
2877
    FROZEN_INVALID,     /* The PyImport_FrozenModules entry is bogus
2878
                           (eg. does not contain executable code). */
2879
} frozen_status;
2880
2881
static inline void
2882
set_frozen_error(frozen_status status, PyObject *modname)
2883
0
{
2884
0
    const char *err = NULL;
2885
0
    switch (status) {
2886
0
        case FROZEN_BAD_NAME:
2887
0
        case FROZEN_NOT_FOUND:
2888
0
            err = "No such frozen object named %R";
2889
0
            break;
2890
0
        case FROZEN_DISABLED:
2891
0
            err = "Frozen modules are disabled and the frozen object named %R is not essential";
2892
0
            break;
2893
0
        case FROZEN_EXCLUDED:
2894
0
            err = "Excluded frozen object named %R";
2895
0
            break;
2896
0
        case FROZEN_INVALID:
2897
0
            err = "Frozen object named %R is invalid";
2898
0
            break;
2899
0
        case FROZEN_OKAY:
2900
            // There was no error.
2901
0
            break;
2902
0
        default:
2903
0
            Py_UNREACHABLE();
2904
0
    }
2905
0
    if (err != NULL) {
2906
0
        PyObject *msg = PyUnicode_FromFormat(err, modname);
2907
0
        if (msg == NULL) {
2908
0
            PyErr_Clear();
2909
0
        }
2910
0
        PyErr_SetImportError(msg, modname, NULL);
2911
0
        Py_XDECREF(msg);
2912
0
    }
2913
0
}
2914
2915
static const struct _frozen *
2916
look_up_frozen(const char *name)
2917
2.65k
{
2918
2.65k
    const struct _frozen *p;
2919
    // We always use the bootstrap modules.
2920
10.3k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
2921
10.3k
        if (p->name == NULL) {
2922
            // We hit the end-of-list sentinel value.
2923
2.53k
            break;
2924
2.53k
        }
2925
7.82k
        if (strcmp(name, p->name) == 0) {
2926
112
            return p;
2927
112
        }
2928
7.82k
    }
2929
    // Prefer custom modules, if any.  Frozen stdlib modules can be
2930
    // disabled here by setting "code" to NULL in the array entry.
2931
2.53k
    if (PyImport_FrozenModules != NULL) {
2932
0
        for (p = PyImport_FrozenModules; ; p++) {
2933
0
            if (p->name == NULL) {
2934
0
                break;
2935
0
            }
2936
0
            if (strcmp(name, p->name) == 0) {
2937
0
                return p;
2938
0
            }
2939
0
        }
2940
0
    }
2941
    // Frozen stdlib modules may be disabled.
2942
2.53k
    if (use_frozen()) {
2943
35.2k
        for (p = _PyImport_FrozenStdlib; ; p++) {
2944
35.2k
            if (p->name == NULL) {
2945
2.22k
                break;
2946
2.22k
            }
2947
33.0k
            if (strcmp(name, p->name) == 0) {
2948
316
                return p;
2949
316
            }
2950
33.0k
        }
2951
26.6k
        for (p = _PyImport_FrozenTest; ; p++) {
2952
26.6k
            if (p->name == NULL) {
2953
2.22k
                break;
2954
2.22k
            }
2955
24.4k
            if (strcmp(name, p->name) == 0) {
2956
0
                return p;
2957
0
            }
2958
24.4k
        }
2959
2.22k
    }
2960
2.22k
    return NULL;
2961
2.53k
}
2962
2963
struct frozen_info {
2964
    PyObject *nameobj;
2965
    const char *data;
2966
    Py_ssize_t size;
2967
    bool is_package;
2968
    bool is_alias;
2969
    const char *origname;
2970
};
2971
2972
static frozen_status
2973
find_frozen(PyObject *nameobj, struct frozen_info *info)
2974
2.65k
{
2975
2.65k
    if (info != NULL) {
2976
2.65k
        memset(info, 0, sizeof(*info));
2977
2.65k
    }
2978
2979
2.65k
    if (nameobj == NULL || nameobj == Py_None) {
2980
0
        return FROZEN_BAD_NAME;
2981
0
    }
2982
2.65k
    const char *name = PyUnicode_AsUTF8(nameobj);
2983
2.65k
    if (name == NULL) {
2984
        // Note that this function previously used
2985
        // _PyUnicode_EqualToASCIIString().  We clear the error here
2986
        // (instead of propagating it) to match the earlier behavior
2987
        // more closely.
2988
0
        PyErr_Clear();
2989
0
        return FROZEN_BAD_NAME;
2990
0
    }
2991
2992
2.65k
    const struct _frozen *p = look_up_frozen(name);
2993
2.65k
    if (p == NULL) {
2994
2.22k
        return FROZEN_NOT_FOUND;
2995
2.22k
    }
2996
428
    if (info != NULL) {
2997
428
        info->nameobj = nameobj;  // borrowed
2998
428
        info->data = (const char *)p->code;
2999
428
        info->size = p->size;
3000
428
        info->is_package = p->is_package;
3001
428
        if (p->size < 0) {
3002
            // backward compatibility with negative size values
3003
0
            info->size = -(p->size);
3004
0
            info->is_package = true;
3005
0
        }
3006
428
        info->origname = name;
3007
428
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3008
428
                                              &info->origname);
3009
428
    }
3010
428
    if (p->code == NULL) {
3011
        /* It is frozen but marked as un-importable. */
3012
0
        return FROZEN_EXCLUDED;
3013
0
    }
3014
428
    if (p->code[0] == '\0' || p->size == 0) {
3015
        /* Does not contain executable code. */
3016
0
        return FROZEN_INVALID;
3017
0
    }
3018
428
    return FROZEN_OKAY;
3019
428
}
3020
3021
static PyObject *
3022
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3023
206
{
3024
206
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3025
206
    if (co == NULL) {
3026
        /* Does not contain executable code. */
3027
0
        PyErr_Clear();
3028
0
        set_frozen_error(FROZEN_INVALID, info->nameobj);
3029
0
        return NULL;
3030
0
    }
3031
206
    if (!PyCode_Check(co)) {
3032
        // We stick with TypeError for backward compatibility.
3033
0
        PyErr_Format(PyExc_TypeError,
3034
0
                     "frozen object %R is not a code object",
3035
0
                     info->nameobj);
3036
0
        Py_DECREF(co);
3037
0
        return NULL;
3038
0
    }
3039
206
    return co;
3040
206
}
3041
3042
3043
/* Initialize a frozen module.
3044
   Return 1 for success, 0 if the module is not found, and -1 with
3045
   an exception set if the initialization failed.
3046
   This function is also used from frozenmain.c */
3047
3048
int
3049
PyImport_ImportFrozenModuleObject(PyObject *name)
3050
16
{
3051
16
    PyThreadState *tstate = _PyThreadState_GET();
3052
16
    PyObject *co, *m, *d = NULL;
3053
16
    int err;
3054
3055
16
    struct frozen_info info;
3056
16
    frozen_status status = find_frozen(name, &info);
3057
16
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3058
0
        return 0;
3059
0
    }
3060
16
    else if (status == FROZEN_BAD_NAME) {
3061
0
        return 0;
3062
0
    }
3063
16
    else if (status != FROZEN_OKAY) {
3064
0
        set_frozen_error(status, name);
3065
0
        return -1;
3066
0
    }
3067
16
    co = unmarshal_frozen_code(tstate->interp, &info);
3068
16
    if (co == NULL) {
3069
0
        return -1;
3070
0
    }
3071
16
    if (info.is_package) {
3072
        /* Set __path__ to the empty list */
3073
0
        PyObject *l;
3074
0
        m = import_add_module(tstate, name);
3075
0
        if (m == NULL)
3076
0
            goto err_return;
3077
0
        d = PyModule_GetDict(m);
3078
0
        l = PyList_New(0);
3079
0
        if (l == NULL) {
3080
0
            Py_DECREF(m);
3081
0
            goto err_return;
3082
0
        }
3083
0
        err = PyDict_SetItemString(d, "__path__", l);
3084
0
        Py_DECREF(l);
3085
0
        Py_DECREF(m);
3086
0
        if (err != 0)
3087
0
            goto err_return;
3088
0
    }
3089
16
    d = module_dict_for_exec(tstate, name);
3090
16
    if (d == NULL) {
3091
0
        goto err_return;
3092
0
    }
3093
16
    m = exec_code_in_module(tstate, name, d, co);
3094
16
    if (m == NULL) {
3095
0
        goto err_return;
3096
0
    }
3097
16
    Py_DECREF(m);
3098
    /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
3099
16
    PyObject *origname;
3100
16
    if (info.origname) {
3101
16
        origname = PyUnicode_FromString(info.origname);
3102
16
        if (origname == NULL) {
3103
0
            goto err_return;
3104
0
        }
3105
16
    }
3106
0
    else {
3107
0
        origname = Py_NewRef(Py_None);
3108
0
    }
3109
16
    err = PyDict_SetItemString(d, "__origname__", origname);
3110
16
    Py_DECREF(origname);
3111
16
    if (err != 0) {
3112
0
        goto err_return;
3113
0
    }
3114
16
    Py_DECREF(d);
3115
16
    Py_DECREF(co);
3116
16
    return 1;
3117
3118
0
err_return:
3119
0
    Py_XDECREF(d);
3120
0
    Py_DECREF(co);
3121
0
    return -1;
3122
16
}
3123
3124
int
3125
PyImport_ImportFrozenModule(const char *name)
3126
16
{
3127
16
    PyObject *nameobj;
3128
16
    int ret;
3129
16
    nameobj = PyUnicode_InternFromString(name);
3130
16
    if (nameobj == NULL)
3131
0
        return -1;
3132
16
    ret = PyImport_ImportFrozenModuleObject(nameobj);
3133
16
    Py_DECREF(nameobj);
3134
16
    return ret;
3135
16
}
3136
3137
3138
/*************/
3139
/* importlib */
3140
/*************/
3141
3142
/* Import the _imp extension by calling manually _imp.create_builtin() and
3143
   _imp.exec_builtin() since importlib is not initialized yet. Initializing
3144
   importlib requires the _imp module: this function fix the bootstrap issue.
3145
 */
3146
static PyObject*
3147
bootstrap_imp(PyThreadState *tstate)
3148
16
{
3149
16
    PyObject *name = PyUnicode_FromString("_imp");
3150
16
    if (name == NULL) {
3151
0
        return NULL;
3152
0
    }
3153
3154
    // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
3155
    // an object with just a name attribute.
3156
    //
3157
    // _imp.__spec__ is overridden by importlib._bootstrap._instal() anyway.
3158
16
    PyObject *attrs = Py_BuildValue("{sO}", "name", name);
3159
16
    if (attrs == NULL) {
3160
0
        goto error;
3161
0
    }
3162
16
    PyObject *spec = _PyNamespace_New(attrs);
3163
16
    Py_DECREF(attrs);
3164
16
    if (spec == NULL) {
3165
0
        goto error;
3166
0
    }
3167
3168
    // Create the _imp module from its definition.
3169
16
    PyObject *mod = create_builtin(tstate, name, spec);
3170
16
    Py_CLEAR(name);
3171
16
    Py_DECREF(spec);
3172
16
    if (mod == NULL) {
3173
0
        goto error;
3174
0
    }
3175
16
    assert(mod != Py_None);  // not found
3176
3177
    // Execute the _imp module: call imp_module_exec().
3178
16
    if (exec_builtin_or_dynamic(mod) < 0) {
3179
0
        Py_DECREF(mod);
3180
0
        goto error;
3181
0
    }
3182
16
    return mod;
3183
3184
0
error:
3185
0
    Py_XDECREF(name);
3186
0
    return NULL;
3187
16
}
3188
3189
/* Global initializations.  Can be undone by Py_FinalizeEx().  Don't
3190
   call this twice without an intervening Py_FinalizeEx() call.  When
3191
   initializations fail, a fatal error is issued and the function does
3192
   not return.  On return, the first thread and interpreter state have
3193
   been created.
3194
3195
   Locking: you must hold the interpreter lock while calling this.
3196
   (If the lock has not yet been initialized, that's equivalent to
3197
   having the lock, but you cannot use multiple threads.)
3198
3199
*/
3200
static int
3201
init_importlib(PyThreadState *tstate, PyObject *sysmod)
3202
16
{
3203
16
    assert(!_PyErr_Occurred(tstate));
3204
3205
16
    PyInterpreterState *interp = tstate->interp;
3206
16
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3207
3208
    // Import _importlib through its frozen version, _frozen_importlib.
3209
16
    if (verbose) {
3210
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
3211
0
    }
3212
16
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
3213
0
        return -1;
3214
0
    }
3215
3216
16
    PyObject *importlib = PyImport_AddModuleRef("_frozen_importlib");
3217
16
    if (importlib == NULL) {
3218
0
        return -1;
3219
0
    }
3220
16
    IMPORTLIB(interp) = importlib;
3221
3222
    // Import the _imp module
3223
16
    if (verbose) {
3224
0
        PySys_FormatStderr("import _imp # builtin\n");
3225
0
    }
3226
16
    PyObject *imp_mod = bootstrap_imp(tstate);
3227
16
    if (imp_mod == NULL) {
3228
0
        return -1;
3229
0
    }
3230
16
    if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
3231
0
        Py_DECREF(imp_mod);
3232
0
        return -1;
3233
0
    }
3234
3235
    // Install importlib as the implementation of import
3236
16
    PyObject *value = PyObject_CallMethod(importlib, "_install",
3237
16
                                          "OO", sysmod, imp_mod);
3238
16
    Py_DECREF(imp_mod);
3239
16
    if (value == NULL) {
3240
0
        return -1;
3241
0
    }
3242
16
    Py_DECREF(value);
3243
3244
16
    assert(!_PyErr_Occurred(tstate));
3245
16
    return 0;
3246
16
}
3247
3248
3249
static int
3250
init_importlib_external(PyInterpreterState *interp)
3251
16
{
3252
16
    PyObject *value;
3253
16
    value = PyObject_CallMethod(IMPORTLIB(interp),
3254
16
                                "_install_external_importers", "");
3255
16
    if (value == NULL) {
3256
0
        return -1;
3257
0
    }
3258
16
    Py_DECREF(value);
3259
16
    return 0;
3260
16
}
3261
3262
PyObject *
3263
_PyImport_GetImportlibLoader(PyInterpreterState *interp,
3264
                             const char *loader_name)
3265
16
{
3266
16
    return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
3267
16
}
3268
3269
PyObject *
3270
_PyImport_GetImportlibExternalLoader(PyInterpreterState *interp,
3271
                                     const char *loader_name)
3272
0
{
3273
0
    PyObject *bootstrap = PyObject_GetAttrString(IMPORTLIB(interp),
3274
0
                                                 "_bootstrap_external");
3275
0
    if (bootstrap == NULL) {
3276
0
        return NULL;
3277
0
    }
3278
3279
0
    PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
3280
0
    Py_DECREF(bootstrap);
3281
0
    return loader_type;
3282
0
}
3283
3284
PyObject *
3285
_PyImport_BlessMyLoader(PyInterpreterState *interp, PyObject *module_globals)
3286
0
{
3287
0
    PyObject *external = PyObject_GetAttrString(IMPORTLIB(interp),
3288
0
                                                "_bootstrap_external");
3289
0
    if (external == NULL) {
3290
0
        return NULL;
3291
0
    }
3292
3293
0
    PyObject *loader = PyObject_CallMethod(external, "_bless_my_loader",
3294
0
                                           "O", module_globals, NULL);
3295
0
    Py_DECREF(external);
3296
0
    return loader;
3297
0
}
3298
3299
PyObject *
3300
_PyImport_ImportlibModuleRepr(PyInterpreterState *interp, PyObject *m)
3301
0
{
3302
0
    return PyObject_CallMethod(IMPORTLIB(interp), "_module_repr", "O", m);
3303
0
}
3304
3305
3306
/*******************/
3307
3308
/* Return a finder object for a sys.path/pkg.__path__ item 'p',
3309
   possibly by fetching it from the path_importer_cache dict. If it
3310
   wasn't yet cached, traverse path_hooks until a hook is found
3311
   that can handle the path item. Return None if no hook could;
3312
   this tells our caller that the path based finder could not find
3313
   a finder for this path item. Cache the result in
3314
   path_importer_cache. */
3315
3316
static PyObject *
3317
get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
3318
                  PyObject *path_hooks, PyObject *p)
3319
0
{
3320
0
    PyObject *importer;
3321
0
    Py_ssize_t j, nhooks;
3322
3323
0
    if (!PyList_Check(path_hooks)) {
3324
0
        PyErr_SetString(PyExc_RuntimeError, "sys.path_hooks is not a list");
3325
0
        return NULL;
3326
0
    }
3327
0
    if (!PyDict_Check(path_importer_cache)) {
3328
0
        PyErr_SetString(PyExc_RuntimeError, "sys.path_importer_cache is not a dict");
3329
0
        return NULL;
3330
0
    }
3331
3332
0
    nhooks = PyList_Size(path_hooks);
3333
0
    if (nhooks < 0)
3334
0
        return NULL; /* Shouldn't happen */
3335
3336
0
    if (PyDict_GetItemRef(path_importer_cache, p, &importer) != 0) {
3337
        // found or error
3338
0
        return importer;
3339
0
    }
3340
    // not found
3341
    /* set path_importer_cache[p] to None to avoid recursion */
3342
0
    if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
3343
0
        return NULL;
3344
3345
0
    for (j = 0; j < nhooks; j++) {
3346
0
        PyObject *hook = PyList_GetItem(path_hooks, j);
3347
0
        if (hook == NULL)
3348
0
            return NULL;
3349
0
        importer = PyObject_CallOneArg(hook, p);
3350
0
        if (importer != NULL)
3351
0
            break;
3352
3353
0
        if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
3354
0
            return NULL;
3355
0
        }
3356
0
        _PyErr_Clear(tstate);
3357
0
    }
3358
0
    if (importer == NULL) {
3359
0
        Py_RETURN_NONE;
3360
0
    }
3361
0
    if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
3362
0
        Py_DECREF(importer);
3363
0
        return NULL;
3364
0
    }
3365
0
    return importer;
3366
0
}
3367
3368
PyObject *
3369
PyImport_GetImporter(PyObject *path)
3370
0
{
3371
0
    PyThreadState *tstate = _PyThreadState_GET();
3372
0
    PyObject *path_importer_cache = PySys_GetAttrString("path_importer_cache");
3373
0
    if (path_importer_cache == NULL) {
3374
0
        return NULL;
3375
0
    }
3376
0
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
3377
0
    if (path_hooks == NULL) {
3378
0
        Py_DECREF(path_importer_cache);
3379
0
        return NULL;
3380
0
    }
3381
0
    PyObject *importer = get_path_importer(tstate, path_importer_cache, path_hooks, path);
3382
0
    Py_DECREF(path_hooks);
3383
0
    Py_DECREF(path_importer_cache);
3384
0
    return importer;
3385
0
}
3386
3387
3388
/*********************/
3389
/* importing modules */
3390
/*********************/
3391
3392
int
3393
_PyImport_InitDefaultImportFunc(PyInterpreterState *interp)
3394
16
{
3395
    // Get the __import__ function
3396
16
    PyObject *import_func;
3397
16
    if (PyDict_GetItemStringRef(interp->builtins, "__import__", &import_func) <= 0) {
3398
0
        return -1;
3399
0
    }
3400
16
    IMPORT_FUNC(interp) = import_func;
3401
16
    return 0;
3402
16
}
3403
3404
int
3405
_PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
3406
8.76k
{
3407
8.76k
    return func == IMPORT_FUNC(interp);
3408
8.76k
}
3409
3410
3411
/* Import a module, either built-in, frozen, or external, and return
3412
   its module object WITH INCREMENTED REFERENCE COUNT */
3413
3414
PyObject *
3415
PyImport_ImportModule(const char *name)
3416
268
{
3417
268
    PyObject *pname;
3418
268
    PyObject *result;
3419
3420
268
    pname = PyUnicode_FromString(name);
3421
268
    if (pname == NULL)
3422
0
        return NULL;
3423
268
    result = PyImport_Import(pname);
3424
268
    Py_DECREF(pname);
3425
268
    return result;
3426
268
}
3427
3428
3429
/* Import a module without blocking
3430
 *
3431
 * At first it tries to fetch the module from sys.modules. If the module was
3432
 * never loaded before it loads it with PyImport_ImportModule() unless another
3433
 * thread holds the import lock. In the latter case the function raises an
3434
 * ImportError instead of blocking.
3435
 *
3436
 * Returns the module object with incremented ref count.
3437
 *
3438
 * Removed in 3.15, but kept for stable ABI compatibility.
3439
 */
3440
PyAPI_FUNC(PyObject *)
3441
PyImport_ImportModuleNoBlock(const char *name)
3442
0
{
3443
0
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
3444
0
        "PyImport_ImportModuleNoBlock() is deprecated and scheduled for "
3445
0
        "removal in Python 3.15. Use PyImport_ImportModule() instead.", 1))
3446
0
    {
3447
0
        return NULL;
3448
0
    }
3449
0
    return PyImport_ImportModule(name);
3450
0
}
3451
3452
3453
/* Remove importlib frames from the traceback,
3454
 * except in Verbose mode. */
3455
static void
3456
remove_importlib_frames(PyThreadState *tstate)
3457
1.39k
{
3458
1.39k
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3459
1.39k
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3460
1.39k
    const char *remove_frames = "_call_with_frames_removed";
3461
1.39k
    int always_trim = 0;
3462
1.39k
    int in_importlib = 0;
3463
1.39k
    PyObject **prev_link, **outer_link = NULL;
3464
1.39k
    PyObject *base_tb = NULL;
3465
3466
    /* Synopsis: if it's an ImportError, we trim all importlib chunks
3467
       from the traceback. We always trim chunks
3468
       which end with a call to "_call_with_frames_removed". */
3469
3470
1.39k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3471
1.39k
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3472
0
        goto done;
3473
0
    }
3474
3475
1.39k
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3476
1.39k
        always_trim = 1;
3477
1.39k
    }
3478
3479
1.39k
    assert(PyExceptionInstance_Check(exc));
3480
1.39k
    base_tb = PyException_GetTraceback(exc);
3481
1.39k
    prev_link = &base_tb;
3482
1.39k
    PyObject *tb = base_tb;
3483
4.21k
    while (tb != NULL) {
3484
2.81k
        assert(PyTraceBack_Check(tb));
3485
2.81k
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3486
2.81k
        PyObject *next = (PyObject *) traceback->tb_next;
3487
2.81k
        PyFrameObject *frame = traceback->tb_frame;
3488
2.81k
        PyCodeObject *code = PyFrame_GetCode(frame);
3489
2.81k
        int now_in_importlib;
3490
3491
2.81k
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3492
2.81k
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3493
2.81k
        if (now_in_importlib && !in_importlib) {
3494
            /* This is the link to this chunk of importlib tracebacks */
3495
1.39k
            outer_link = prev_link;
3496
1.39k
        }
3497
2.81k
        in_importlib = now_in_importlib;
3498
3499
2.81k
        if (in_importlib &&
3500
2.81k
            (always_trim ||
3501
2.80k
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3502
2.80k
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3503
2.80k
            prev_link = outer_link;
3504
2.80k
        }
3505
10
        else {
3506
10
            prev_link = (PyObject **) &traceback->tb_next;
3507
10
        }
3508
2.81k
        Py_DECREF(code);
3509
2.81k
        tb = next;
3510
2.81k
    }
3511
1.39k
    if (base_tb == NULL) {
3512
1.38k
        base_tb = Py_None;
3513
1.38k
        Py_INCREF(Py_None);
3514
1.38k
    }
3515
1.39k
    PyException_SetTraceback(exc, base_tb);
3516
1.39k
done:
3517
1.39k
    Py_XDECREF(base_tb);
3518
1.39k
    _PyErr_SetRaisedException(tstate, exc);
3519
1.39k
}
3520
3521
3522
static PyObject *
3523
resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
3524
106
{
3525
106
    PyObject *abs_name;
3526
106
    PyObject *package = NULL;
3527
106
    PyObject *spec = NULL;
3528
106
    Py_ssize_t last_dot;
3529
106
    PyObject *base;
3530
106
    int level_up;
3531
3532
106
    if (globals == NULL) {
3533
0
        _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
3534
0
        goto error;
3535
0
    }
3536
106
    if (!PyDict_Check(globals)) {
3537
0
        _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
3538
0
        goto error;
3539
0
    }
3540
106
    if (PyDict_GetItemRef(globals, &_Py_ID(__package__), &package) < 0) {
3541
0
        goto error;
3542
0
    }
3543
106
    if (package == Py_None) {
3544
0
        Py_DECREF(package);
3545
0
        package = NULL;
3546
0
    }
3547
106
    if (PyDict_GetItemRef(globals, &_Py_ID(__spec__), &spec) < 0) {
3548
0
        goto error;
3549
0
    }
3550
3551
106
    if (package != NULL) {
3552
106
        if (!PyUnicode_Check(package)) {
3553
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3554
0
                             "package must be a string");
3555
0
            goto error;
3556
0
        }
3557
106
        else if (spec != NULL && spec != Py_None) {
3558
106
            int equal;
3559
106
            PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
3560
106
            if (parent == NULL) {
3561
0
                goto error;
3562
0
            }
3563
3564
106
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
3565
106
            Py_DECREF(parent);
3566
106
            if (equal < 0) {
3567
0
                goto error;
3568
0
            }
3569
106
            else if (equal == 0) {
3570
0
                if (PyErr_WarnEx(PyExc_DeprecationWarning,
3571
0
                        "__package__ != __spec__.parent", 1) < 0) {
3572
0
                    goto error;
3573
0
                }
3574
0
            }
3575
106
        }
3576
106
    }
3577
0
    else if (spec != NULL && spec != Py_None) {
3578
0
        package = PyObject_GetAttr(spec, &_Py_ID(parent));
3579
0
        if (package == NULL) {
3580
0
            goto error;
3581
0
        }
3582
0
        else if (!PyUnicode_Check(package)) {
3583
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3584
0
                             "__spec__.parent must be a string");
3585
0
            goto error;
3586
0
        }
3587
0
    }
3588
0
    else {
3589
0
        if (PyErr_WarnEx(PyExc_ImportWarning,
3590
0
                    "can't resolve package from __spec__ or __package__, "
3591
0
                    "falling back on __name__ and __path__", 1) < 0) {
3592
0
            goto error;
3593
0
        }
3594
3595
0
        if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &package) < 0) {
3596
0
            goto error;
3597
0
        }
3598
0
        if (package == NULL) {
3599
0
            _PyErr_SetString(tstate, PyExc_KeyError,
3600
0
                             "'__name__' not in globals");
3601
0
            goto error;
3602
0
        }
3603
3604
0
        if (!PyUnicode_Check(package)) {
3605
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3606
0
                             "__name__ must be a string");
3607
0
            goto error;
3608
0
        }
3609
3610
0
        int haspath = PyDict_Contains(globals, &_Py_ID(__path__));
3611
0
        if (haspath < 0) {
3612
0
            goto error;
3613
0
        }
3614
0
        if (!haspath) {
3615
0
            Py_ssize_t dot;
3616
3617
0
            dot = PyUnicode_FindChar(package, '.',
3618
0
                                        0, PyUnicode_GET_LENGTH(package), -1);
3619
0
            if (dot == -2) {
3620
0
                goto error;
3621
0
            }
3622
0
            else if (dot == -1) {
3623
0
                goto no_parent_error;
3624
0
            }
3625
0
            PyObject *substr = PyUnicode_Substring(package, 0, dot);
3626
0
            if (substr == NULL) {
3627
0
                goto error;
3628
0
            }
3629
0
            Py_SETREF(package, substr);
3630
0
        }
3631
0
    }
3632
3633
106
    last_dot = PyUnicode_GET_LENGTH(package);
3634
106
    if (last_dot == 0) {
3635
0
        goto no_parent_error;
3636
0
    }
3637
3638
106
    for (level_up = 1; level_up < level; level_up += 1) {
3639
0
        last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
3640
0
        if (last_dot == -2) {
3641
0
            goto error;
3642
0
        }
3643
0
        else if (last_dot == -1) {
3644
0
            _PyErr_SetString(tstate, PyExc_ImportError,
3645
0
                             "attempted relative import beyond top-level "
3646
0
                             "package");
3647
0
            goto error;
3648
0
        }
3649
0
    }
3650
3651
106
    Py_XDECREF(spec);
3652
106
    base = PyUnicode_Substring(package, 0, last_dot);
3653
106
    Py_DECREF(package);
3654
106
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
3655
40
        return base;
3656
40
    }
3657
3658
66
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3659
66
    Py_DECREF(base);
3660
66
    return abs_name;
3661
3662
0
  no_parent_error:
3663
0
    _PyErr_SetString(tstate, PyExc_ImportError,
3664
0
                     "attempted relative import "
3665
0
                     "with no known parent package");
3666
3667
0
  error:
3668
0
    Py_XDECREF(spec);
3669
0
    Py_XDECREF(package);
3670
0
    return NULL;
3671
0
}
3672
3673
static PyObject *
3674
import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
3675
2.66k
{
3676
2.66k
    PyObject *mod = NULL;
3677
2.66k
    PyInterpreterState *interp = tstate->interp;
3678
2.66k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
3679
2.66k
#define import_level FIND_AND_LOAD(interp).import_level
3680
2.66k
#define accumulated FIND_AND_LOAD(interp).accumulated
3681
3682
2.66k
    PyTime_t t1 = 0, accumulated_copy = accumulated;
3683
3684
2.66k
    PyObject *sys_path, *sys_meta_path, *sys_path_hooks;
3685
2.66k
    if (PySys_GetOptionalAttrString("path", &sys_path) < 0) {
3686
0
        return NULL;
3687
0
    }
3688
2.66k
    if (PySys_GetOptionalAttrString("meta_path", &sys_meta_path) < 0) {
3689
0
        Py_XDECREF(sys_path);
3690
0
        return NULL;
3691
0
    }
3692
2.66k
    if (PySys_GetOptionalAttrString("path_hooks", &sys_path_hooks) < 0) {
3693
0
        Py_XDECREF(sys_meta_path);
3694
0
        Py_XDECREF(sys_path);
3695
0
        return NULL;
3696
0
    }
3697
2.66k
    if (_PySys_Audit(tstate, "import", "OOOOO",
3698
2.66k
                     abs_name, Py_None, sys_path ? sys_path : Py_None,
3699
2.66k
                     sys_meta_path ? sys_meta_path : Py_None,
3700
2.66k
                     sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
3701
0
        Py_XDECREF(sys_path_hooks);
3702
0
        Py_XDECREF(sys_meta_path);
3703
0
        Py_XDECREF(sys_path);
3704
0
        return NULL;
3705
0
    }
3706
2.66k
    Py_XDECREF(sys_path_hooks);
3707
2.66k
    Py_XDECREF(sys_meta_path);
3708
2.66k
    Py_XDECREF(sys_path);
3709
3710
3711
    /* XOptions is initialized after first some imports.
3712
     * So we can't have negative cache before completed initialization.
3713
     * Anyway, importlib._find_and_load is much slower than
3714
     * _PyDict_GetItemIdWithError().
3715
     */
3716
2.66k
    if (import_time) {
3717
0
        _IMPORT_TIME_HEADER(interp);
3718
3719
0
        import_level++;
3720
        // ignore error: don't block import if reading the clock fails
3721
0
        (void)PyTime_PerfCounterRaw(&t1);
3722
0
        accumulated = 0;
3723
0
    }
3724
3725
2.66k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
3726
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
3727
3728
2.66k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
3729
2.66k
                                     abs_name, IMPORT_FUNC(interp), NULL);
3730
3731
2.66k
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
3732
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
3733
0
                                       mod != NULL);
3734
3735
2.66k
    if (import_time) {
3736
0
        PyTime_t t2;
3737
0
        (void)PyTime_PerfCounterRaw(&t2);
3738
0
        PyTime_t cum = t2 - t1;
3739
3740
0
        import_level--;
3741
0
        fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
3742
0
                (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
3743
0
                (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
3744
0
                import_level*2, "", PyUnicode_AsUTF8(abs_name));
3745
3746
0
        accumulated = accumulated_copy + cum;
3747
0
    }
3748
3749
2.66k
    return mod;
3750
2.66k
#undef import_level
3751
2.66k
#undef accumulated
3752
2.66k
}
3753
3754
PyObject *
3755
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
3756
                                 PyObject *locals, PyObject *fromlist,
3757
                                 int level)
3758
19.0k
{
3759
19.0k
    PyThreadState *tstate = _PyThreadState_GET();
3760
19.0k
    PyObject *abs_name = NULL;
3761
19.0k
    PyObject *final_mod = NULL;
3762
19.0k
    PyObject *mod = NULL;
3763
19.0k
    PyObject *package = NULL;
3764
19.0k
    PyInterpreterState *interp = tstate->interp;
3765
19.0k
    int has_from;
3766
3767
19.0k
    if (name == NULL) {
3768
0
        _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3769
0
        goto error;
3770
0
    }
3771
3772
    /* The below code is importlib.__import__() & _gcd_import(), ported to C
3773
       for added performance. */
3774
3775
19.0k
    if (!PyUnicode_Check(name)) {
3776
0
        _PyErr_SetString(tstate, PyExc_TypeError,
3777
0
                         "module name must be a string");
3778
0
        goto error;
3779
0
    }
3780
19.0k
    if (level < 0) {
3781
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
3782
0
        goto error;
3783
0
    }
3784
3785
19.0k
    if (level > 0) {
3786
106
        abs_name = resolve_name(tstate, name, globals, level);
3787
106
        if (abs_name == NULL)
3788
0
            goto error;
3789
106
    }
3790
18.9k
    else {  /* level == 0 */
3791
18.9k
        if (PyUnicode_GET_LENGTH(name) == 0) {
3792
0
            _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3793
0
            goto error;
3794
0
        }
3795
18.9k
        abs_name = Py_NewRef(name);
3796
18.9k
    }
3797
3798
19.0k
    mod = import_get_module(tstate, abs_name);
3799
19.0k
    if (mod == NULL && _PyErr_Occurred(tstate)) {
3800
0
        goto error;
3801
0
    }
3802
3803
19.0k
    if (mod != NULL && mod != Py_None) {
3804
16.4k
        if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
3805
0
            goto error;
3806
0
        }
3807
16.4k
    }
3808
2.66k
    else {
3809
2.66k
        Py_XDECREF(mod);
3810
2.66k
        mod = import_find_and_load(tstate, abs_name);
3811
2.66k
        if (mod == NULL) {
3812
1.39k
            goto error;
3813
1.39k
        }
3814
2.66k
    }
3815
3816
17.6k
    has_from = 0;
3817
17.6k
    if (fromlist != NULL && fromlist != Py_None) {
3818
7.30k
        has_from = PyObject_IsTrue(fromlist);
3819
7.30k
        if (has_from < 0)
3820
0
            goto error;
3821
7.30k
    }
3822
17.6k
    if (!has_from) {
3823
15.9k
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3824
15.9k
        if (level == 0 || len > 0) {
3825
15.9k
            Py_ssize_t dot;
3826
3827
15.9k
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
3828
15.9k
            if (dot == -2) {
3829
0
                goto error;
3830
0
            }
3831
3832
15.9k
            if (dot == -1) {
3833
                /* No dot in module name, simple exit */
3834
13.2k
                final_mod = Py_NewRef(mod);
3835
13.2k
                goto error;
3836
13.2k
            }
3837
3838
2.65k
            if (level == 0) {
3839
2.65k
                PyObject *front = PyUnicode_Substring(name, 0, dot);
3840
2.65k
                if (front == NULL) {
3841
0
                    goto error;
3842
0
                }
3843
3844
2.65k
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
3845
2.65k
                Py_DECREF(front);
3846
2.65k
            }
3847
0
            else {
3848
0
                Py_ssize_t cut_off = len - dot;
3849
0
                Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
3850
0
                PyObject *to_return = PyUnicode_Substring(abs_name, 0,
3851
0
                                                        abs_name_len - cut_off);
3852
0
                if (to_return == NULL) {
3853
0
                    goto error;
3854
0
                }
3855
3856
0
                final_mod = import_get_module(tstate, to_return);
3857
0
                if (final_mod == NULL) {
3858
0
                    if (!_PyErr_Occurred(tstate)) {
3859
0
                        _PyErr_Format(tstate, PyExc_KeyError,
3860
0
                                      "%R not in sys.modules as expected",
3861
0
                                      to_return);
3862
0
                    }
3863
0
                    Py_DECREF(to_return);
3864
0
                    goto error;
3865
0
                }
3866
3867
0
                Py_DECREF(to_return);
3868
0
            }
3869
2.65k
        }
3870
0
        else {
3871
0
            final_mod = Py_NewRef(mod);
3872
0
        }
3873
15.9k
    }
3874
1.77k
    else {
3875
1.77k
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
3876
1.77k
        if (has_path < 0) {
3877
0
            goto error;
3878
0
        }
3879
1.77k
        if (has_path) {
3880
171
            final_mod = PyObject_CallMethodObjArgs(
3881
171
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
3882
171
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
3883
171
        }
3884
1.59k
        else {
3885
1.59k
            final_mod = Py_NewRef(mod);
3886
1.59k
        }
3887
1.77k
    }
3888
3889
19.0k
  error:
3890
19.0k
    Py_XDECREF(abs_name);
3891
19.0k
    Py_XDECREF(mod);
3892
19.0k
    Py_XDECREF(package);
3893
19.0k
    if (final_mod == NULL) {
3894
1.39k
        remove_importlib_frames(tstate);
3895
1.39k
    }
3896
19.0k
    return final_mod;
3897
17.6k
}
3898
3899
PyObject *
3900
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
3901
                           PyObject *fromlist, int level)
3902
128
{
3903
128
    PyObject *nameobj, *mod;
3904
128
    nameobj = PyUnicode_FromString(name);
3905
128
    if (nameobj == NULL)
3906
0
        return NULL;
3907
128
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
3908
128
                                           fromlist, level);
3909
128
    Py_DECREF(nameobj);
3910
128
    return mod;
3911
128
}
3912
3913
3914
/* Re-import a module of any kind and return its module object, WITH
3915
   INCREMENTED REFERENCE COUNT */
3916
3917
PyObject *
3918
PyImport_ReloadModule(PyObject *m)
3919
0
{
3920
0
    PyObject *reloaded_module = NULL;
3921
0
    PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
3922
0
    if (importlib == NULL) {
3923
0
        if (PyErr_Occurred()) {
3924
0
            return NULL;
3925
0
        }
3926
3927
0
        importlib = PyImport_ImportModule("importlib");
3928
0
        if (importlib == NULL) {
3929
0
            return NULL;
3930
0
        }
3931
0
    }
3932
3933
0
    reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
3934
0
    Py_DECREF(importlib);
3935
0
    return reloaded_module;
3936
0
}
3937
3938
3939
/* Higher-level import emulator which emulates the "import" statement
3940
   more accurately -- it invokes the __import__() function from the
3941
   builtins of the current globals.  This means that the import is
3942
   done using whatever import hooks are installed in the current
3943
   environment.
3944
   A dummy list ["__doc__"] is passed as the 4th argument so that
3945
   e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
3946
   will return <module "gencache"> instead of <module "win32com">. */
3947
3948
PyObject *
3949
PyImport_Import(PyObject *module_name)
3950
5.53k
{
3951
5.53k
    PyThreadState *tstate = _PyThreadState_GET();
3952
5.53k
    PyObject *globals = NULL;
3953
5.53k
    PyObject *import = NULL;
3954
5.53k
    PyObject *builtins = NULL;
3955
5.53k
    PyObject *r = NULL;
3956
3957
5.53k
    PyObject *from_list = PyList_New(0);
3958
5.53k
    if (from_list == NULL) {
3959
0
        goto err;
3960
0
    }
3961
3962
    /* Get the builtins from current globals */
3963
5.53k
    globals = PyEval_GetGlobals();  // borrowed
3964
5.53k
    if (globals != NULL) {
3965
5.41k
        Py_INCREF(globals);
3966
        // XXX Use _PyEval_EnsureBuiltins()?
3967
5.41k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
3968
5.41k
        if (builtins == NULL) {
3969
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
3970
0
            goto err;
3971
0
        }
3972
5.41k
    }
3973
128
    else if (_PyErr_Occurred(tstate)) {
3974
0
        goto err;
3975
0
    }
3976
128
    else {
3977
        /* No globals -- use standard builtins, and fake globals */
3978
128
        globals = PyDict_New();
3979
128
        if (globals == NULL) {
3980
0
            goto err;
3981
0
        }
3982
128
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
3983
0
            goto err;
3984
0
        }
3985
128
    }
3986
3987
    /* Get the __import__ function from the builtins */
3988
5.53k
    if (PyDict_Check(builtins)) {
3989
5.41k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
3990
5.41k
        if (import == NULL) {
3991
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
3992
0
        }
3993
5.41k
    }
3994
128
    else
3995
128
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
3996
5.53k
    if (import == NULL)
3997
0
        goto err;
3998
3999
    /* Call the __import__ function with the proper argument list
4000
       Always use absolute import here.
4001
       Calling for side-effect of import. */
4002
5.53k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4003
5.53k
                              globals, from_list, 0, NULL);
4004
5.53k
    if (r == NULL)
4005
0
        goto err;
4006
5.53k
    Py_DECREF(r);
4007
4008
5.53k
    r = import_get_module(tstate, module_name);
4009
5.53k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4010
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4011
0
    }
4012
4013
5.53k
  err:
4014
5.53k
    Py_XDECREF(globals);
4015
5.53k
    Py_XDECREF(builtins);
4016
5.53k
    Py_XDECREF(import);
4017
5.53k
    Py_XDECREF(from_list);
4018
4019
5.53k
    return r;
4020
5.53k
}
4021
4022
4023
/*********************/
4024
/* runtime lifecycle */
4025
/*********************/
4026
4027
PyStatus
4028
_PyImport_Init(void)
4029
16
{
4030
16
    if (INITTAB != NULL) {
4031
0
        return _PyStatus_ERR("global import state already initialized");
4032
0
    }
4033
16
    if (init_builtin_modules_table() != 0) {
4034
0
        return PyStatus_NoMemory();
4035
0
    }
4036
16
    return _PyStatus_OK();
4037
16
}
4038
4039
void
4040
_PyImport_Fini(void)
4041
0
{
4042
    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
4043
    // XXX Should we actually leave them (mostly) intact, since we don't
4044
    // ever dlclose() the module files?
4045
0
    _extensions_cache_clear_all();
4046
4047
    /* Free memory allocated by _PyImport_Init() */
4048
0
    fini_builtin_modules_table();
4049
0
}
4050
4051
void
4052
_PyImport_Fini2(void)
4053
0
{
4054
    // Reset PyImport_Inittab
4055
0
    PyImport_Inittab = _PyImport_Inittab;
4056
4057
    /* Free memory allocated by PyImport_ExtendInittab() */
4058
0
    _PyMem_DefaultRawFree(inittab_copy);
4059
0
    inittab_copy = NULL;
4060
0
}
4061
4062
4063
/*************************/
4064
/* interpreter lifecycle */
4065
/*************************/
4066
4067
PyStatus
4068
_PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
4069
16
{
4070
    // XXX Initialize here: interp->modules and interp->import_func.
4071
    // XXX Initialize here: sys.modules and sys.meta_path.
4072
4073
16
    if (importlib) {
4074
        /* This call sets up builtin and frozen import support */
4075
16
        if (init_importlib(tstate, sysmod) < 0) {
4076
0
            return _PyStatus_ERR("failed to initialize importlib");
4077
0
        }
4078
16
    }
4079
4080
16
    return _PyStatus_OK();
4081
16
}
4082
4083
/* In some corner cases it is important to be sure that the import
4084
   machinery has been initialized (or not cleaned up yet).  For
4085
   example, see issue #4236 and PyModule_Create2(). */
4086
4087
int
4088
_PyImport_IsInitialized(PyInterpreterState *interp)
4089
0
{
4090
0
    if (MODULES(interp) == NULL)
4091
0
        return 0;
4092
0
    return 1;
4093
0
}
4094
4095
/* Clear the direct per-interpreter import state, if not cleared already. */
4096
void
4097
_PyImport_ClearCore(PyInterpreterState *interp)
4098
0
{
4099
    /* interp->modules should have been cleaned up and cleared already
4100
       by _PyImport_FiniCore(). */
4101
0
    Py_CLEAR(MODULES(interp));
4102
0
    Py_CLEAR(MODULES_BY_INDEX(interp));
4103
0
    Py_CLEAR(IMPORTLIB(interp));
4104
0
    Py_CLEAR(IMPORT_FUNC(interp));
4105
0
}
4106
4107
void
4108
_PyImport_FiniCore(PyInterpreterState *interp)
4109
0
{
4110
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4111
4112
0
    if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
4113
0
        PyErr_FormatUnraisable("Exception ignored while "
4114
0
                               "clearing sys.meta_path");
4115
0
    }
4116
4117
    // XXX Pull in most of finalize_modules() in pylifecycle.c.
4118
4119
0
    if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
4120
0
        PyErr_FormatUnraisable("Exception ignored while "
4121
0
                               "clearing sys.modules");
4122
0
    }
4123
4124
0
    _PyImport_ClearCore(interp);
4125
0
}
4126
4127
// XXX Add something like _PyImport_Disable() for use early in interp fini?
4128
4129
4130
/* "external" imports */
4131
4132
static int
4133
init_zipimport(PyThreadState *tstate, int verbose)
4134
16
{
4135
16
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4136
16
    if (path_hooks == NULL) {
4137
0
        return -1;
4138
0
    }
4139
4140
16
    if (verbose) {
4141
0
        PySys_WriteStderr("# installing zipimport hook\n");
4142
0
    }
4143
4144
16
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4145
16
    if (zipimporter == NULL) {
4146
0
        _PyErr_Clear(tstate); /* No zipimporter object -- okay */
4147
0
        if (verbose) {
4148
0
            PySys_WriteStderr("# can't import zipimport.zipimporter\n");
4149
0
        }
4150
0
    }
4151
16
    else {
4152
        /* sys.path_hooks.insert(0, zipimporter) */
4153
16
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4154
16
        Py_DECREF(zipimporter);
4155
16
        if (err < 0) {
4156
0
            Py_DECREF(path_hooks);
4157
0
            return -1;
4158
0
        }
4159
16
        if (verbose) {
4160
0
            PySys_WriteStderr("# installed zipimport hook\n");
4161
0
        }
4162
16
    }
4163
16
    Py_DECREF(path_hooks);
4164
4165
16
    return 0;
4166
16
}
4167
4168
PyStatus
4169
_PyImport_InitExternal(PyThreadState *tstate)
4170
16
{
4171
16
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4172
4173
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4174
4175
16
    if (init_importlib_external(tstate->interp) != 0) {
4176
0
        _PyErr_Print(tstate);
4177
0
        return _PyStatus_ERR("external importer setup failed");
4178
0
    }
4179
4180
16
    if (init_zipimport(tstate, verbose) != 0) {
4181
0
        PyErr_Print();
4182
0
        return _PyStatus_ERR("initializing zipimport failed");
4183
0
    }
4184
4185
16
    return _PyStatus_OK();
4186
16
}
4187
4188
void
4189
_PyImport_FiniExternal(PyInterpreterState *interp)
4190
0
{
4191
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4192
4193
    // XXX Uninstall importlib metapath importers here?
4194
4195
0
    if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
4196
0
        PyErr_FormatUnraisable("Exception ignored while "
4197
0
                               "clearing sys.path_importer_cache");
4198
0
    }
4199
0
    if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
4200
0
        PyErr_FormatUnraisable("Exception ignored while "
4201
0
                               "clearing sys.path_hooks");
4202
0
    }
4203
0
}
4204
4205
4206
/******************/
4207
/* module helpers */
4208
/******************/
4209
4210
PyObject *
4211
PyImport_ImportModuleAttr(PyObject *modname, PyObject *attrname)
4212
5.27k
{
4213
5.27k
    PyObject *mod = PyImport_Import(modname);
4214
5.27k
    if (mod == NULL) {
4215
0
        return NULL;
4216
0
    }
4217
5.27k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4218
5.27k
    Py_DECREF(mod);
4219
5.27k
    return result;
4220
5.27k
}
4221
4222
PyObject *
4223
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4224
2.74k
{
4225
2.74k
    PyObject *pmodname = PyUnicode_FromString(modname);
4226
2.74k
    if (pmodname == NULL) {
4227
0
        return NULL;
4228
0
    }
4229
2.74k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4230
2.74k
    if (pattrname == NULL) {
4231
0
        Py_DECREF(pmodname);
4232
0
        return NULL;
4233
0
    }
4234
2.74k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4235
2.74k
    Py_DECREF(pattrname);
4236
2.74k
    Py_DECREF(pmodname);
4237
2.74k
    return result;
4238
2.74k
}
4239
4240
4241
/**************/
4242
/* the module */
4243
/**************/
4244
4245
/*[clinic input]
4246
_imp.lock_held
4247
4248
Return True if the import lock is currently held, else False.
4249
4250
On platforms without threads, return False.
4251
[clinic start generated code]*/
4252
4253
static PyObject *
4254
_imp_lock_held_impl(PyObject *module)
4255
/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
4256
0
{
4257
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4258
0
    return PyBool_FromLong(PyMutex_IsLocked(&IMPORT_LOCK(interp).mutex));
4259
0
}
4260
4261
/*[clinic input]
4262
@permit_long_docstring_body
4263
_imp.acquire_lock
4264
4265
Acquires the interpreter's import lock for the current thread.
4266
4267
This lock should be used by import hooks to ensure thread-safety when importing
4268
modules. On platforms without threads, this function does nothing.
4269
[clinic start generated code]*/
4270
4271
static PyObject *
4272
_imp_acquire_lock_impl(PyObject *module)
4273
/*[clinic end generated code: output=1aff58cb0ee1b026 input=e1a4ef049d34e7dd]*/
4274
12.8k
{
4275
12.8k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4276
12.8k
    _PyImport_AcquireLock(interp);
4277
12.8k
    Py_RETURN_NONE;
4278
12.8k
}
4279
4280
/*[clinic input]
4281
_imp.release_lock
4282
4283
Release the interpreter's import lock.
4284
4285
On platforms without threads, this function does nothing.
4286
[clinic start generated code]*/
4287
4288
static PyObject *
4289
_imp_release_lock_impl(PyObject *module)
4290
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
4291
12.8k
{
4292
12.8k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4293
12.8k
    if (!_PyRecursiveMutex_IsLockedByCurrentThread(&IMPORT_LOCK(interp))) {
4294
0
        PyErr_SetString(PyExc_RuntimeError,
4295
0
                        "not holding the import lock");
4296
0
        return NULL;
4297
0
    }
4298
12.8k
    _PyImport_ReleaseLock(interp);
4299
12.8k
    Py_RETURN_NONE;
4300
12.8k
}
4301
4302
4303
/*[clinic input]
4304
_imp._fix_co_filename
4305
4306
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
4307
        Code object to change.
4308
4309
    path: unicode
4310
        File path to use.
4311
    /
4312
4313
Changes code.co_filename to specify the passed-in file path.
4314
[clinic start generated code]*/
4315
4316
static PyObject *
4317
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
4318
                           PyObject *path)
4319
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
4320
4321
531
{
4322
531
    update_compiled_module(code, path);
4323
4324
531
    Py_RETURN_NONE;
4325
531
}
4326
4327
4328
/*[clinic input]
4329
_imp.create_builtin
4330
4331
    spec: object
4332
    /
4333
4334
Create an extension module.
4335
[clinic start generated code]*/
4336
4337
static PyObject *
4338
_imp_create_builtin(PyObject *module, PyObject *spec)
4339
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
4340
294
{
4341
294
    PyThreadState *tstate = _PyThreadState_GET();
4342
4343
294
    PyObject *name = PyObject_GetAttrString(spec, "name");
4344
294
    if (name == NULL) {
4345
0
        return NULL;
4346
0
    }
4347
4348
294
    if (!PyUnicode_Check(name)) {
4349
0
        PyErr_Format(PyExc_TypeError,
4350
0
                     "name must be string, not %.200s",
4351
0
                     Py_TYPE(name)->tp_name);
4352
0
        Py_DECREF(name);
4353
0
        return NULL;
4354
0
    }
4355
4356
294
    PyObject *mod = create_builtin(tstate, name, spec);
4357
294
    Py_DECREF(name);
4358
294
    return mod;
4359
294
}
4360
4361
4362
/*[clinic input]
4363
_imp.extension_suffixes
4364
4365
Returns the list of file suffixes used to identify extension modules.
4366
[clinic start generated code]*/
4367
4368
static PyObject *
4369
_imp_extension_suffixes_impl(PyObject *module)
4370
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
4371
32
{
4372
32
    PyObject *list;
4373
4374
32
    list = PyList_New(0);
4375
32
    if (list == NULL)
4376
0
        return NULL;
4377
32
#ifdef HAVE_DYNAMIC_LOADING
4378
32
    const char *suffix;
4379
32
    unsigned int index = 0;
4380
4381
128
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
4382
96
        PyObject *item = PyUnicode_FromString(suffix);
4383
96
        if (item == NULL) {
4384
0
            Py_DECREF(list);
4385
0
            return NULL;
4386
0
        }
4387
96
        if (PyList_Append(list, item) < 0) {
4388
0
            Py_DECREF(list);
4389
0
            Py_DECREF(item);
4390
0
            return NULL;
4391
0
        }
4392
96
        Py_DECREF(item);
4393
96
        index += 1;
4394
96
    }
4395
32
#endif
4396
32
    return list;
4397
32
}
4398
4399
/*[clinic input]
4400
_imp.init_frozen
4401
4402
    name: unicode
4403
    /
4404
4405
Initializes a frozen module.
4406
[clinic start generated code]*/
4407
4408
static PyObject *
4409
_imp_init_frozen_impl(PyObject *module, PyObject *name)
4410
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
4411
0
{
4412
0
    PyThreadState *tstate = _PyThreadState_GET();
4413
0
    int ret;
4414
4415
0
    ret = PyImport_ImportFrozenModuleObject(name);
4416
0
    if (ret < 0)
4417
0
        return NULL;
4418
0
    if (ret == 0) {
4419
0
        Py_RETURN_NONE;
4420
0
    }
4421
0
    return import_add_module(tstate, name);
4422
0
}
4423
4424
/*[clinic input]
4425
_imp.find_frozen
4426
4427
    name: unicode
4428
    /
4429
    *
4430
    withdata: bool = False
4431
4432
Return info about the corresponding frozen module (if there is one) or None.
4433
4434
The returned info (a 2-tuple):
4435
4436
 * data         the raw marshalled bytes
4437
 * is_package   whether or not it is a package
4438
 * origname     the originally frozen module's name, or None if not
4439
                a stdlib module (this will usually be the same as
4440
                the module's current name)
4441
[clinic start generated code]*/
4442
4443
static PyObject *
4444
_imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
4445
/*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
4446
2.41k
{
4447
2.41k
    struct frozen_info info;
4448
2.41k
    frozen_status status = find_frozen(name, &info);
4449
2.41k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
4450
2.22k
        Py_RETURN_NONE;
4451
2.22k
    }
4452
190
    else if (status == FROZEN_BAD_NAME) {
4453
0
        Py_RETURN_NONE;
4454
0
    }
4455
190
    else if (status != FROZEN_OKAY) {
4456
0
        set_frozen_error(status, name);
4457
0
        return NULL;
4458
0
    }
4459
4460
190
    PyObject *data = NULL;
4461
190
    if (withdata) {
4462
0
        data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
4463
0
        if (data == NULL) {
4464
0
            return NULL;
4465
0
        }
4466
0
    }
4467
4468
190
    PyObject *origname = NULL;
4469
190
    if (info.origname != NULL && info.origname[0] != '\0') {
4470
190
        origname = PyUnicode_FromString(info.origname);
4471
190
        if (origname == NULL) {
4472
0
            Py_XDECREF(data);
4473
0
            return NULL;
4474
0
        }
4475
190
    }
4476
4477
190
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
4478
190
                                    info.is_package ? Py_True : Py_False,
4479
190
                                    origname ? origname : Py_None);
4480
190
    Py_XDECREF(origname);
4481
190
    Py_XDECREF(data);
4482
190
    return result;
4483
190
}
4484
4485
/*[clinic input]
4486
_imp.get_frozen_object
4487
4488
    name: unicode
4489
    data as dataobj: object = None
4490
    /
4491
4492
Create a code object for a frozen module.
4493
[clinic start generated code]*/
4494
4495
static PyObject *
4496
_imp_get_frozen_object_impl(PyObject *module, PyObject *name,
4497
                            PyObject *dataobj)
4498
/*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
4499
190
{
4500
190
    struct frozen_info info = {0};
4501
190
    Py_buffer buf = {0};
4502
190
    if (PyObject_CheckBuffer(dataobj)) {
4503
0
        if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
4504
0
            return NULL;
4505
0
        }
4506
0
        info.data = (const char *)buf.buf;
4507
0
        info.size = buf.len;
4508
0
    }
4509
190
    else if (dataobj != Py_None) {
4510
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
4511
0
        return NULL;
4512
0
    }
4513
190
    else {
4514
190
        frozen_status status = find_frozen(name, &info);
4515
190
        if (status != FROZEN_OKAY) {
4516
0
            set_frozen_error(status, name);
4517
0
            return NULL;
4518
0
        }
4519
190
    }
4520
4521
190
    if (info.nameobj == NULL) {
4522
0
        info.nameobj = name;
4523
0
    }
4524
190
    if (info.size == 0) {
4525
        /* Does not contain executable code. */
4526
0
        set_frozen_error(FROZEN_INVALID, name);
4527
0
        return NULL;
4528
0
    }
4529
4530
190
    PyInterpreterState *interp = _PyInterpreterState_GET();
4531
190
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
4532
190
    if (dataobj != Py_None) {
4533
0
        PyBuffer_Release(&buf);
4534
0
    }
4535
190
    return codeobj;
4536
190
}
4537
4538
/*[clinic input]
4539
_imp.is_frozen_package
4540
4541
    name: unicode
4542
    /
4543
4544
Returns True if the module name is of a frozen package.
4545
[clinic start generated code]*/
4546
4547
static PyObject *
4548
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
4549
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
4550
16
{
4551
16
    struct frozen_info info;
4552
16
    frozen_status status = find_frozen(name, &info);
4553
16
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
4554
0
        set_frozen_error(status, name);
4555
0
        return NULL;
4556
0
    }
4557
16
    return PyBool_FromLong(info.is_package);
4558
16
}
4559
4560
/*[clinic input]
4561
_imp.is_builtin
4562
4563
    name: unicode
4564
    /
4565
4566
Returns True if the module name corresponds to a built-in module.
4567
[clinic start generated code]*/
4568
4569
static PyObject *
4570
_imp_is_builtin_impl(PyObject *module, PyObject *name)
4571
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
4572
2.70k
{
4573
2.70k
    return PyLong_FromLong(is_builtin(name));
4574
2.70k
}
4575
4576
/*[clinic input]
4577
_imp.is_frozen
4578
4579
    name: unicode
4580
    /
4581
4582
Returns True if the module name corresponds to a frozen module.
4583
[clinic start generated code]*/
4584
4585
static PyObject *
4586
_imp_is_frozen_impl(PyObject *module, PyObject *name)
4587
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
4588
16
{
4589
16
    struct frozen_info info;
4590
16
    frozen_status status = find_frozen(name, &info);
4591
16
    if (status != FROZEN_OKAY) {
4592
0
        Py_RETURN_FALSE;
4593
0
    }
4594
16
    Py_RETURN_TRUE;
4595
16
}
4596
4597
/*[clinic input]
4598
_imp._frozen_module_names
4599
4600
Returns the list of available frozen modules.
4601
[clinic start generated code]*/
4602
4603
static PyObject *
4604
_imp__frozen_module_names_impl(PyObject *module)
4605
/*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
4606
0
{
4607
0
    return list_frozen_module_names();
4608
0
}
4609
4610
/*[clinic input]
4611
_imp._override_frozen_modules_for_tests
4612
4613
    override: int
4614
    /
4615
4616
(internal-only) Override PyConfig.use_frozen_modules.
4617
4618
(-1: "off", 1: "on", 0: no override)
4619
See frozen_modules() in Lib/test/support/import_helper.py.
4620
[clinic start generated code]*/
4621
4622
static PyObject *
4623
_imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
4624
/*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
4625
0
{
4626
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4627
0
    OVERRIDE_FROZEN_MODULES(interp) = override;
4628
0
    Py_RETURN_NONE;
4629
0
}
4630
4631
/*[clinic input]
4632
_imp._override_multi_interp_extensions_check
4633
4634
    override: int
4635
    /
4636
4637
(internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
4638
4639
(-1: "never", 1: "always", 0: no override)
4640
[clinic start generated code]*/
4641
4642
static PyObject *
4643
_imp__override_multi_interp_extensions_check_impl(PyObject *module,
4644
                                                  int override)
4645
/*[clinic end generated code: output=3ff043af52bbf280 input=e086a2ea181f92ae]*/
4646
0
{
4647
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4648
0
    if (_Py_IsMainInterpreter(interp)) {
4649
0
        PyErr_SetString(PyExc_RuntimeError,
4650
0
                        "_imp._override_multi_interp_extensions_check() "
4651
0
                        "cannot be used in the main interpreter");
4652
0
        return NULL;
4653
0
    }
4654
#ifdef Py_GIL_DISABLED
4655
    PyErr_SetString(PyExc_RuntimeError,
4656
                    "_imp._override_multi_interp_extensions_check() "
4657
                    "cannot be used in the free-threaded build");
4658
    return NULL;
4659
#else
4660
0
    int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
4661
0
    OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
4662
0
    return PyLong_FromLong(oldvalue);
4663
0
#endif
4664
0
}
4665
4666
#ifdef HAVE_DYNAMIC_LOADING
4667
4668
/*[clinic input]
4669
_imp.create_dynamic
4670
4671
    spec: object
4672
    file: object = NULL
4673
    /
4674
4675
Create an extension module.
4676
[clinic start generated code]*/
4677
4678
static PyObject *
4679
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
4680
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
4681
73
{
4682
73
    PyObject *mod = NULL;
4683
73
    PyThreadState *tstate = _PyThreadState_GET();
4684
4685
73
    struct _Py_ext_module_loader_info info;
4686
73
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
4687
0
        return NULL;
4688
0
    }
4689
4690
73
    struct extensions_cache_value *cached = NULL;
4691
73
    mod = import_find_extension(tstate, &info, &cached);
4692
73
    if (mod != NULL) {
4693
0
        assert(!_PyErr_Occurred(tstate));
4694
0
        assert(cached != NULL);
4695
        /* The module might not have md_def set in certain reload cases. */
4696
0
        assert(_PyModule_GetDef(mod) == NULL
4697
0
                || cached->def == _PyModule_GetDef(mod));
4698
0
        assert_singlephase(cached);
4699
0
        goto finally;
4700
0
    }
4701
73
    else if (_PyErr_Occurred(tstate)) {
4702
0
        goto finally;
4703
0
    }
4704
    /* Otherwise it must be multi-phase init or the first time it's loaded. */
4705
4706
    /* If the module was added to the global cache
4707
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
4708
     * then we have to do a little dance here. */
4709
73
    if (cached != NULL) {
4710
0
        assert(cached->def->m_base.m_copy == NULL);
4711
        /* For now we clear the cache and move on. */
4712
0
        _extensions_cache_delete(info.path, info.name);
4713
0
    }
4714
4715
73
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
4716
73
                    Py_None, Py_None, Py_None) < 0)
4717
0
    {
4718
0
        goto finally;
4719
0
    }
4720
4721
    /* We would move this (and the fclose() below) into
4722
     * _PyImport_GetModInitFunc(), but it isn't clear if the intervening
4723
     * code relies on fp still being open. */
4724
73
    FILE *fp;
4725
73
    if (file != NULL) {
4726
0
        fp = Py_fopen(info.filename, "r");
4727
0
        if (fp == NULL) {
4728
0
            goto finally;
4729
0
        }
4730
0
    }
4731
73
    else {
4732
73
        fp = NULL;
4733
73
    }
4734
4735
73
    PyModInitFunction p0 = _PyImport_GetModInitFunc(&info, fp);
4736
73
    if (p0 == NULL) {
4737
0
        goto finally;
4738
0
    }
4739
4740
#ifdef Py_GIL_DISABLED
4741
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
4742
    // would ideally be inside import_run_extension(). They are kept in the
4743
    // callers for now because that would complicate the control flow inside
4744
    // import_run_extension(). It should be possible to restructure
4745
    // import_run_extension() to address this.
4746
    _PyEval_EnableGILTransient(tstate);
4747
#endif
4748
73
    mod = import_run_extension(
4749
73
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
4750
#ifdef Py_GIL_DISABLED
4751
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
4752
        Py_CLEAR(mod);
4753
        goto finally;
4754
    }
4755
#endif
4756
4757
    // XXX Shouldn't this happen in the error cases too (i.e. in "finally")?
4758
73
    if (fp) {
4759
0
        fclose(fp);
4760
0
    }
4761
4762
73
finally:
4763
73
    _Py_ext_module_loader_info_clear(&info);
4764
73
    return mod;
4765
73
}
4766
4767
/*[clinic input]
4768
_imp.exec_dynamic -> int
4769
4770
    mod: object
4771
    /
4772
4773
Initialize an extension module.
4774
[clinic start generated code]*/
4775
4776
static int
4777
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
4778
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
4779
73
{
4780
73
    return exec_builtin_or_dynamic(mod);
4781
73
}
4782
4783
4784
#endif /* HAVE_DYNAMIC_LOADING */
4785
4786
/*[clinic input]
4787
_imp.exec_builtin -> int
4788
4789
    mod: object
4790
    /
4791
4792
Initialize a built-in module.
4793
[clinic start generated code]*/
4794
4795
static int
4796
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
4797
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
4798
294
{
4799
294
    return exec_builtin_or_dynamic(mod);
4800
294
}
4801
4802
/*[clinic input]
4803
_imp.source_hash
4804
4805
    key: long
4806
    source: Py_buffer
4807
[clinic start generated code]*/
4808
4809
static PyObject *
4810
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
4811
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
4812
0
{
4813
0
    union {
4814
0
        uint64_t x;
4815
0
        char data[sizeof(uint64_t)];
4816
0
    } hash;
4817
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
4818
#if !PY_LITTLE_ENDIAN
4819
    // Force to little-endian. There really ought to be a succinct standard way
4820
    // to do this.
4821
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
4822
        char tmp = hash.data[i];
4823
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
4824
        hash.data[sizeof(hash.data) - i - 1] = tmp;
4825
    }
4826
#endif
4827
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
4828
0
}
4829
4830
4831
PyDoc_STRVAR(doc_imp,
4832
"(Extremely) low-level import machinery bits as used by importlib.");
4833
4834
static PyMethodDef imp_methods[] = {
4835
    _IMP_EXTENSION_SUFFIXES_METHODDEF
4836
    _IMP_LOCK_HELD_METHODDEF
4837
    _IMP_ACQUIRE_LOCK_METHODDEF
4838
    _IMP_RELEASE_LOCK_METHODDEF
4839
    _IMP_FIND_FROZEN_METHODDEF
4840
    _IMP_GET_FROZEN_OBJECT_METHODDEF
4841
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
4842
    _IMP_CREATE_BUILTIN_METHODDEF
4843
    _IMP_INIT_FROZEN_METHODDEF
4844
    _IMP_IS_BUILTIN_METHODDEF
4845
    _IMP_IS_FROZEN_METHODDEF
4846
    _IMP__FROZEN_MODULE_NAMES_METHODDEF
4847
    _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
4848
    _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
4849
    _IMP_CREATE_DYNAMIC_METHODDEF
4850
    _IMP_EXEC_DYNAMIC_METHODDEF
4851
    _IMP_EXEC_BUILTIN_METHODDEF
4852
    _IMP__FIX_CO_FILENAME_METHODDEF
4853
    _IMP_SOURCE_HASH_METHODDEF
4854
    {NULL, NULL}  /* sentinel */
4855
};
4856
4857
4858
static int
4859
imp_module_exec(PyObject *module)
4860
16
{
4861
16
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
4862
16
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
4863
16
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
4864
0
        return -1;
4865
0
    }
4866
4867
16
    if (PyModule_AddIntConstant(
4868
16
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
4869
0
    {
4870
0
        return -1;
4871
0
    }
4872
4873
16
    return 0;
4874
16
}
4875
4876
4877
static PyModuleDef_Slot imp_slots[] = {
4878
    {Py_mod_exec, imp_module_exec},
4879
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
4880
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
4881
    {0, NULL}
4882
};
4883
4884
static struct PyModuleDef imp_module = {
4885
    PyModuleDef_HEAD_INIT,
4886
    .m_name = "_imp",
4887
    .m_doc = doc_imp,
4888
    .m_size = 0,
4889
    .m_methods = imp_methods,
4890
    .m_slots = imp_slots,
4891
};
4892
4893
PyMODINIT_FUNC
4894
PyInit__imp(void)
4895
16
{
4896
16
    return PyModuleDef_Init(&imp_module);
4897
16
}