Coverage Report

Created: 2025-07-18 06:10

/src/cpython3/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
0
{
46
0
    return !_Py_IsMainInterpreter(interp)
47
0
        && !(interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC)
48
0
        && interp->ceval.own_gil;
49
0
}
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
1.91k
#define INITTAB _PyRuntime.imports.inittab
73
432
#define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
74
1.04k
#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
4.08M
    (interp)->imports.modules
85
#define MODULES_BY_INDEX(interp) \
86
242
    (interp)->imports.modules_by_index
87
#define IMPORTLIB(interp) \
88
1.75k
    (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
1.39k
    (interp)->imports.override_frozen_modules
93
#ifdef HAVE_DLOPEN
94
#  define DLOPENFLAGS(interp) \
95
24
        (interp)->imports.dlopenflags
96
#endif
97
#define IMPORT_FUNC(interp) \
98
2.10M
    (interp)->imports.import_func
99
100
#define IMPORT_LOCK(interp) \
101
20.3k
    (interp)->imports.lock
102
103
#define FIND_AND_LOAD(interp) \
104
1.46k
    (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
6.78k
{
127
6.78k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
128
6.78k
}
129
130
void
131
_PyImport_ReleaseLock(PyInterpreterState *interp)
132
6.78k
{
133
6.78k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
134
6.78k
}
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
22
{
151
22
    assert(MODULES(interp) == NULL);
152
22
    MODULES(interp) = PyDict_New();
153
22
    if (MODULES(interp) == NULL) {
154
0
        return NULL;
155
0
    }
156
22
    return MODULES(interp);
157
22
}
158
159
PyObject *
160
_PyImport_GetModules(PyInterpreterState *interp)
161
708k
{
162
708k
    return MODULES(interp);
163
708k
}
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
3.37M
{
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
3.37M
    PyObject *modules = MODULES(tstate->interp);
194
3.37M
    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
3.37M
    return modules;
203
3.37M
}
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
2
{
215
2
    PyThreadState *tstate = _PyThreadState_GET();
216
2
    PyObject *modules = get_modules_dict(tstate, true);
217
2
    return PyObject_SetItem(modules, name, m);
218
2
}
219
220
int
221
_PyImport_SetModuleString(const char *name, PyObject *m)
222
22
{
223
22
    PyThreadState *tstate = _PyThreadState_GET();
224
22
    PyObject *modules = get_modules_dict(tstate, true);
225
22
    return PyMapping_SetItemString(modules, name, m);
226
22
}
227
228
static PyObject *
229
import_get_module(PyThreadState *tstate, PyObject *name)
230
3.37M
{
231
3.37M
    PyObject *modules = get_modules_dict(tstate, false);
232
3.37M
    if (modules == NULL) {
233
0
        return NULL;
234
0
    }
235
236
3.37M
    PyObject *m;
237
3.37M
    Py_INCREF(modules);
238
3.37M
    (void)PyMapping_GetOptionalItem(modules, name, &m);
239
3.37M
    Py_DECREF(modules);
240
3.37M
    return m;
241
3.37M
}
242
243
static int
244
import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
245
3.11M
{
246
3.11M
    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
3.11M
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
254
3.11M
    if (rc > 0) {
255
3.11M
        rc = _PyModuleSpec_IsInitializing(spec);
256
3.11M
        Py_DECREF(spec);
257
3.11M
    }
258
3.11M
    if (rc == 0) {
259
3.11M
        goto done;
260
3.11M
    }
261
171
    else if (rc < 0) {
262
0
        return rc;
263
0
    }
264
265
    /* Wait until module is done importing. */
266
171
    PyObject *value = PyObject_CallMethodOneArg(
267
171
        IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
268
171
    if (value == NULL) {
269
0
        return -1;
270
0
    }
271
171
    Py_DECREF(value);
272
273
3.11M
done:
274
    /* When -X importtime=2, print an import time entry even if an
275
       imported module has already been loaded.
276
     */
277
3.11M
    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
3.11M
    return 0;
286
171
}
287
288
static void remove_importlib_frames(PyThreadState *tstate);
289
290
PyObject *
291
PyImport_GetModule(PyObject *name)
292
708k
{
293
708k
    PyThreadState *tstate = _PyThreadState_GET();
294
708k
    PyObject *mod;
295
296
708k
    mod = import_get_module(tstate, name);
297
708k
    if (mod != NULL && mod != Py_None) {
298
708k
        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
708k
    }
304
708k
    return mod;
305
708k
}
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
66
{
314
66
    PyObject *modules = get_modules_dict(tstate, false);
315
66
    if (modules == NULL) {
316
0
        return NULL;
317
0
    }
318
319
66
    PyObject *m;
320
66
    if (PyMapping_GetOptionalItem(modules, name, &m) < 0) {
321
0
        return NULL;
322
0
    }
323
66
    if (m != NULL && PyModule_Check(m)) {
324
22
        return m;
325
22
    }
326
44
    Py_XDECREF(m);
327
44
    m = PyModule_NewObject(name);
328
44
    if (m == NULL)
329
0
        return NULL;
330
44
    if (PyObject_SetItem(modules, name, m) != 0) {
331
0
        Py_DECREF(m);
332
0
        return NULL;
333
0
    }
334
335
44
    return m;
336
44
}
337
338
PyObject *
339
PyImport_AddModuleRef(const char *name)
340
22
{
341
22
    PyObject *name_obj = PyUnicode_FromString(name);
342
22
    if (name_obj == NULL) {
343
0
        return NULL;
344
0
    }
345
22
    PyThreadState *tstate = _PyThreadState_GET();
346
22
    PyObject *module = import_add_module(tstate, name_obj);
347
22
    Py_DECREF(name_obj);
348
22
    return module;
349
22
}
350
351
352
PyObject *
353
PyImport_AddModuleObject(PyObject *name)
354
22
{
355
22
    PyThreadState *tstate = _PyThreadState_GET();
356
22
    PyObject *mod = import_add_module(tstate, name);
357
22
    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
22
    PyObject *ref = PyWeakref_NewRef(mod, NULL);
372
22
    Py_DECREF(mod);
373
22
    if (ref == NULL) {
374
0
        return NULL;
375
0
    }
376
22
    mod = _PyWeakref_GET_REF(ref);
377
22
    Py_DECREF(ref);
378
22
    Py_XDECREF(mod);
379
380
22
    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
22
    return mod; /* borrowed reference */
386
22
}
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
432
{
434
432
    return _Py_atomic_add_ssize(&LAST_MODULE_INDEX, 1) + 1;
435
432
}
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
0
#ifndef NDEBUG
448
0
    struct extensions_cache_value *cached = _find_cached_def(def);
449
0
    assert(cached == NULL || index == _get_cached_module_index(cached));
450
0
#endif
451
0
    return index;
452
0
}
453
454
static void
455
_set_module_index(PyModuleDef *def, Py_ssize_t index)
456
44
{
457
44
    assert(index > 0);
458
44
    if (index == def->m_base.m_index) {
459
        /* There's nothing to do. */
460
44
    }
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
44
}
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
44
{
504
44
    assert(index > 0);
505
506
44
    if (MODULES_BY_INDEX(interp) == NULL) {
507
22
        MODULES_BY_INDEX(interp) = PyList_New(0);
508
22
        if (MODULES_BY_INDEX(interp) == NULL) {
509
0
            return -1;
510
0
        }
511
22
    }
512
513
154
    while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
514
110
        if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
515
0
            return -1;
516
0
        }
517
110
    }
518
519
44
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
520
44
}
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.46k
# define PKGCONTEXT pkgcontext
789
#endif
790
791
const char *
792
_PyImport_ResolveNameWithPackageContext(const char *name)
793
88
{
794
#ifndef HAVE_THREAD_LOCAL
795
    PyMutex_Lock(&EXTENSIONS.mutex);
796
#endif
797
88
    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
88
    return name;
808
88
}
809
810
const char *
811
_PyImport_SwapPackageContext(const char *newcontext)
812
688
{
813
#ifndef HAVE_THREAD_LOCAL
814
    PyMutex_Lock(&EXTENSIONS.mutex);
815
#endif
816
688
    const char *oldcontext = PKGCONTEXT;
817
688
    PKGCONTEXT = newcontext;
818
#ifndef HAVE_THREAD_LOCAL
819
    PyMutex_Unlock(&EXTENSIONS.mutex);
820
#endif
821
688
    return oldcontext;
822
688
}
823
824
#ifdef HAVE_DLOPEN
825
int
826
_PyImport_GetDLOpenFlags(PyInterpreterState *interp)
827
24
{
828
24
    return DLOPENFLAGS(interp);
829
24
}
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
344
exec_builtin_or_dynamic(PyObject *mod) {
842
344
    PyModuleDef *def;
843
344
    void *state;
844
845
344
    if (!PyModule_Check(mod)) {
846
0
        return 0;
847
0
    }
848
849
344
    def = PyModule_GetDef(mod);
850
344
    if (def == NULL) {
851
0
        return 0;
852
0
    }
853
854
344
    state = PyModule_GetState(mod);
855
344
    if (state) {
856
        /* Already initialized; skip reload */
857
0
        return 0;
858
0
    }
859
860
344
    return PyModule_ExecDef(mod, def);
861
344
}
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
476
{
960
476
    PyMutex_Lock(&_PyRuntime.imports.extensions.mutex);
961
476
}
962
963
static inline void
964
extensions_lock_release(void)
965
476
{
966
476
    PyMutex_Unlock(&_PyRuntime.imports.extensions.mutex);
967
476
}
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
44
{
1027
44
    struct extensions_cache_value *value
1028
44
            = PyMem_RawMalloc(sizeof(struct extensions_cache_value));
1029
44
    if (value == NULL) {
1030
0
        PyErr_NoMemory();
1031
0
        return NULL;
1032
0
    }
1033
44
    *value = (struct extensions_cache_value){0};
1034
44
    return value;
1035
44
}
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
44
{
1046
44
    assert(cached->m_index > 0);
1047
44
    return cached->m_index;
1048
44
}
1049
1050
static void
1051
fixup_cached_def(struct extensions_cache_value *value)
1052
44
{
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
44
    PyModuleDef *def = value->def;
1063
44
    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
44
    _Py_SetImmortalUntracked((PyObject *)def);
1068
1069
44
    def->m_base.m_init = value->m_init;
1070
1071
44
    assert(value->m_index > 0);
1072
44
    _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
44
    assert(def->m_base.m_copy == NULL
1077
44
           || def->m_base.m_init == NULL
1078
44
           || value->m_dict != NULL);
1079
44
    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
44
}
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
44
{
1095
44
    Py_XDECREF(oldbase->m_copy);
1096
44
}
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
44
{
1114
44
    assert(value != NULL);
1115
    /* This should only have been called without an m_dict already set. */
1116
44
    assert(value->m_dict == NULL);
1117
44
    if (m_dict == NULL) {
1118
44
        return 0;
1119
44
    }
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
432
{
1204
432
    const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1205
432
    const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1206
432
    if (str1_data == NULL || str2_data == NULL) {
1207
0
        return NULL;
1208
0
    }
1209
432
    Py_ssize_t str1_len = strlen(str1_data);
1210
432
    Py_ssize_t str2_len = strlen(str2_data);
1211
1212
    /* Make sure sep and the NULL byte won't cause an overflow. */
1213
432
    assert(SIZE_MAX - str1_len - str2_len > 2);
1214
432
    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
432
    char *key = PyMem_RawMalloc(size);
1218
432
    if (key == NULL) {
1219
0
        PyErr_NoMemory();
1220
0
        return NULL;
1221
0
    }
1222
1223
432
    memcpy(key, str1_data, str1_len);
1224
432
    key[str1_len] = sep;
1225
432
    memcpy(key + str1_len + 1, str2_data, str2_len);
1226
432
    key[size - 1] = '\0';
1227
432
    assert(strlen(key) == size - 1);
1228
432
    return key;
1229
432
}
1230
1231
static Py_uhash_t
1232
hashtable_hash_str(const void *key)
1233
520
{
1234
520
    return Py_HashBuffer(key, strlen((const char *)key));
1235
520
}
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
388
{
1246
388
    PyMem_RawFree(ptr);
1247
388
}
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
0
{
1259
0
    if (value == NULL) {
1260
        /* It was previously deleted. */
1261
0
        return 0;
1262
0
    }
1263
0
    struct hashtable_next_match_def_data *data
1264
0
            = (struct hashtable_next_match_def_data *)user_data;
1265
0
    struct extensions_cache_value *cur
1266
0
            = (struct extensions_cache_value *)value;
1267
0
    if (cur->def == data->def) {
1268
0
        data->matched = cur;
1269
0
        return 1;
1270
0
    }
1271
0
    return 0;
1272
0
}
1273
1274
static struct extensions_cache_value *
1275
_find_cached_def(PyModuleDef *def)
1276
0
{
1277
0
    struct hashtable_next_match_def_data data = {0};
1278
0
    (void)_Py_hashtable_foreach(
1279
0
            EXTENSIONS.hashtable, hashtable_next_match_def, &data);
1280
0
    return data.matched;
1281
0
}
1282
#endif
1283
1284
432
#define HTSEP ':'
1285
1286
static int
1287
_extensions_cache_init(void)
1288
22
{
1289
22
    _Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
1290
22
    EXTENSIONS.hashtable = _Py_hashtable_new_full(
1291
22
        hashtable_hash_str,
1292
22
        hashtable_compare_str,
1293
22
        hashtable_destroy_str,  // key
1294
22
        del_extensions_cache_value,  // value
1295
22
        &alloc
1296
22
    );
1297
22
    if (EXTENSIONS.hashtable == NULL) {
1298
0
        PyErr_NoMemory();
1299
0
        return -1;
1300
0
    }
1301
22
    return 0;
1302
22
}
1303
1304
static _Py_hashtable_entry_t *
1305
_extensions_cache_find_unlocked(PyObject *path, PyObject *name,
1306
                                void **p_key)
1307
476
{
1308
476
    if (EXTENSIONS.hashtable == NULL) {
1309
44
        return NULL;
1310
44
    }
1311
432
    void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1312
432
    if (key == NULL) {
1313
0
        return NULL;
1314
0
    }
1315
432
    _Py_hashtable_entry_t *entry =
1316
432
            _Py_hashtable_get_entry(EXTENSIONS.hashtable, key);
1317
432
    if (p_key != NULL) {
1318
44
        *p_key = key;
1319
44
    }
1320
388
    else {
1321
388
        hashtable_destroy_str(key);
1322
388
    }
1323
432
    return entry;
1324
432
}
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
432
{
1330
432
    struct extensions_cache_value *value = NULL;
1331
432
    extensions_lock_acquire();
1332
1333
432
    _Py_hashtable_entry_t *entry =
1334
432
            _extensions_cache_find_unlocked(path, name, NULL);
1335
432
    if (entry == NULL) {
1336
        /* It was never added. */
1337
432
        goto finally;
1338
432
    }
1339
0
    value = (struct extensions_cache_value *)entry->value;
1340
1341
432
finally:
1342
432
    extensions_lock_release();
1343
432
    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
44
{
1353
44
    struct extensions_cache_value *value = NULL;
1354
44
    void *key = NULL;
1355
44
    struct extensions_cache_value *newvalue = NULL;
1356
44
    PyModuleDef_Base olddefbase = def->m_base;
1357
1358
44
    assert(def != NULL);
1359
44
    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
44
    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
44
    assert(def->m_base.m_copy == NULL || m_dict != NULL);
1365
44
    assert((origin == _Py_ext_module_origin_DYNAMIC) == (name != path));
1366
44
    assert(origin != _Py_ext_module_origin_CORE || m_dict == NULL);
1367
1368
44
    extensions_lock_acquire();
1369
1370
44
    if (EXTENSIONS.hashtable == NULL) {
1371
22
        if (_extensions_cache_init() < 0) {
1372
0
            goto finally;
1373
0
        }
1374
22
    }
1375
1376
    /* Create a cached value to populate for the module. */
1377
44
    _Py_hashtable_entry_t *entry =
1378
44
            _extensions_cache_find_unlocked(path, name, &key);
1379
44
    value = entry == NULL
1380
44
        ? NULL
1381
44
        : (struct extensions_cache_value *)entry->value;
1382
44
    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
44
    newvalue = alloc_extensions_cache_value();
1394
44
    if (newvalue == NULL) {
1395
0
        goto finally;
1396
0
    }
1397
1398
    /* Populate the new cache value data. */
1399
44
    *newvalue = (struct extensions_cache_value){
1400
44
        .def=def,
1401
44
        .m_init=m_init,
1402
44
        .m_index=m_index,
1403
        /* m_dict is set by set_cached_m_dict(). */
1404
44
        .origin=origin,
1405
#ifdef Py_GIL_DISABLED
1406
        .md_gil=md_gil,
1407
#endif
1408
44
    };
1409
44
#ifndef Py_GIL_DISABLED
1410
44
    (void)md_gil;
1411
44
#endif
1412
44
    if (init_cached_m_dict(newvalue, m_dict) < 0) {
1413
0
        goto finally;
1414
0
    }
1415
44
    fixup_cached_def(newvalue);
1416
1417
44
    if (entry == NULL) {
1418
        /* It was never added. */
1419
44
        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
44
        key = NULL;
1425
44
    }
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
44
    value = newvalue;
1444
1445
44
finally:
1446
44
    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
44
    else {
1453
44
        cleanup_old_cached_def(&olddefbase);
1454
44
    }
1455
1456
44
finally_oldvalue:
1457
44
    extensions_lock_release();
1458
44
    if (key != NULL) {
1459
0
        hashtable_destroy_str(key);
1460
0
    }
1461
1462
44
    return value;
1463
44
}
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
344
{
1581
344
    if (_Py_IsMainInterpreter(tstate->interp)) {
1582
344
        return tstate;
1583
344
    }
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
0
#ifndef NDEBUG
1590
0
    PyThreadState *old_tstate = PyThreadState_Swap(main_tstate);
1591
0
    assert(old_tstate == tstate);
1592
#else
1593
    (void)PyThreadState_Swap(main_tstate);
1594
#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
432
{
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
432
    if (path == name) {
1653
408
        if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
1654
44
            return 1;
1655
44
        }
1656
364
        if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
1657
44
            return 1;
1658
44
        }
1659
364
    }
1660
344
    return 0;
1661
432
}
1662
1663
1664
static _Py_ext_module_kind
1665
_get_extension_kind(PyModuleDef *def, bool check_size)
1666
388
{
1667
388
    _Py_ext_module_kind kind;
1668
388
    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
0
        kind = _Py_ext_module_kind_SINGLEPHASE;
1672
0
    }
1673
388
    else if (def->m_slots != NULL) {
1674
344
        kind = _Py_ext_module_kind_MULTIPHASE;
1675
344
    }
1676
44
    else if (check_size && def->m_size == -1) {
1677
44
        kind = _Py_ext_module_kind_SINGLEPHASE;
1678
44
    }
1679
0
    else if (def->m_base.m_init != NULL) {
1680
0
        kind = _Py_ext_module_kind_SINGLEPHASE;
1681
0
    }
1682
0
    else {
1683
        // This is probably single-phase init, but a multi-phase
1684
        // module *can* have NULL m_slots.
1685
0
        kind = _Py_ext_module_kind_UNKNOWN;
1686
0
    }
1687
388
    return kind;
1688
388
}
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
344
    do {                                                            \
1695
344
        _Py_ext_module_kind kind = _get_extension_kind(def, false); \
1696
344
        assert(kind == _Py_ext_module_kind_MULTIPHASE               \
1697
344
                /* m_slots can be NULL. */                          \
1698
344
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1699
344
    } while (0)
1700
1701
#define assert_singlephase_def(def)                                 \
1702
44
    do {                                                            \
1703
44
        _Py_ext_module_kind kind = _get_extension_kind(def, true);  \
1704
44
        assert(kind == _Py_ext_module_kind_SINGLEPHASE              \
1705
44
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1706
44
    } while (0)
1707
1708
#define assert_singlephase(cached)                                          \
1709
0
    do {                                                                    \
1710
0
        _Py_ext_module_kind kind = _get_extension_kind(cached->def, true);  \
1711
0
        assert(kind == _Py_ext_module_kind_SINGLEPHASE);                    \
1712
0
    } 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
44
{
1735
44
    struct extensions_cache_value *cached = NULL;
1736
44
    PyModInitFunction m_init = NULL;
1737
44
    PyObject *m_dict = NULL;
1738
1739
    /* Set up for _extensions_cache_set(). */
1740
44
    if (singlephase == NULL) {
1741
0
        assert(def->m_base.m_init == NULL);
1742
0
        assert(def->m_base.m_copy == NULL);
1743
0
    }
1744
44
    else {
1745
44
        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
44
        else if (singlephase->m_dict == NULL) {
1758
            /* It must be a core builtin module. */
1759
44
            assert(is_core_module(tstate->interp, name, path));
1760
44
            assert(def->m_size == -1);
1761
44
            assert(def->m_base.m_copy == NULL);
1762
44
            assert(def->m_base.m_init == NULL);
1763
44
        }
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
44
    }
1775
1776
    /* Add the module's def to the global cache. */
1777
    // XXX Why special-case the main interpreter?
1778
44
    if (_Py_IsMainInterpreter(tstate->interp) || def->m_size == -1) {
1779
44
#ifndef NDEBUG
1780
44
        cached = _extensions_cache_get(path, name);
1781
44
        assert(cached == NULL || cached->def == def);
1782
44
#endif
1783
44
        cached = _extensions_cache_set(
1784
44
                path, name, def, m_init, singlephase->m_index, m_dict,
1785
44
                singlephase->origin, singlephase->md_gil);
1786
44
        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
44
    }
1792
1793
44
    return cached;
1794
44
}
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
44
{
1803
44
    assert(mod != NULL && PyModule_Check(mod));
1804
44
    assert(cached->def == _PyModule_GetDef(mod));
1805
1806
44
    Py_ssize_t index = _get_cached_module_index(cached);
1807
44
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1808
0
        return -1;
1809
0
    }
1810
1811
44
    if (modules != NULL) {
1812
44
        if (PyObject_SetItem(modules, name, mod) < 0) {
1813
0
            return -1;
1814
0
        }
1815
44
    }
1816
1817
44
    return 0;
1818
44
}
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
344
{
1937
    /* Only single-phase init modules will be in the cache. */
1938
344
    struct extensions_cache_value *cached
1939
344
            = _extensions_cache_get(info->path, info->name);
1940
344
    if (cached == NULL) {
1941
344
        return NULL;
1942
344
    }
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
344
{
1975
    /* Core modules go through _PyImport_FixupBuiltin(). */
1976
344
    assert(!is_core_module(tstate->interp, info->name, info->path));
1977
1978
344
    PyObject *mod = NULL;
1979
344
    PyModuleDef *def = NULL;
1980
344
    struct extensions_cache_value *cached = NULL;
1981
344
    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
344
    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
344
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2032
344
    if (main_tstate == NULL) {
2033
0
        return NULL;
2034
0
    }
2035
344
    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
344
    struct _Py_ext_module_loader_result res;
2043
344
    int rc = _PyImport_RunModInitFunc(p0, info, &res);
2044
344
    if (rc < 0) {
2045
        /* We discard res.def. */
2046
0
        assert(res.module == NULL);
2047
0
    }
2048
344
    else {
2049
344
        assert(!PyErr_Occurred());
2050
344
        assert(res.err == NULL);
2051
2052
344
        mod = res.module;
2053
344
        res.module = NULL;
2054
344
        def = res.def;
2055
344
        assert(def != NULL);
2056
2057
        /* Do anything else that should be done
2058
         * while still using the main interpreter. */
2059
344
        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
344
    }
2117
2118
344
main_finally:
2119
    /* Switch back to the subinterpreter. */
2120
344
    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
344
    if (rc < 0) {
2134
0
        _Py_ext_module_loader_result_apply_error(&res, name_buf);
2135
0
        goto error;
2136
0
    }
2137
2138
344
    if (res.kind == _Py_ext_module_kind_MULTIPHASE) {
2139
344
        assert_multiphase_def(def);
2140
344
        assert(mod == NULL);
2141
        /* Note that we cheat a little by not repeating the calls
2142
         * to _PyImport_GetModInitFunc() and _PyImport_RunModInitFunc(). */
2143
344
        mod = PyModule_FromDefAndSpec(def, spec);
2144
344
        if (mod == NULL) {
2145
0
            goto error;
2146
0
        }
2147
344
    }
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
344
    _Py_ext_module_loader_result_clear(&res);
2184
344
    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
344
}
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
44
{
2247
44
    int res = -1;
2248
44
    assert(mod != NULL && PyModule_Check(mod));
2249
2250
44
    PyObject *nameobj;
2251
44
    nameobj = PyUnicode_InternFromString(name);
2252
44
    if (nameobj == NULL) {
2253
0
        return -1;
2254
0
    }
2255
2256
44
    PyModuleDef *def = PyModule_GetDef(mod);
2257
44
    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
44
    assert(is_core_module(tstate->interp, nameobj, nameobj));
2267
44
    assert_singlephase_def(def);
2268
44
    assert(def->m_size == -1);
2269
44
    assert(def->m_base.m_copy == NULL);
2270
44
    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
44
    struct extensions_cache_value *cached
2277
44
            = _extensions_cache_get(nameobj, nameobj);
2278
44
    if (cached == NULL) {
2279
44
        struct singlephase_global_update singlephase = {
2280
44
            .m_index=def->m_base.m_index,
2281
            /* We don't want def->m_base.m_copy populated. */
2282
44
            .m_dict=NULL,
2283
44
            .origin=_Py_ext_module_origin_CORE,
2284
#ifdef Py_GIL_DISABLED
2285
            /* Unused when m_dict == NULL. */
2286
            .md_gil=NULL,
2287
#endif
2288
44
        };
2289
44
        cached = update_global_state_for_extension(
2290
44
                tstate, nameobj, nameobj, def, &singlephase);
2291
44
        if (cached == NULL) {
2292
0
            goto finally;
2293
0
        }
2294
44
    }
2295
2296
44
    if (finish_singlephase_extension(tstate, mod, cached, nameobj, modules) < 0) {
2297
0
        goto finally;
2298
0
    }
2299
2300
44
    res = 0;
2301
2302
44
finally:
2303
44
    Py_DECREF(nameobj);
2304
44
    return res;
2305
44
}
2306
2307
/* Helper to test for built-in module */
2308
2309
static int
2310
is_builtin(PyObject *name)
2311
1.53k
{
2312
1.53k
    int i;
2313
1.53k
    struct _inittab *inittab = INITTAB;
2314
52.1k
    for (i = 0; inittab[i].name != NULL; i++) {
2315
50.9k
        if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
2316
298
            if (inittab[i].initfunc == NULL)
2317
0
                return -1;
2318
298
            else
2319
298
                return 1;
2320
298
        }
2321
50.9k
    }
2322
1.23k
    return 0;
2323
1.53k
}
2324
2325
static PyObject*
2326
create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
2327
320
{
2328
320
    struct _Py_ext_module_loader_info info;
2329
320
    if (_Py_ext_module_loader_info_init_for_builtin(&info, name) < 0) {
2330
0
        return NULL;
2331
0
    }
2332
2333
320
    struct extensions_cache_value *cached = NULL;
2334
320
    PyObject *mod = import_find_extension(tstate, &info, &cached);
2335
320
    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
320
    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
320
    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
320
    struct _inittab *found = NULL;
2358
12.1k
    for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
2359
11.8k
        if (_PyUnicode_EqualToASCIIString(info.name, p->name)) {
2360
320
            found = p;
2361
320
        }
2362
11.8k
    }
2363
320
    if (found == NULL) {
2364
        // not found
2365
0
        mod = Py_NewRef(Py_None);
2366
0
        goto finally;
2367
0
    }
2368
2369
320
    PyModInitFunction p0 = (PyModInitFunction)found->initfunc;
2370
320
    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
320
    mod = import_run_extension(
2387
320
                    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
320
finally:
2396
320
    _Py_ext_module_loader_info_clear(&info);
2397
320
    return mod;
2398
320
}
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
22
{
2480
22
    size_t size;
2481
836
    for (size = 0; PyImport_Inittab[size].name != NULL; size++)
2482
814
        ;
2483
22
    size++;
2484
2485
    /* Make the copy. */
2486
22
    struct _inittab *copied = _PyMem_DefaultRawMalloc(size * sizeof(struct _inittab));
2487
22
    if (copied == NULL) {
2488
0
        return -1;
2489
0
    }
2490
22
    memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
2491
22
    INITTAB = copied;
2492
22
    return 0;
2493
22
}
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
22
{
2506
22
    PyObject *list = PyList_New(0);
2507
22
    if (list == NULL) {
2508
0
        return NULL;
2509
0
    }
2510
22
    struct _inittab *inittab = INITTAB;
2511
836
    for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
2512
814
        PyObject *name = PyUnicode_FromString(inittab[i].name);
2513
814
        if (name == NULL) {
2514
0
            Py_DECREF(list);
2515
0
            return NULL;
2516
0
        }
2517
814
        if (PyList_Append(list, name) < 0) {
2518
0
            Py_DECREF(name);
2519
0
            Py_DECREF(list);
2520
0
            return NULL;
2521
0
        }
2522
814
        Py_DECREF(name);
2523
814
    }
2524
22
    return list;
2525
22
}
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
22
{
2633
22
    PyObject *m, *d;
2634
2635
22
    m = import_add_module(tstate, name);
2636
22
    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
22
    d = PyModule_GetDict(m);
2641
22
    int r = PyDict_Contains(d, &_Py_ID(__builtins__));
2642
22
    if (r == 0) {
2643
22
        r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
2644
22
    }
2645
22
    if (r < 0) {
2646
0
        remove_module(tstate, name);
2647
0
        Py_DECREF(m);
2648
0
        return NULL;
2649
0
    }
2650
2651
22
    Py_INCREF(d);
2652
22
    Py_DECREF(m);
2653
22
    return d;
2654
22
}
2655
2656
static PyObject *
2657
exec_code_in_module(PyThreadState *tstate, PyObject *name,
2658
                    PyObject *module_dict, PyObject *code_object)
2659
22
{
2660
22
    PyObject *v, *m;
2661
2662
22
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
2663
22
    if (v == NULL) {
2664
0
        remove_module(tstate, name);
2665
0
        return NULL;
2666
0
    }
2667
22
    Py_DECREF(v);
2668
2669
22
    m = import_get_module(tstate, name);
2670
22
    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
22
    return m;
2677
22
}
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
344
{
2736
344
    PyObject *oldname;
2737
2738
344
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2739
344
        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
560
{
2759
560
    const struct _module_alias *entry;
2760
4.20k
    for (entry = aliases; ; entry++) {
2761
4.20k
        if (entry->name == NULL) {
2762
            /* It isn't an alias. */
2763
450
            return false;
2764
450
        }
2765
3.75k
        if (strcmp(name, entry->name) == 0) {
2766
110
            if (alias != NULL) {
2767
110
                *alias = entry->orig;
2768
110
            }
2769
110
            return true;
2770
110
        }
2771
3.75k
    }
2772
560
}
2773
2774
static bool
2775
use_frozen(void)
2776
1.39k
{
2777
1.39k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2778
1.39k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2779
1.39k
    if (override > 0) {
2780
0
        return true;
2781
0
    }
2782
1.39k
    else if (override < 0) {
2783
0
        return false;
2784
0
    }
2785
1.39k
    else {
2786
1.39k
        return interp->config.use_frozen_modules;
2787
1.39k
    }
2788
1.39k
}
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
1.54k
{
2918
1.54k
    const struct _frozen *p;
2919
    // We always use the bootstrap modules.
2920
5.85k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
2921
5.85k
        if (p->name == NULL) {
2922
            // We hit the end-of-list sentinel value.
2923
1.39k
            break;
2924
1.39k
        }
2925
4.46k
        if (strcmp(name, p->name) == 0) {
2926
154
            return p;
2927
154
        }
2928
4.46k
    }
2929
    // Prefer custom modules, if any.  Frozen stdlib modules can be
2930
    // disabled here by setting "code" to NULL in the array entry.
2931
1.39k
    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
1.39k
    if (use_frozen()) {
2943
17.2k
        for (p = _PyImport_FrozenStdlib; ; p++) {
2944
17.2k
            if (p->name == NULL) {
2945
986
                break;
2946
986
            }
2947
16.2k
            if (strcmp(name, p->name) == 0) {
2948
406
                return p;
2949
406
            }
2950
16.2k
        }
2951
11.8k
        for (p = _PyImport_FrozenTest; ; p++) {
2952
11.8k
            if (p->name == NULL) {
2953
986
                break;
2954
986
            }
2955
10.8k
            if (strcmp(name, p->name) == 0) {
2956
0
                return p;
2957
0
            }
2958
10.8k
        }
2959
986
    }
2960
986
    return NULL;
2961
1.39k
}
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
1.54k
{
2975
1.54k
    if (info != NULL) {
2976
1.54k
        memset(info, 0, sizeof(*info));
2977
1.54k
    }
2978
2979
1.54k
    if (nameobj == NULL || nameobj == Py_None) {
2980
0
        return FROZEN_BAD_NAME;
2981
0
    }
2982
1.54k
    const char *name = PyUnicode_AsUTF8(nameobj);
2983
1.54k
    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
1.54k
    const struct _frozen *p = look_up_frozen(name);
2993
1.54k
    if (p == NULL) {
2994
986
        return FROZEN_NOT_FOUND;
2995
986
    }
2996
560
    if (info != NULL) {
2997
560
        info->nameobj = nameobj;  // borrowed
2998
560
        info->data = (const char *)p->code;
2999
560
        info->size = p->size;
3000
560
        info->is_package = p->is_package;
3001
560
        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
560
        info->origname = name;
3007
560
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3008
560
                                              &info->origname);
3009
560
    }
3010
560
    if (p->code == NULL) {
3011
        /* It is frozen but marked as un-importable. */
3012
0
        return FROZEN_EXCLUDED;
3013
0
    }
3014
560
    if (p->code[0] == '\0' || p->size == 0) {
3015
        /* Does not contain executable code. */
3016
0
        return FROZEN_INVALID;
3017
0
    }
3018
560
    return FROZEN_OKAY;
3019
560
}
3020
3021
static PyObject *
3022
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3023
269
{
3024
269
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3025
269
    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
269
    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
269
    return co;
3040
269
}
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
22
{
3051
22
    PyThreadState *tstate = _PyThreadState_GET();
3052
22
    PyObject *co, *m, *d = NULL;
3053
22
    int err;
3054
3055
22
    struct frozen_info info;
3056
22
    frozen_status status = find_frozen(name, &info);
3057
22
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3058
0
        return 0;
3059
0
    }
3060
22
    else if (status == FROZEN_BAD_NAME) {
3061
0
        return 0;
3062
0
    }
3063
22
    else if (status != FROZEN_OKAY) {
3064
0
        set_frozen_error(status, name);
3065
0
        return -1;
3066
0
    }
3067
22
    co = unmarshal_frozen_code(tstate->interp, &info);
3068
22
    if (co == NULL) {
3069
0
        return -1;
3070
0
    }
3071
22
    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
22
    d = module_dict_for_exec(tstate, name);
3090
22
    if (d == NULL) {
3091
0
        goto err_return;
3092
0
    }
3093
22
    m = exec_code_in_module(tstate, name, d, co);
3094
22
    if (m == NULL) {
3095
0
        goto err_return;
3096
0
    }
3097
22
    Py_DECREF(m);
3098
    /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
3099
22
    PyObject *origname;
3100
22
    if (info.origname) {
3101
22
        origname = PyUnicode_FromString(info.origname);
3102
22
        if (origname == NULL) {
3103
0
            goto err_return;
3104
0
        }
3105
22
    }
3106
0
    else {
3107
0
        origname = Py_NewRef(Py_None);
3108
0
    }
3109
22
    err = PyDict_SetItemString(d, "__origname__", origname);
3110
22
    Py_DECREF(origname);
3111
22
    if (err != 0) {
3112
0
        goto err_return;
3113
0
    }
3114
22
    Py_DECREF(d);
3115
22
    Py_DECREF(co);
3116
22
    return 1;
3117
3118
0
err_return:
3119
0
    Py_XDECREF(d);
3120
0
    Py_DECREF(co);
3121
0
    return -1;
3122
22
}
3123
3124
int
3125
PyImport_ImportFrozenModule(const char *name)
3126
22
{
3127
22
    PyObject *nameobj;
3128
22
    int ret;
3129
22
    nameobj = PyUnicode_InternFromString(name);
3130
22
    if (nameobj == NULL)
3131
0
        return -1;
3132
22
    ret = PyImport_ImportFrozenModuleObject(nameobj);
3133
22
    Py_DECREF(nameobj);
3134
22
    return ret;
3135
22
}
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
22
{
3149
22
    PyObject *name = PyUnicode_FromString("_imp");
3150
22
    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
22
    PyObject *attrs = Py_BuildValue("{sO}", "name", name);
3159
22
    if (attrs == NULL) {
3160
0
        goto error;
3161
0
    }
3162
22
    PyObject *spec = _PyNamespace_New(attrs);
3163
22
    Py_DECREF(attrs);
3164
22
    if (spec == NULL) {
3165
0
        goto error;
3166
0
    }
3167
3168
    // Create the _imp module from its definition.
3169
22
    PyObject *mod = create_builtin(tstate, name, spec);
3170
22
    Py_CLEAR(name);
3171
22
    Py_DECREF(spec);
3172
22
    if (mod == NULL) {
3173
0
        goto error;
3174
0
    }
3175
22
    assert(mod != Py_None);  // not found
3176
3177
    // Execute the _imp module: call imp_module_exec().
3178
22
    if (exec_builtin_or_dynamic(mod) < 0) {
3179
0
        Py_DECREF(mod);
3180
0
        goto error;
3181
0
    }
3182
22
    return mod;
3183
3184
0
error:
3185
0
    Py_XDECREF(name);
3186
0
    return NULL;
3187
22
}
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
22
{
3203
22
    assert(!_PyErr_Occurred(tstate));
3204
3205
22
    PyInterpreterState *interp = tstate->interp;
3206
22
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3207
3208
    // Import _importlib through its frozen version, _frozen_importlib.
3209
22
    if (verbose) {
3210
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
3211
0
    }
3212
22
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
3213
0
        return -1;
3214
0
    }
3215
3216
22
    PyObject *importlib = PyImport_AddModuleRef("_frozen_importlib");
3217
22
    if (importlib == NULL) {
3218
0
        return -1;
3219
0
    }
3220
22
    IMPORTLIB(interp) = importlib;
3221
3222
    // Import the _imp module
3223
22
    if (verbose) {
3224
0
        PySys_FormatStderr("import _imp # builtin\n");
3225
0
    }
3226
22
    PyObject *imp_mod = bootstrap_imp(tstate);
3227
22
    if (imp_mod == NULL) {
3228
0
        return -1;
3229
0
    }
3230
22
    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
22
    PyObject *value = PyObject_CallMethod(importlib, "_install",
3237
22
                                          "OO", sysmod, imp_mod);
3238
22
    Py_DECREF(imp_mod);
3239
22
    if (value == NULL) {
3240
0
        return -1;
3241
0
    }
3242
22
    Py_DECREF(value);
3243
3244
22
    assert(!_PyErr_Occurred(tstate));
3245
22
    return 0;
3246
22
}
3247
3248
3249
static int
3250
init_importlib_external(PyInterpreterState *interp)
3251
22
{
3252
22
    PyObject *value;
3253
22
    value = PyObject_CallMethod(IMPORTLIB(interp),
3254
22
                                "_install_external_importers", "");
3255
22
    if (value == NULL) {
3256
0
        return -1;
3257
0
    }
3258
22
    Py_DECREF(value);
3259
22
    return 0;
3260
22
}
3261
3262
PyObject *
3263
_PyImport_GetImportlibLoader(PyInterpreterState *interp,
3264
                             const char *loader_name)
3265
22
{
3266
22
    return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
3267
22
}
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
22
{
3395
    // Get the __import__ function
3396
22
    PyObject *import_func;
3397
22
    if (PyDict_GetItemStringRef(interp->builtins, "__import__", &import_func) <= 0) {
3398
0
        return -1;
3399
0
    }
3400
22
    IMPORT_FUNC(interp) = import_func;
3401
22
    return 0;
3402
22
}
3403
3404
int
3405
_PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
3406
2.09M
{
3407
2.09M
    return func == IMPORT_FUNC(interp);
3408
2.09M
}
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
17.7k
{
3417
17.7k
    PyObject *pname;
3418
17.7k
    PyObject *result;
3419
3420
17.7k
    pname = PyUnicode_FromString(name);
3421
17.7k
    if (pname == NULL)
3422
0
        return NULL;
3423
17.7k
    result = PyImport_Import(pname);
3424
17.7k
    Py_DECREF(pname);
3425
17.7k
    return result;
3426
17.7k
}
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
619
{
3458
619
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3459
619
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3460
619
    const char *remove_frames = "_call_with_frames_removed";
3461
619
    int always_trim = 0;
3462
619
    int in_importlib = 0;
3463
619
    PyObject **prev_link, **outer_link = NULL;
3464
619
    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
619
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3471
619
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3472
0
        goto done;
3473
0
    }
3474
3475
619
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3476
619
        always_trim = 1;
3477
619
    }
3478
3479
619
    assert(PyExceptionInstance_Check(exc));
3480
619
    base_tb = PyException_GetTraceback(exc);
3481
619
    prev_link = &base_tb;
3482
619
    PyObject *tb = base_tb;
3483
1.86k
    while (tb != NULL) {
3484
1.24k
        assert(PyTraceBack_Check(tb));
3485
1.24k
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3486
1.24k
        PyObject *next = (PyObject *) traceback->tb_next;
3487
1.24k
        PyFrameObject *frame = traceback->tb_frame;
3488
1.24k
        PyCodeObject *code = PyFrame_GetCode(frame);
3489
1.24k
        int now_in_importlib;
3490
3491
1.24k
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3492
1.24k
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3493
1.24k
        if (now_in_importlib && !in_importlib) {
3494
            /* This is the link to this chunk of importlib tracebacks */
3495
619
            outer_link = prev_link;
3496
619
        }
3497
1.24k
        in_importlib = now_in_importlib;
3498
3499
1.24k
        if (in_importlib &&
3500
1.24k
            (always_trim ||
3501
1.24k
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3502
1.24k
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3503
1.24k
            prev_link = outer_link;
3504
1.24k
        }
3505
1
        else {
3506
1
            prev_link = (PyObject **) &traceback->tb_next;
3507
1
        }
3508
1.24k
        Py_DECREF(code);
3509
1.24k
        tb = next;
3510
1.24k
    }
3511
619
    if (base_tb == NULL) {
3512
618
        base_tb = Py_None;
3513
618
        Py_INCREF(Py_None);
3514
618
    }
3515
619
    PyException_SetTraceback(exc, base_tb);
3516
619
done:
3517
619
    Py_XDECREF(base_tb);
3518
619
    _PyErr_SetRaisedException(tstate, exc);
3519
619
}
3520
3521
3522
static PyObject *
3523
resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
3524
59
{
3525
59
    PyObject *abs_name;
3526
59
    PyObject *package = NULL;
3527
59
    PyObject *spec = NULL;
3528
59
    Py_ssize_t last_dot;
3529
59
    PyObject *base;
3530
59
    int level_up;
3531
3532
59
    if (globals == NULL) {
3533
0
        _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
3534
0
        goto error;
3535
0
    }
3536
59
    if (!PyDict_Check(globals)) {
3537
0
        _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
3538
0
        goto error;
3539
0
    }
3540
59
    if (PyDict_GetItemRef(globals, &_Py_ID(__package__), &package) < 0) {
3541
0
        goto error;
3542
0
    }
3543
59
    if (package == Py_None) {
3544
0
        Py_DECREF(package);
3545
0
        package = NULL;
3546
0
    }
3547
59
    if (PyDict_GetItemRef(globals, &_Py_ID(__spec__), &spec) < 0) {
3548
0
        goto error;
3549
0
    }
3550
3551
59
    if (package != NULL) {
3552
59
        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
59
        else if (spec != NULL && spec != Py_None) {
3558
59
            int equal;
3559
59
            PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
3560
59
            if (parent == NULL) {
3561
0
                goto error;
3562
0
            }
3563
3564
59
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
3565
59
            Py_DECREF(parent);
3566
59
            if (equal < 0) {
3567
0
                goto error;
3568
0
            }
3569
59
            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
59
        }
3576
59
    }
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
59
    last_dot = PyUnicode_GET_LENGTH(package);
3634
59
    if (last_dot == 0) {
3635
0
        goto no_parent_error;
3636
0
    }
3637
3638
59
    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
59
    Py_XDECREF(spec);
3652
59
    base = PyUnicode_Substring(package, 0, last_dot);
3653
59
    Py_DECREF(package);
3654
59
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
3655
36
        return base;
3656
36
    }
3657
3658
23
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3659
23
    Py_DECREF(base);
3660
23
    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
1.46k
{
3676
1.46k
    PyObject *mod = NULL;
3677
1.46k
    PyInterpreterState *interp = tstate->interp;
3678
1.46k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
3679
1.46k
#define import_level FIND_AND_LOAD(interp).import_level
3680
1.46k
#define accumulated FIND_AND_LOAD(interp).accumulated
3681
3682
1.46k
    PyTime_t t1 = 0, accumulated_copy = accumulated;
3683
3684
1.46k
    PyObject *sys_path, *sys_meta_path, *sys_path_hooks;
3685
1.46k
    if (PySys_GetOptionalAttrString("path", &sys_path) < 0) {
3686
0
        return NULL;
3687
0
    }
3688
1.46k
    if (PySys_GetOptionalAttrString("meta_path", &sys_meta_path) < 0) {
3689
0
        Py_XDECREF(sys_path);
3690
0
        return NULL;
3691
0
    }
3692
1.46k
    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
1.46k
    if (_PySys_Audit(tstate, "import", "OOOOO",
3698
1.46k
                     abs_name, Py_None, sys_path ? sys_path : Py_None,
3699
1.46k
                     sys_meta_path ? sys_meta_path : Py_None,
3700
1.46k
                     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
1.46k
    Py_XDECREF(sys_path_hooks);
3707
1.46k
    Py_XDECREF(sys_meta_path);
3708
1.46k
    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
1.46k
    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
1.46k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
3726
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
3727
3728
1.46k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
3729
1.46k
                                     abs_name, IMPORT_FUNC(interp), NULL);
3730
3731
1.46k
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
3732
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
3733
0
                                       mod != NULL);
3734
3735
1.46k
    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
1.46k
    return mod;
3750
1.46k
#undef import_level
3751
1.46k
#undef accumulated
3752
1.46k
}
3753
3754
PyObject *
3755
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
3756
                                 PyObject *locals, PyObject *fromlist,
3757
                                 int level)
3758
2.40M
{
3759
2.40M
    PyThreadState *tstate = _PyThreadState_GET();
3760
2.40M
    PyObject *abs_name = NULL;
3761
2.40M
    PyObject *final_mod = NULL;
3762
2.40M
    PyObject *mod = NULL;
3763
2.40M
    PyObject *package = NULL;
3764
2.40M
    PyInterpreterState *interp = tstate->interp;
3765
2.40M
    int has_from;
3766
3767
2.40M
    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
2.40M
    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
2.40M
    if (level < 0) {
3781
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
3782
0
        goto error;
3783
0
    }
3784
3785
2.40M
    if (level > 0) {
3786
59
        abs_name = resolve_name(tstate, name, globals, level);
3787
59
        if (abs_name == NULL)
3788
0
            goto error;
3789
59
    }
3790
2.40M
    else {  /* level == 0 */
3791
2.40M
        if (PyUnicode_GET_LENGTH(name) == 0) {
3792
0
            _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3793
0
            goto error;
3794
0
        }
3795
2.40M
        abs_name = Py_NewRef(name);
3796
2.40M
    }
3797
3798
2.40M
    mod = import_get_module(tstate, abs_name);
3799
2.40M
    if (mod == NULL && _PyErr_Occurred(tstate)) {
3800
0
        goto error;
3801
0
    }
3802
3803
2.40M
    if (mod != NULL && mod != Py_None) {
3804
2.40M
        if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
3805
0
            goto error;
3806
0
        }
3807
2.40M
    }
3808
1.46k
    else {
3809
1.46k
        Py_XDECREF(mod);
3810
1.46k
        mod = import_find_and_load(tstate, abs_name);
3811
1.46k
        if (mod == NULL) {
3812
619
            goto error;
3813
619
        }
3814
1.46k
    }
3815
3816
2.40M
    has_from = 0;
3817
2.40M
    if (fromlist != NULL && fromlist != Py_None) {
3818
259k
        has_from = PyObject_IsTrue(fromlist);
3819
259k
        if (has_from < 0)
3820
0
            goto error;
3821
259k
    }
3822
2.40M
    if (!has_from) {
3823
2.40M
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3824
2.40M
        if (level == 0 || len > 0) {
3825
2.40M
            Py_ssize_t dot;
3826
3827
2.40M
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
3828
2.40M
            if (dot == -2) {
3829
0
                goto error;
3830
0
            }
3831
3832
2.40M
            if (dot == -1) {
3833
                /* No dot in module name, simple exit */
3834
2.40M
                final_mod = Py_NewRef(mod);
3835
2.40M
                goto error;
3836
2.40M
            }
3837
3838
344
            if (level == 0) {
3839
344
                PyObject *front = PyUnicode_Substring(name, 0, dot);
3840
344
                if (front == NULL) {
3841
0
                    goto error;
3842
0
                }
3843
3844
344
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
3845
344
                Py_DECREF(front);
3846
344
            }
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
344
        }
3870
0
        else {
3871
0
            final_mod = Py_NewRef(mod);
3872
0
        }
3873
2.40M
    }
3874
929
    else {
3875
929
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
3876
929
        if (has_path < 0) {
3877
0
            goto error;
3878
0
        }
3879
929
        if (has_path) {
3880
52
            final_mod = PyObject_CallMethodObjArgs(
3881
52
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
3882
52
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
3883
52
        }
3884
877
        else {
3885
877
            final_mod = Py_NewRef(mod);
3886
877
        }
3887
929
    }
3888
3889
2.40M
  error:
3890
2.40M
    Py_XDECREF(abs_name);
3891
2.40M
    Py_XDECREF(mod);
3892
2.40M
    Py_XDECREF(package);
3893
2.40M
    if (final_mod == NULL) {
3894
619
        remove_importlib_frames(tstate);
3895
619
    }
3896
2.40M
    return final_mod;
3897
2.40M
}
3898
3899
PyObject *
3900
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
3901
                           PyObject *fromlist, int level)
3902
48.1k
{
3903
48.1k
    PyObject *nameobj, *mod;
3904
48.1k
    nameobj = PyUnicode_FromString(name);
3905
48.1k
    if (nameobj == NULL)
3906
0
        return NULL;
3907
48.1k
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
3908
48.1k
                                           fromlist, level);
3909
48.1k
    Py_DECREF(nameobj);
3910
48.1k
    return mod;
3911
48.1k
}
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
258k
{
3951
258k
    PyThreadState *tstate = _PyThreadState_GET();
3952
258k
    PyObject *globals = NULL;
3953
258k
    PyObject *import = NULL;
3954
258k
    PyObject *builtins = NULL;
3955
258k
    PyObject *r = NULL;
3956
3957
258k
    PyObject *from_list = PyList_New(0);
3958
258k
    if (from_list == NULL) {
3959
0
        goto err;
3960
0
    }
3961
3962
    /* Get the builtins from current globals */
3963
258k
    globals = PyEval_GetGlobals();  // borrowed
3964
258k
    if (globals != NULL) {
3965
210k
        Py_INCREF(globals);
3966
        // XXX Use _PyEval_EnsureBuiltins()?
3967
210k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
3968
210k
        if (builtins == NULL) {
3969
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
3970
0
            goto err;
3971
0
        }
3972
210k
    }
3973
48.1k
    else if (_PyErr_Occurred(tstate)) {
3974
0
        goto err;
3975
0
    }
3976
48.1k
    else {
3977
        /* No globals -- use standard builtins, and fake globals */
3978
48.1k
        globals = PyDict_New();
3979
48.1k
        if (globals == NULL) {
3980
0
            goto err;
3981
0
        }
3982
48.1k
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
3983
0
            goto err;
3984
0
        }
3985
48.1k
    }
3986
3987
    /* Get the __import__ function from the builtins */
3988
258k
    if (PyDict_Check(builtins)) {
3989
210k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
3990
210k
        if (import == NULL) {
3991
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
3992
0
        }
3993
210k
    }
3994
48.1k
    else
3995
48.1k
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
3996
258k
    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
258k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4003
258k
                              globals, from_list, 0, NULL);
4004
258k
    if (r == NULL)
4005
0
        goto err;
4006
258k
    Py_DECREF(r);
4007
4008
258k
    r = import_get_module(tstate, module_name);
4009
258k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4010
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4011
0
    }
4012
4013
258k
  err:
4014
258k
    Py_XDECREF(globals);
4015
258k
    Py_XDECREF(builtins);
4016
258k
    Py_XDECREF(import);
4017
258k
    Py_XDECREF(from_list);
4018
4019
258k
    return r;
4020
258k
}
4021
4022
4023
/*********************/
4024
/* runtime lifecycle */
4025
/*********************/
4026
4027
PyStatus
4028
_PyImport_Init(void)
4029
22
{
4030
22
    if (INITTAB != NULL) {
4031
0
        return _PyStatus_ERR("global import state already initialized");
4032
0
    }
4033
22
    if (init_builtin_modules_table() != 0) {
4034
0
        return PyStatus_NoMemory();
4035
0
    }
4036
22
    return _PyStatus_OK();
4037
22
}
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
22
{
4070
    // XXX Initialize here: interp->modules and interp->import_func.
4071
    // XXX Initialize here: sys.modules and sys.meta_path.
4072
4073
22
    if (importlib) {
4074
        /* This call sets up builtin and frozen import support */
4075
22
        if (init_importlib(tstate, sysmod) < 0) {
4076
0
            return _PyStatus_ERR("failed to initialize importlib");
4077
0
        }
4078
22
    }
4079
4080
22
    return _PyStatus_OK();
4081
22
}
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
22
{
4135
22
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4136
22
    if (path_hooks == NULL) {
4137
0
        return -1;
4138
0
    }
4139
4140
22
    if (verbose) {
4141
0
        PySys_WriteStderr("# installing zipimport hook\n");
4142
0
    }
4143
4144
22
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4145
22
    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
22
    else {
4152
        /* sys.path_hooks.insert(0, zipimporter) */
4153
22
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4154
22
        Py_DECREF(zipimporter);
4155
22
        if (err < 0) {
4156
0
            Py_DECREF(path_hooks);
4157
0
            return -1;
4158
0
        }
4159
22
        if (verbose) {
4160
0
            PySys_WriteStderr("# installed zipimport hook\n");
4161
0
        }
4162
22
    }
4163
22
    Py_DECREF(path_hooks);
4164
4165
22
    return 0;
4166
22
}
4167
4168
PyStatus
4169
_PyImport_InitExternal(PyThreadState *tstate)
4170
22
{
4171
22
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4172
4173
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4174
4175
22
    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
22
    if (init_zipimport(tstate, verbose) != 0) {
4181
0
        PyErr_Print();
4182
0
        return _PyStatus_ERR("initializing zipimport failed");
4183
0
    }
4184
4185
22
    return _PyStatus_OK();
4186
22
}
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
4.47k
{
4213
4.47k
    PyObject *mod = PyImport_Import(modname);
4214
4.47k
    if (mod == NULL) {
4215
0
        return NULL;
4216
0
    }
4217
4.47k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4218
4.47k
    Py_DECREF(mod);
4219
4.47k
    return result;
4220
4.47k
}
4221
4222
PyObject *
4223
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4224
4.17k
{
4225
4.17k
    PyObject *pmodname = PyUnicode_FromString(modname);
4226
4.17k
    if (pmodname == NULL) {
4227
0
        return NULL;
4228
0
    }
4229
4.17k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4230
4.17k
    if (pattrname == NULL) {
4231
0
        Py_DECREF(pmodname);
4232
0
        return NULL;
4233
0
    }
4234
4.17k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4235
4.17k
    Py_DECREF(pattrname);
4236
4.17k
    Py_DECREF(pmodname);
4237
4.17k
    return result;
4238
4.17k
}
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
_imp.acquire_lock
4263
4264
Acquires the interpreter's import lock for the current thread.
4265
4266
This lock should be used by import hooks to ensure thread-safety when importing
4267
modules. On platforms without threads, this function does nothing.
4268
[clinic start generated code]*/
4269
4270
static PyObject *
4271
_imp_acquire_lock_impl(PyObject *module)
4272
/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
4273
6.78k
{
4274
6.78k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4275
6.78k
    _PyImport_AcquireLock(interp);
4276
6.78k
    Py_RETURN_NONE;
4277
6.78k
}
4278
4279
/*[clinic input]
4280
_imp.release_lock
4281
4282
Release the interpreter's import lock.
4283
4284
On platforms without threads, this function does nothing.
4285
[clinic start generated code]*/
4286
4287
static PyObject *
4288
_imp_release_lock_impl(PyObject *module)
4289
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
4290
6.78k
{
4291
6.78k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4292
6.78k
    if (!_PyRecursiveMutex_IsLockedByCurrentThread(&IMPORT_LOCK(interp))) {
4293
0
        PyErr_SetString(PyExc_RuntimeError,
4294
0
                        "not holding the import lock");
4295
0
        return NULL;
4296
0
    }
4297
6.78k
    _PyImport_ReleaseLock(interp);
4298
6.78k
    Py_RETURN_NONE;
4299
6.78k
}
4300
4301
4302
/*[clinic input]
4303
_imp._fix_co_filename
4304
4305
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
4306
        Code object to change.
4307
4308
    path: unicode
4309
        File path to use.
4310
    /
4311
4312
Changes code.co_filename to specify the passed-in file path.
4313
[clinic start generated code]*/
4314
4315
static PyObject *
4316
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
4317
                           PyObject *path)
4318
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
4319
4320
344
{
4321
344
    update_compiled_module(code, path);
4322
4323
344
    Py_RETURN_NONE;
4324
344
}
4325
4326
4327
/*[clinic input]
4328
_imp.create_builtin
4329
4330
    spec: object
4331
    /
4332
4333
Create an extension module.
4334
[clinic start generated code]*/
4335
4336
static PyObject *
4337
_imp_create_builtin(PyObject *module, PyObject *spec)
4338
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
4339
298
{
4340
298
    PyThreadState *tstate = _PyThreadState_GET();
4341
4342
298
    PyObject *name = PyObject_GetAttrString(spec, "name");
4343
298
    if (name == NULL) {
4344
0
        return NULL;
4345
0
    }
4346
4347
298
    if (!PyUnicode_Check(name)) {
4348
0
        PyErr_Format(PyExc_TypeError,
4349
0
                     "name must be string, not %.200s",
4350
0
                     Py_TYPE(name)->tp_name);
4351
0
        Py_DECREF(name);
4352
0
        return NULL;
4353
0
    }
4354
4355
298
    PyObject *mod = create_builtin(tstate, name, spec);
4356
298
    Py_DECREF(name);
4357
298
    return mod;
4358
298
}
4359
4360
4361
/*[clinic input]
4362
_imp.extension_suffixes
4363
4364
Returns the list of file suffixes used to identify extension modules.
4365
[clinic start generated code]*/
4366
4367
static PyObject *
4368
_imp_extension_suffixes_impl(PyObject *module)
4369
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
4370
44
{
4371
44
    PyObject *list;
4372
4373
44
    list = PyList_New(0);
4374
44
    if (list == NULL)
4375
0
        return NULL;
4376
44
#ifdef HAVE_DYNAMIC_LOADING
4377
44
    const char *suffix;
4378
44
    unsigned int index = 0;
4379
4380
176
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
4381
132
        PyObject *item = PyUnicode_FromString(suffix);
4382
132
        if (item == NULL) {
4383
0
            Py_DECREF(list);
4384
0
            return NULL;
4385
0
        }
4386
132
        if (PyList_Append(list, item) < 0) {
4387
0
            Py_DECREF(list);
4388
0
            Py_DECREF(item);
4389
0
            return NULL;
4390
0
        }
4391
132
        Py_DECREF(item);
4392
132
        index += 1;
4393
132
    }
4394
44
#endif
4395
44
    return list;
4396
44
}
4397
4398
/*[clinic input]
4399
_imp.init_frozen
4400
4401
    name: unicode
4402
    /
4403
4404
Initializes a frozen module.
4405
[clinic start generated code]*/
4406
4407
static PyObject *
4408
_imp_init_frozen_impl(PyObject *module, PyObject *name)
4409
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
4410
0
{
4411
0
    PyThreadState *tstate = _PyThreadState_GET();
4412
0
    int ret;
4413
4414
0
    ret = PyImport_ImportFrozenModuleObject(name);
4415
0
    if (ret < 0)
4416
0
        return NULL;
4417
0
    if (ret == 0) {
4418
0
        Py_RETURN_NONE;
4419
0
    }
4420
0
    return import_add_module(tstate, name);
4421
0
}
4422
4423
/*[clinic input]
4424
_imp.find_frozen
4425
4426
    name: unicode
4427
    /
4428
    *
4429
    withdata: bool = False
4430
4431
Return info about the corresponding frozen module (if there is one) or None.
4432
4433
The returned info (a 2-tuple):
4434
4435
 * data         the raw marshalled bytes
4436
 * is_package   whether or not it is a package
4437
 * origname     the originally frozen module's name, or None if not
4438
                a stdlib module (this will usually be the same as
4439
                the module's current name)
4440
[clinic start generated code]*/
4441
4442
static PyObject *
4443
_imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
4444
/*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
4445
1.23k
{
4446
1.23k
    struct frozen_info info;
4447
1.23k
    frozen_status status = find_frozen(name, &info);
4448
1.23k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
4449
986
        Py_RETURN_NONE;
4450
986
    }
4451
247
    else if (status == FROZEN_BAD_NAME) {
4452
0
        Py_RETURN_NONE;
4453
0
    }
4454
247
    else if (status != FROZEN_OKAY) {
4455
0
        set_frozen_error(status, name);
4456
0
        return NULL;
4457
0
    }
4458
4459
247
    PyObject *data = NULL;
4460
247
    if (withdata) {
4461
0
        data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
4462
0
        if (data == NULL) {
4463
0
            return NULL;
4464
0
        }
4465
0
    }
4466
4467
247
    PyObject *origname = NULL;
4468
247
    if (info.origname != NULL && info.origname[0] != '\0') {
4469
247
        origname = PyUnicode_FromString(info.origname);
4470
247
        if (origname == NULL) {
4471
0
            Py_XDECREF(data);
4472
0
            return NULL;
4473
0
        }
4474
247
    }
4475
4476
247
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
4477
247
                                    info.is_package ? Py_True : Py_False,
4478
247
                                    origname ? origname : Py_None);
4479
247
    Py_XDECREF(origname);
4480
247
    Py_XDECREF(data);
4481
247
    return result;
4482
247
}
4483
4484
/*[clinic input]
4485
_imp.get_frozen_object
4486
4487
    name: unicode
4488
    data as dataobj: object = None
4489
    /
4490
4491
Create a code object for a frozen module.
4492
[clinic start generated code]*/
4493
4494
static PyObject *
4495
_imp_get_frozen_object_impl(PyObject *module, PyObject *name,
4496
                            PyObject *dataobj)
4497
/*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
4498
247
{
4499
247
    struct frozen_info info = {0};
4500
247
    Py_buffer buf = {0};
4501
247
    if (PyObject_CheckBuffer(dataobj)) {
4502
0
        if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
4503
0
            return NULL;
4504
0
        }
4505
0
        info.data = (const char *)buf.buf;
4506
0
        info.size = buf.len;
4507
0
    }
4508
247
    else if (dataobj != Py_None) {
4509
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
4510
0
        return NULL;
4511
0
    }
4512
247
    else {
4513
247
        frozen_status status = find_frozen(name, &info);
4514
247
        if (status != FROZEN_OKAY) {
4515
0
            set_frozen_error(status, name);
4516
0
            return NULL;
4517
0
        }
4518
247
    }
4519
4520
247
    if (info.nameobj == NULL) {
4521
0
        info.nameobj = name;
4522
0
    }
4523
247
    if (info.size == 0) {
4524
        /* Does not contain executable code. */
4525
0
        set_frozen_error(FROZEN_INVALID, name);
4526
0
        return NULL;
4527
0
    }
4528
4529
247
    PyInterpreterState *interp = _PyInterpreterState_GET();
4530
247
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
4531
247
    if (dataobj != Py_None) {
4532
0
        PyBuffer_Release(&buf);
4533
0
    }
4534
247
    return codeobj;
4535
247
}
4536
4537
/*[clinic input]
4538
_imp.is_frozen_package
4539
4540
    name: unicode
4541
    /
4542
4543
Returns True if the module name is of a frozen package.
4544
[clinic start generated code]*/
4545
4546
static PyObject *
4547
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
4548
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
4549
22
{
4550
22
    struct frozen_info info;
4551
22
    frozen_status status = find_frozen(name, &info);
4552
22
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
4553
0
        set_frozen_error(status, name);
4554
0
        return NULL;
4555
0
    }
4556
22
    return PyBool_FromLong(info.is_package);
4557
22
}
4558
4559
/*[clinic input]
4560
_imp.is_builtin
4561
4562
    name: unicode
4563
    /
4564
4565
Returns True if the module name corresponds to a built-in module.
4566
[clinic start generated code]*/
4567
4568
static PyObject *
4569
_imp_is_builtin_impl(PyObject *module, PyObject *name)
4570
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
4571
1.53k
{
4572
1.53k
    return PyLong_FromLong(is_builtin(name));
4573
1.53k
}
4574
4575
/*[clinic input]
4576
_imp.is_frozen
4577
4578
    name: unicode
4579
    /
4580
4581
Returns True if the module name corresponds to a frozen module.
4582
[clinic start generated code]*/
4583
4584
static PyObject *
4585
_imp_is_frozen_impl(PyObject *module, PyObject *name)
4586
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
4587
22
{
4588
22
    struct frozen_info info;
4589
22
    frozen_status status = find_frozen(name, &info);
4590
22
    if (status != FROZEN_OKAY) {
4591
0
        Py_RETURN_FALSE;
4592
0
    }
4593
22
    Py_RETURN_TRUE;
4594
22
}
4595
4596
/*[clinic input]
4597
_imp._frozen_module_names
4598
4599
Returns the list of available frozen modules.
4600
[clinic start generated code]*/
4601
4602
static PyObject *
4603
_imp__frozen_module_names_impl(PyObject *module)
4604
/*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
4605
0
{
4606
0
    return list_frozen_module_names();
4607
0
}
4608
4609
/*[clinic input]
4610
_imp._override_frozen_modules_for_tests
4611
4612
    override: int
4613
    /
4614
4615
(internal-only) Override PyConfig.use_frozen_modules.
4616
4617
(-1: "off", 1: "on", 0: no override)
4618
See frozen_modules() in Lib/test/support/import_helper.py.
4619
[clinic start generated code]*/
4620
4621
static PyObject *
4622
_imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
4623
/*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
4624
0
{
4625
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4626
0
    OVERRIDE_FROZEN_MODULES(interp) = override;
4627
0
    Py_RETURN_NONE;
4628
0
}
4629
4630
/*[clinic input]
4631
_imp._override_multi_interp_extensions_check
4632
4633
    override: int
4634
    /
4635
4636
(internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
4637
4638
(-1: "never", 1: "always", 0: no override)
4639
[clinic start generated code]*/
4640
4641
static PyObject *
4642
_imp__override_multi_interp_extensions_check_impl(PyObject *module,
4643
                                                  int override)
4644
/*[clinic end generated code: output=3ff043af52bbf280 input=e086a2ea181f92ae]*/
4645
0
{
4646
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4647
0
    if (_Py_IsMainInterpreter(interp)) {
4648
0
        PyErr_SetString(PyExc_RuntimeError,
4649
0
                        "_imp._override_multi_interp_extensions_check() "
4650
0
                        "cannot be used in the main interpreter");
4651
0
        return NULL;
4652
0
    }
4653
#ifdef Py_GIL_DISABLED
4654
    PyErr_SetString(PyExc_RuntimeError,
4655
                    "_imp._override_multi_interp_extensions_check() "
4656
                    "cannot be used in the free-threaded build");
4657
    return NULL;
4658
#else
4659
0
    int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
4660
0
    OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
4661
0
    return PyLong_FromLong(oldvalue);
4662
0
#endif
4663
0
}
4664
4665
#ifdef HAVE_DYNAMIC_LOADING
4666
4667
/*[clinic input]
4668
_imp.create_dynamic
4669
4670
    spec: object
4671
    file: object = NULL
4672
    /
4673
4674
Create an extension module.
4675
[clinic start generated code]*/
4676
4677
static PyObject *
4678
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
4679
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
4680
24
{
4681
24
    PyObject *mod = NULL;
4682
24
    PyThreadState *tstate = _PyThreadState_GET();
4683
4684
24
    struct _Py_ext_module_loader_info info;
4685
24
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
4686
0
        return NULL;
4687
0
    }
4688
4689
24
    struct extensions_cache_value *cached = NULL;
4690
24
    mod = import_find_extension(tstate, &info, &cached);
4691
24
    if (mod != NULL) {
4692
0
        assert(!_PyErr_Occurred(tstate));
4693
0
        assert(cached != NULL);
4694
        /* The module might not have md_def set in certain reload cases. */
4695
0
        assert(_PyModule_GetDef(mod) == NULL
4696
0
                || cached->def == _PyModule_GetDef(mod));
4697
0
        assert_singlephase(cached);
4698
0
        goto finally;
4699
0
    }
4700
24
    else if (_PyErr_Occurred(tstate)) {
4701
0
        goto finally;
4702
0
    }
4703
    /* Otherwise it must be multi-phase init or the first time it's loaded. */
4704
4705
    /* If the module was added to the global cache
4706
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
4707
     * then we have to do a little dance here. */
4708
24
    if (cached != NULL) {
4709
0
        assert(cached->def->m_base.m_copy == NULL);
4710
        /* For now we clear the cache and move on. */
4711
0
        _extensions_cache_delete(info.path, info.name);
4712
0
    }
4713
4714
24
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
4715
24
                    Py_None, Py_None, Py_None) < 0)
4716
0
    {
4717
0
        goto finally;
4718
0
    }
4719
4720
    /* We would move this (and the fclose() below) into
4721
     * _PyImport_GetModInitFunc(), but it isn't clear if the intervening
4722
     * code relies on fp still being open. */
4723
24
    FILE *fp;
4724
24
    if (file != NULL) {
4725
0
        fp = Py_fopen(info.filename, "r");
4726
0
        if (fp == NULL) {
4727
0
            goto finally;
4728
0
        }
4729
0
    }
4730
24
    else {
4731
24
        fp = NULL;
4732
24
    }
4733
4734
24
    PyModInitFunction p0 = _PyImport_GetModInitFunc(&info, fp);
4735
24
    if (p0 == NULL) {
4736
0
        goto finally;
4737
0
    }
4738
4739
#ifdef Py_GIL_DISABLED
4740
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
4741
    // would ideally be inside import_run_extension(). They are kept in the
4742
    // callers for now because that would complicate the control flow inside
4743
    // import_run_extension(). It should be possible to restructure
4744
    // import_run_extension() to address this.
4745
    _PyEval_EnableGILTransient(tstate);
4746
#endif
4747
24
    mod = import_run_extension(
4748
24
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
4749
#ifdef Py_GIL_DISABLED
4750
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
4751
        Py_CLEAR(mod);
4752
        goto finally;
4753
    }
4754
#endif
4755
4756
    // XXX Shouldn't this happen in the error cases too (i.e. in "finally")?
4757
24
    if (fp) {
4758
0
        fclose(fp);
4759
0
    }
4760
4761
24
finally:
4762
24
    _Py_ext_module_loader_info_clear(&info);
4763
24
    return mod;
4764
24
}
4765
4766
/*[clinic input]
4767
_imp.exec_dynamic -> int
4768
4769
    mod: object
4770
    /
4771
4772
Initialize an extension module.
4773
[clinic start generated code]*/
4774
4775
static int
4776
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
4777
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
4778
24
{
4779
24
    return exec_builtin_or_dynamic(mod);
4780
24
}
4781
4782
4783
#endif /* HAVE_DYNAMIC_LOADING */
4784
4785
/*[clinic input]
4786
_imp.exec_builtin -> int
4787
4788
    mod: object
4789
    /
4790
4791
Initialize a built-in module.
4792
[clinic start generated code]*/
4793
4794
static int
4795
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
4796
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
4797
298
{
4798
298
    return exec_builtin_or_dynamic(mod);
4799
298
}
4800
4801
/*[clinic input]
4802
_imp.source_hash
4803
4804
    key: long
4805
    source: Py_buffer
4806
[clinic start generated code]*/
4807
4808
static PyObject *
4809
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
4810
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
4811
0
{
4812
0
    union {
4813
0
        uint64_t x;
4814
0
        char data[sizeof(uint64_t)];
4815
0
    } hash;
4816
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
4817
#if !PY_LITTLE_ENDIAN
4818
    // Force to little-endian. There really ought to be a succinct standard way
4819
    // to do this.
4820
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
4821
        char tmp = hash.data[i];
4822
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
4823
        hash.data[sizeof(hash.data) - i - 1] = tmp;
4824
    }
4825
#endif
4826
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
4827
0
}
4828
4829
4830
PyDoc_STRVAR(doc_imp,
4831
"(Extremely) low-level import machinery bits as used by importlib.");
4832
4833
static PyMethodDef imp_methods[] = {
4834
    _IMP_EXTENSION_SUFFIXES_METHODDEF
4835
    _IMP_LOCK_HELD_METHODDEF
4836
    _IMP_ACQUIRE_LOCK_METHODDEF
4837
    _IMP_RELEASE_LOCK_METHODDEF
4838
    _IMP_FIND_FROZEN_METHODDEF
4839
    _IMP_GET_FROZEN_OBJECT_METHODDEF
4840
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
4841
    _IMP_CREATE_BUILTIN_METHODDEF
4842
    _IMP_INIT_FROZEN_METHODDEF
4843
    _IMP_IS_BUILTIN_METHODDEF
4844
    _IMP_IS_FROZEN_METHODDEF
4845
    _IMP__FROZEN_MODULE_NAMES_METHODDEF
4846
    _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
4847
    _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
4848
    _IMP_CREATE_DYNAMIC_METHODDEF
4849
    _IMP_EXEC_DYNAMIC_METHODDEF
4850
    _IMP_EXEC_BUILTIN_METHODDEF
4851
    _IMP__FIX_CO_FILENAME_METHODDEF
4852
    _IMP_SOURCE_HASH_METHODDEF
4853
    {NULL, NULL}  /* sentinel */
4854
};
4855
4856
4857
static int
4858
imp_module_exec(PyObject *module)
4859
22
{
4860
22
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
4861
22
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
4862
22
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
4863
0
        return -1;
4864
0
    }
4865
4866
22
    if (PyModule_AddIntConstant(
4867
22
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
4868
0
    {
4869
0
        return -1;
4870
0
    }
4871
4872
22
    return 0;
4873
22
}
4874
4875
4876
static PyModuleDef_Slot imp_slots[] = {
4877
    {Py_mod_exec, imp_module_exec},
4878
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
4879
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
4880
    {0, NULL}
4881
};
4882
4883
static struct PyModuleDef imp_module = {
4884
    PyModuleDef_HEAD_INIT,
4885
    .m_name = "_imp",
4886
    .m_doc = doc_imp,
4887
    .m_size = 0,
4888
    .m_methods = imp_methods,
4889
    .m_slots = imp_slots,
4890
};
4891
4892
PyMODINIT_FUNC
4893
PyInit__imp(void)
4894
22
{
4895
22
    return PyModuleDef_Init(&imp_module);
4896
22
}