Coverage Report

Created: 2026-06-14 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/Python-3.8.3/Python/import.c
Line
Count
Source
1
/* Module definition and import implementation */
2
3
#include "Python.h"
4
5
#include "Python-ast.h"
6
#undef Yield   /* undefine macro conflicting with <winbase.h> */
7
#include "pycore_pyhash.h"
8
#include "pycore_pylifecycle.h"
9
#include "pycore_pymem.h"
10
#include "pycore_pystate.h"
11
#include "errcode.h"
12
#include "marshal.h"
13
#include "code.h"
14
#include "frameobject.h"
15
#include "osdefs.h"
16
#include "importdl.h"
17
#include "pydtrace.h"
18
19
#ifdef HAVE_FCNTL_H
20
#include <fcntl.h>
21
#endif
22
#ifdef __cplusplus
23
extern "C" {
24
#endif
25
26
#define CACHEDIR "__pycache__"
27
28
/* See _PyImport_FixupExtensionObject() below */
29
static PyObject *extensions = NULL;
30
31
/* This table is defined in config.c: */
32
extern struct _inittab _PyImport_Inittab[];
33
34
struct _inittab *PyImport_Inittab = _PyImport_Inittab;
35
static struct _inittab *inittab_copy = NULL;
36
37
/*[clinic input]
38
module _imp
39
[clinic start generated code]*/
40
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
41
42
#include "clinic/import.c.h"
43
44
/* Initialize things */
45
46
PyStatus
47
_PyImport_Init(PyInterpreterState *interp)
48
13
{
49
13
    interp->builtins_copy = PyDict_Copy(interp->builtins);
50
13
    if (interp->builtins_copy == NULL) {
51
0
        return _PyStatus_ERR("Can't backup builtins dict");
52
0
    }
53
13
    return _PyStatus_OK();
54
13
}
55
56
PyStatus
57
_PyImportHooks_Init(void)
58
13
{
59
13
    PyObject *v, *path_hooks = NULL;
60
13
    int err = 0;
61
62
    /* adding sys.path_hooks and sys.path_importer_cache */
63
13
    v = PyList_New(0);
64
13
    if (v == NULL)
65
0
        goto error;
66
13
    err = PySys_SetObject("meta_path", v);
67
13
    Py_DECREF(v);
68
13
    if (err)
69
0
        goto error;
70
13
    v = PyDict_New();
71
13
    if (v == NULL)
72
0
        goto error;
73
13
    err = PySys_SetObject("path_importer_cache", v);
74
13
    Py_DECREF(v);
75
13
    if (err)
76
0
        goto error;
77
13
    path_hooks = PyList_New(0);
78
13
    if (path_hooks == NULL)
79
0
        goto error;
80
13
    err = PySys_SetObject("path_hooks", path_hooks);
81
13
    if (err) {
82
0
        goto error;
83
0
    }
84
13
    Py_DECREF(path_hooks);
85
13
    return _PyStatus_OK();
86
87
0
  error:
88
0
    PyErr_Print();
89
0
    return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
90
13
                        "or path_importer_cache failed");
91
13
}
92
93
PyStatus
94
_PyImportZip_Init(PyInterpreterState *interp)
95
13
{
96
13
    PyObject *path_hooks, *zipimport;
97
13
    int err = 0;
98
99
13
    path_hooks = PySys_GetObject("path_hooks");
100
13
    if (path_hooks == NULL) {
101
0
        PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
102
0
        goto error;
103
0
    }
104
105
13
    int verbose = interp->config.verbose;
106
13
    if (verbose) {
107
0
        PySys_WriteStderr("# installing zipimport hook\n");
108
0
    }
109
110
13
    zipimport = PyImport_ImportModule("zipimport");
111
13
    if (zipimport == NULL) {
112
0
        PyErr_Clear(); /* No zip import module -- okay */
113
0
        if (verbose) {
114
0
            PySys_WriteStderr("# can't import zipimport\n");
115
0
        }
116
0
    }
117
13
    else {
118
13
        _Py_IDENTIFIER(zipimporter);
119
13
        PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
120
13
                                                    &PyId_zipimporter);
121
13
        Py_DECREF(zipimport);
122
13
        if (zipimporter == NULL) {
123
0
            PyErr_Clear(); /* No zipimporter object -- okay */
124
0
            if (verbose) {
125
0
                PySys_WriteStderr("# can't import zipimport.zipimporter\n");
126
0
            }
127
0
        }
128
13
        else {
129
            /* sys.path_hooks.insert(0, zipimporter) */
130
13
            err = PyList_Insert(path_hooks, 0, zipimporter);
131
13
            Py_DECREF(zipimporter);
132
13
            if (err < 0) {
133
0
                goto error;
134
0
            }
135
13
            if (verbose) {
136
0
                PySys_WriteStderr("# installed zipimport hook\n");
137
0
            }
138
13
        }
139
13
    }
140
141
13
    return _PyStatus_OK();
142
143
0
  error:
144
0
    PyErr_Print();
145
0
    return _PyStatus_ERR("initializing zipimport failed");
146
13
}
147
148
/* Locking primitives to prevent parallel imports of the same module
149
   in different threads to return with a partially loaded module.
150
   These calls are serialized by the global interpreter lock. */
151
152
#include "pythread.h"
153
154
static PyThread_type_lock import_lock = 0;
155
static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
156
static int import_lock_level = 0;
157
158
void
159
_PyImport_AcquireLock(void)
160
1.60k
{
161
1.60k
    unsigned long me = PyThread_get_thread_ident();
162
1.60k
    if (me == PYTHREAD_INVALID_THREAD_ID)
163
0
        return; /* Too bad */
164
1.60k
    if (import_lock == NULL) {
165
13
        import_lock = PyThread_allocate_lock();
166
13
        if (import_lock == NULL)
167
0
            return;  /* Nothing much we can do. */
168
13
    }
169
1.60k
    if (import_lock_thread == me) {
170
0
        import_lock_level++;
171
0
        return;
172
0
    }
173
1.60k
    if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
174
1.60k
        !PyThread_acquire_lock(import_lock, 0))
175
0
    {
176
0
        PyThreadState *tstate = PyEval_SaveThread();
177
0
        PyThread_acquire_lock(import_lock, 1);
178
0
        PyEval_RestoreThread(tstate);
179
0
    }
180
1.60k
    assert(import_lock_level == 0);
181
1.60k
    import_lock_thread = me;
182
1.60k
    import_lock_level = 1;
183
1.60k
}
184
185
int
186
_PyImport_ReleaseLock(void)
187
1.60k
{
188
1.60k
    unsigned long me = PyThread_get_thread_ident();
189
1.60k
    if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
190
0
        return 0; /* Too bad */
191
1.60k
    if (import_lock_thread != me)
192
0
        return -1;
193
1.60k
    import_lock_level--;
194
1.60k
    assert(import_lock_level >= 0);
195
1.60k
    if (import_lock_level == 0) {
196
1.60k
        import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
197
1.60k
        PyThread_release_lock(import_lock);
198
1.60k
    }
199
1.60k
    return 1;
200
1.60k
}
201
202
/* This function is called from PyOS_AfterFork_Child to ensure that newly
203
   created child processes do not share locks with the parent.
204
   We now acquire the import lock around fork() calls but on some platforms
205
   (Solaris 9 and earlier? see isue7242) that still left us with problems. */
206
207
void
208
_PyImport_ReInitLock(void)
209
0
{
210
0
    if (import_lock != NULL) {
211
0
        import_lock = PyThread_allocate_lock();
212
0
        if (import_lock == NULL) {
213
0
            Py_FatalError("PyImport_ReInitLock failed to create a new lock");
214
0
        }
215
0
    }
216
0
    if (import_lock_level > 1) {
217
        /* Forked as a side effect of import */
218
0
        unsigned long me = PyThread_get_thread_ident();
219
        /* The following could fail if the lock is already held, but forking as
220
           a side-effect of an import is a) rare, b) nuts, and c) difficult to
221
           do thanks to the lock only being held when doing individual module
222
           locks per import. */
223
0
        PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
224
0
        import_lock_thread = me;
225
0
        import_lock_level--;
226
0
    } else {
227
0
        import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
228
0
        import_lock_level = 0;
229
0
    }
230
0
}
231
232
/*[clinic input]
233
_imp.lock_held
234
235
Return True if the import lock is currently held, else False.
236
237
On platforms without threads, return False.
238
[clinic start generated code]*/
239
240
static PyObject *
241
_imp_lock_held_impl(PyObject *module)
242
/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
243
0
{
244
0
    return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
245
0
}
246
247
/*[clinic input]
248
_imp.acquire_lock
249
250
Acquires the interpreter's import lock for the current thread.
251
252
This lock should be used by import hooks to ensure thread-safety when importing
253
modules. On platforms without threads, this function does nothing.
254
[clinic start generated code]*/
255
256
static PyObject *
257
_imp_acquire_lock_impl(PyObject *module)
258
/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
259
1.60k
{
260
1.60k
    _PyImport_AcquireLock();
261
1.60k
    Py_RETURN_NONE;
262
1.60k
}
263
264
/*[clinic input]
265
_imp.release_lock
266
267
Release the interpreter's import lock.
268
269
On platforms without threads, this function does nothing.
270
[clinic start generated code]*/
271
272
static PyObject *
273
_imp_release_lock_impl(PyObject *module)
274
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
275
1.60k
{
276
1.60k
    if (_PyImport_ReleaseLock() < 0) {
277
0
        PyErr_SetString(PyExc_RuntimeError,
278
0
                        "not holding the import lock");
279
0
        return NULL;
280
0
    }
281
1.60k
    Py_RETURN_NONE;
282
1.60k
}
283
284
void
285
_PyImport_Fini(void)
286
0
{
287
0
    Py_CLEAR(extensions);
288
0
    if (import_lock != NULL) {
289
0
        PyThread_free_lock(import_lock);
290
0
        import_lock = NULL;
291
0
    }
292
0
}
293
294
void
295
_PyImport_Fini2(void)
296
0
{
297
    /* Use the same memory allocator than PyImport_ExtendInittab(). */
298
0
    PyMemAllocatorEx old_alloc;
299
0
    _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
300
301
    /* Free memory allocated by PyImport_ExtendInittab() */
302
0
    PyMem_RawFree(inittab_copy);
303
0
    inittab_copy = NULL;
304
305
0
    PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
306
0
}
307
308
/* Helper for sys */
309
310
PyObject *
311
PyImport_GetModuleDict(void)
312
2.44k
{
313
2.44k
    PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
314
2.44k
    if (interp->modules == NULL) {
315
0
        Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
316
0
    }
317
2.44k
    return interp->modules;
318
2.44k
}
319
320
/* In some corner cases it is important to be sure that the import
321
   machinery has been initialized (or not cleaned up yet).  For
322
   example, see issue #4236 and PyModule_Create2(). */
323
324
int
325
_PyImport_IsInitialized(PyInterpreterState *interp)
326
176
{
327
176
    if (interp->modules == NULL)
328
0
        return 0;
329
176
    return 1;
330
176
}
331
332
PyObject *
333
_PyImport_GetModuleId(struct _Py_Identifier *nameid)
334
0
{
335
0
    PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
336
0
    if (name == NULL) {
337
0
        return NULL;
338
0
    }
339
0
    return PyImport_GetModule(name);
340
0
}
341
342
int
343
_PyImport_SetModule(PyObject *name, PyObject *m)
344
0
{
345
0
    PyObject *modules = PyImport_GetModuleDict();
346
0
    return PyObject_SetItem(modules, name, m);
347
0
}
348
349
int
350
_PyImport_SetModuleString(const char *name, PyObject *m)
351
13
{
352
13
    PyObject *modules = PyImport_GetModuleDict();
353
13
    return PyMapping_SetItemString(modules, name, m);
354
13
}
355
356
PyObject *
357
PyImport_GetModule(PyObject *name)
358
2.07k
{
359
2.07k
    PyObject *m;
360
2.07k
    PyObject *modules = PyImport_GetModuleDict();
361
2.07k
    if (modules == NULL) {
362
0
        PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
363
0
        return NULL;
364
0
    }
365
2.07k
    Py_INCREF(modules);
366
2.07k
    if (PyDict_CheckExact(modules)) {
367
2.07k
        m = PyDict_GetItemWithError(modules, name);  /* borrowed */
368
2.07k
        Py_XINCREF(m);
369
2.07k
    }
370
0
    else {
371
0
        m = PyObject_GetItem(modules, name);
372
0
        if (m == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
373
0
            PyErr_Clear();
374
0
        }
375
0
    }
376
2.07k
    Py_DECREF(modules);
377
2.07k
    return m;
378
2.07k
}
379
380
381
/* List of names to clear in sys */
382
static const char * const sys_deletes[] = {
383
    "path", "argv", "ps1", "ps2",
384
    "last_type", "last_value", "last_traceback",
385
    "path_hooks", "path_importer_cache", "meta_path",
386
    "__interactivehook__",
387
    NULL
388
};
389
390
static const char * const sys_files[] = {
391
    "stdin", "__stdin__",
392
    "stdout", "__stdout__",
393
    "stderr", "__stderr__",
394
    NULL
395
};
396
397
/* Un-initialize things, as good as we can */
398
399
void
400
PyImport_Cleanup(void)
401
0
{
402
0
    Py_ssize_t pos;
403
0
    PyObject *key, *value, *dict;
404
0
    PyInterpreterState *interp = _PyInterpreterState_Get();
405
0
    PyObject *modules = PyImport_GetModuleDict();
406
0
    PyObject *weaklist = NULL;
407
0
    const char * const *p;
408
409
0
    if (modules == NULL)
410
0
        return; /* Already done */
411
412
    /* Delete some special variables first.  These are common
413
       places where user values hide and people complain when their
414
       destructors fail.  Since the modules containing them are
415
       deleted *last* of all, they would come too late in the normal
416
       destruction order.  Sigh. */
417
418
    /* XXX Perhaps these precautions are obsolete. Who knows? */
419
420
0
    int verbose = interp->config.verbose;
421
0
    if (verbose) {
422
0
        PySys_WriteStderr("# clear builtins._\n");
423
0
    }
424
0
    if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
425
0
        PyErr_WriteUnraisable(NULL);
426
0
    }
427
428
0
    for (p = sys_deletes; *p != NULL; p++) {
429
0
        if (verbose) {
430
0
            PySys_WriteStderr("# clear sys.%s\n", *p);
431
0
        }
432
0
        if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
433
0
            PyErr_WriteUnraisable(NULL);
434
0
        }
435
0
    }
436
0
    for (p = sys_files; *p != NULL; p+=2) {
437
0
        if (verbose) {
438
0
            PySys_WriteStderr("# restore sys.%s\n", *p);
439
0
        }
440
0
        value = _PyDict_GetItemStringWithError(interp->sysdict, *(p+1));
441
0
        if (value == NULL) {
442
0
            if (PyErr_Occurred()) {
443
0
                PyErr_WriteUnraisable(NULL);
444
0
            }
445
0
            value = Py_None;
446
0
        }
447
0
        if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
448
0
            PyErr_WriteUnraisable(NULL);
449
0
        }
450
0
    }
451
452
    /* We prepare a list which will receive (name, weakref) tuples of
453
       modules when they are removed from sys.modules.  The name is used
454
       for diagnosis messages (in verbose mode), while the weakref helps
455
       detect those modules which have been held alive. */
456
0
    weaklist = PyList_New(0);
457
0
    if (weaklist == NULL) {
458
0
        PyErr_WriteUnraisable(NULL);
459
0
    }
460
461
0
#define STORE_MODULE_WEAKREF(name, mod) \
462
0
    if (weaklist != NULL) { \
463
0
        PyObject *wr = PyWeakref_NewRef(mod, NULL); \
464
0
        if (wr) { \
465
0
            PyObject *tup = PyTuple_Pack(2, name, wr); \
466
0
            if (!tup || PyList_Append(weaklist, tup) < 0) { \
467
0
                PyErr_WriteUnraisable(NULL); \
468
0
            } \
469
0
            Py_XDECREF(tup); \
470
0
            Py_DECREF(wr); \
471
0
        } \
472
0
        else { \
473
0
            PyErr_WriteUnraisable(NULL); \
474
0
        } \
475
0
    }
476
0
#define CLEAR_MODULE(name, mod) \
477
0
    if (PyModule_Check(mod)) { \
478
0
        if (verbose && PyUnicode_Check(name)) { \
479
0
            PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
480
0
        } \
481
0
        STORE_MODULE_WEAKREF(name, mod); \
482
0
        if (PyObject_SetItem(modules, name, Py_None) < 0) { \
483
0
            PyErr_WriteUnraisable(NULL); \
484
0
        } \
485
0
    }
486
487
    /* Remove all modules from sys.modules, hoping that garbage collection
488
       can reclaim most of them. */
489
0
    if (PyDict_CheckExact(modules)) {
490
0
        pos = 0;
491
0
        while (PyDict_Next(modules, &pos, &key, &value)) {
492
0
            CLEAR_MODULE(key, value);
493
0
        }
494
0
    }
495
0
    else {
496
0
        PyObject *iterator = PyObject_GetIter(modules);
497
0
        if (iterator == NULL) {
498
0
            PyErr_WriteUnraisable(NULL);
499
0
        }
500
0
        else {
501
0
            while ((key = PyIter_Next(iterator))) {
502
0
                value = PyObject_GetItem(modules, key);
503
0
                if (value == NULL) {
504
0
                    PyErr_WriteUnraisable(NULL);
505
0
                    continue;
506
0
                }
507
0
                CLEAR_MODULE(key, value);
508
0
                Py_DECREF(value);
509
0
                Py_DECREF(key);
510
0
            }
511
0
            if (PyErr_Occurred()) {
512
0
                PyErr_WriteUnraisable(NULL);
513
0
            }
514
0
            Py_DECREF(iterator);
515
0
        }
516
0
    }
517
518
    /* Clear the modules dict. */
519
0
    if (PyDict_CheckExact(modules)) {
520
0
        PyDict_Clear(modules);
521
0
    }
522
0
    else {
523
0
        _Py_IDENTIFIER(clear);
524
0
        if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
525
0
            PyErr_WriteUnraisable(NULL);
526
0
        }
527
0
    }
528
    /* Restore the original builtins dict, to ensure that any
529
       user data gets cleared. */
530
0
    dict = PyDict_Copy(interp->builtins);
531
0
    if (dict == NULL) {
532
0
        PyErr_WriteUnraisable(NULL);
533
0
    }
534
0
    PyDict_Clear(interp->builtins);
535
0
    if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
536
0
        PyErr_Clear();
537
0
    }
538
0
    Py_XDECREF(dict);
539
    /* Clear module dict copies stored in the interpreter state */
540
0
    _PyState_ClearModules();
541
    /* Collect references */
542
0
    _PyGC_CollectNoFail();
543
    /* Dump GC stats before it's too late, since it uses the warnings
544
       machinery. */
545
0
    _PyGC_DumpShutdownStats(&_PyRuntime);
546
547
    /* Now, if there are any modules left alive, clear their globals to
548
       minimize potential leaks.  All C extension modules actually end
549
       up here, since they are kept alive in the interpreter state.
550
551
       The special treatment of "builtins" here is because even
552
       when it's not referenced as a module, its dictionary is
553
       referenced by almost every module's __builtins__.  Since
554
       deleting a module clears its dictionary (even if there are
555
       references left to it), we need to delete the "builtins"
556
       module last.  Likewise, we don't delete sys until the very
557
       end because it is implicitly referenced (e.g. by print). */
558
0
    if (weaklist != NULL) {
559
0
        Py_ssize_t i;
560
        /* Since dict is ordered in CPython 3.6+, modules are saved in
561
           importing order.  First clear modules imported later. */
562
0
        for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
563
0
            PyObject *tup = PyList_GET_ITEM(weaklist, i);
564
0
            PyObject *name = PyTuple_GET_ITEM(tup, 0);
565
0
            PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
566
0
            if (mod == Py_None)
567
0
                continue;
568
0
            assert(PyModule_Check(mod));
569
0
            dict = PyModule_GetDict(mod);
570
0
            if (dict == interp->builtins || dict == interp->sysdict)
571
0
                continue;
572
0
            Py_INCREF(mod);
573
0
            if (verbose && PyUnicode_Check(name)) {
574
0
                PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
575
0
            }
576
0
            _PyModule_Clear(mod);
577
0
            Py_DECREF(mod);
578
0
        }
579
0
        Py_DECREF(weaklist);
580
0
    }
581
582
    /* Next, delete sys and builtins (in that order) */
583
0
    if (verbose) {
584
0
        PySys_FormatStderr("# cleanup[3] wiping sys\n");
585
0
    }
586
0
    _PyModule_ClearDict(interp->sysdict);
587
0
    if (verbose) {
588
0
        PySys_FormatStderr("# cleanup[3] wiping builtins\n");
589
0
    }
590
0
    _PyModule_ClearDict(interp->builtins);
591
592
    /* Clear and delete the modules directory.  Actual modules will
593
       still be there only if imported during the execution of some
594
       destructor. */
595
0
    interp->modules = NULL;
596
0
    Py_DECREF(modules);
597
598
    /* Once more */
599
0
    _PyGC_CollectNoFail();
600
601
0
#undef CLEAR_MODULE
602
0
#undef STORE_MODULE_WEAKREF
603
0
}
604
605
606
/* Helper for pythonrun.c -- return magic number and tag. */
607
608
long
609
PyImport_GetMagicNumber(void)
610
0
{
611
0
    long res;
612
0
    PyInterpreterState *interp = _PyInterpreterState_Get();
613
0
    PyObject *external, *pyc_magic;
614
615
0
    external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
616
0
    if (external == NULL)
617
0
        return -1;
618
0
    pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
619
0
    Py_DECREF(external);
620
0
    if (pyc_magic == NULL)
621
0
        return -1;
622
0
    res = PyLong_AsLong(pyc_magic);
623
0
    Py_DECREF(pyc_magic);
624
0
    return res;
625
0
}
626
627
628
extern const char * _PySys_ImplCacheTag;
629
630
const char *
631
PyImport_GetMagicTag(void)
632
0
{
633
0
    return _PySys_ImplCacheTag;
634
0
}
635
636
637
/* Magic for extension modules (built-in as well as dynamically
638
   loaded).  To prevent initializing an extension module more than
639
   once, we keep a static dictionary 'extensions' keyed by the tuple
640
   (module name, module name)  (for built-in modules) or by
641
   (filename, module name) (for dynamically loaded modules), containing these
642
   modules.  A copy of the module's dictionary is stored by calling
643
   _PyImport_FixupExtensionObject() immediately after the module initialization
644
   function succeeds.  A copy can be retrieved from there by calling
645
   _PyImport_FindExtensionObject().
646
647
   Modules which do support multiple initialization set their m_size
648
   field to a non-negative number (indicating the size of the
649
   module-specific state). They are still recorded in the extensions
650
   dictionary, to avoid loading shared libraries twice.
651
*/
652
653
int
654
_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
655
                                 PyObject *filename, PyObject *modules)
656
163
{
657
163
    PyObject *dict, *key;
658
163
    struct PyModuleDef *def;
659
163
    int res;
660
163
    if (extensions == NULL) {
661
13
        extensions = PyDict_New();
662
13
        if (extensions == NULL)
663
0
            return -1;
664
13
    }
665
163
    if (mod == NULL || !PyModule_Check(mod)) {
666
0
        PyErr_BadInternalCall();
667
0
        return -1;
668
0
    }
669
163
    def = PyModule_GetDef(mod);
670
163
    if (!def) {
671
0
        PyErr_BadInternalCall();
672
0
        return -1;
673
0
    }
674
163
    if (PyObject_SetItem(modules, name, mod) < 0)
675
0
        return -1;
676
163
    if (_PyState_AddModule(mod, def) < 0) {
677
0
        PyMapping_DelItem(modules, name);
678
0
        return -1;
679
0
    }
680
163
    if (def->m_size == -1) {
681
123
        if (def->m_base.m_copy) {
682
            /* Somebody already imported the module,
683
               likely under a different name.
684
               XXX this should really not happen. */
685
0
            Py_CLEAR(def->m_base.m_copy);
686
0
        }
687
123
        dict = PyModule_GetDict(mod);
688
123
        if (dict == NULL)
689
0
            return -1;
690
123
        def->m_base.m_copy = PyDict_Copy(dict);
691
123
        if (def->m_base.m_copy == NULL)
692
0
            return -1;
693
123
    }
694
163
    key = PyTuple_Pack(2, filename, name);
695
163
    if (key == NULL)
696
0
        return -1;
697
163
    res = PyDict_SetItem(extensions, key, (PyObject *)def);
698
163
    Py_DECREF(key);
699
163
    if (res < 0)
700
0
        return -1;
701
163
    return 0;
702
163
}
703
704
int
705
_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
706
26
{
707
26
    int res;
708
26
    PyObject *nameobj;
709
26
    nameobj = PyUnicode_InternFromString(name);
710
26
    if (nameobj == NULL)
711
0
        return -1;
712
26
    res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
713
26
    Py_DECREF(nameobj);
714
26
    return res;
715
26
}
716
717
PyObject *
718
_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
719
164
{
720
164
    PyObject *modules = PyImport_GetModuleDict();
721
164
    return _PyImport_FindExtensionObjectEx(name, filename, modules);
722
164
}
723
724
PyObject *
725
_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
726
                                PyObject *modules)
727
164
{
728
164
    PyObject *mod, *mdict, *key;
729
164
    PyModuleDef* def;
730
164
    if (extensions == NULL)
731
0
        return NULL;
732
164
    key = PyTuple_Pack(2, filename, name);
733
164
    if (key == NULL)
734
0
        return NULL;
735
164
    def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
736
164
    Py_DECREF(key);
737
164
    if (def == NULL)
738
138
        return NULL;
739
26
    if (def->m_size == -1) {
740
        /* Module does not support repeated initialization */
741
26
        if (def->m_base.m_copy == NULL)
742
0
            return NULL;
743
26
        mod = _PyImport_AddModuleObject(name, modules);
744
26
        if (mod == NULL)
745
0
            return NULL;
746
26
        mdict = PyModule_GetDict(mod);
747
26
        if (mdict == NULL)
748
0
            return NULL;
749
26
        if (PyDict_Update(mdict, def->m_base.m_copy))
750
0
            return NULL;
751
26
    }
752
0
    else {
753
0
        if (def->m_base.m_init == NULL)
754
0
            return NULL;
755
0
        mod = def->m_base.m_init();
756
0
        if (mod == NULL)
757
0
            return NULL;
758
0
        if (PyObject_SetItem(modules, name, mod) == -1) {
759
0
            Py_DECREF(mod);
760
0
            return NULL;
761
0
        }
762
0
        Py_DECREF(mod);
763
0
    }
764
26
    if (_PyState_AddModule(mod, def) < 0) {
765
0
        PyMapping_DelItem(modules, name);
766
0
        return NULL;
767
0
    }
768
26
    int verbose = _PyInterpreterState_Get()->config.verbose;
769
26
    if (verbose) {
770
0
        PySys_FormatStderr("import %U # previously loaded (%R)\n",
771
0
                           name, filename);
772
0
    }
773
26
    return mod;
774
775
26
}
776
777
PyObject *
778
_PyImport_FindBuiltin(const char *name, PyObject *modules)
779
0
{
780
0
    PyObject *res, *nameobj;
781
0
    nameobj = PyUnicode_InternFromString(name);
782
0
    if (nameobj == NULL)
783
0
        return NULL;
784
0
    res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
785
0
    Py_DECREF(nameobj);
786
0
    return res;
787
0
}
788
789
/* Get the module object corresponding to a module name.
790
   First check the modules dictionary if there's one there,
791
   if not, create a new one and insert it in the modules dictionary.
792
   Because the former action is most common, THIS DOES NOT RETURN A
793
   'NEW' REFERENCE! */
794
795
PyObject *
796
PyImport_AddModuleObject(PyObject *name)
797
52
{
798
52
    PyObject *modules = PyImport_GetModuleDict();
799
52
    return _PyImport_AddModuleObject(name, modules);
800
52
}
801
802
PyObject *
803
_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
804
78
{
805
78
    PyObject *m;
806
78
    if (PyDict_CheckExact(modules)) {
807
78
        m = PyDict_GetItemWithError(modules, name);
808
78
    }
809
0
    else {
810
0
        m = PyObject_GetItem(modules, name);
811
        // For backward-comaptibility we copy the behavior
812
        // of PyDict_GetItemWithError().
813
0
        if (PyErr_ExceptionMatches(PyExc_KeyError)) {
814
0
            PyErr_Clear();
815
0
        }
816
0
    }
817
78
    if (PyErr_Occurred()) {
818
0
        return NULL;
819
0
    }
820
78
    if (m != NULL && PyModule_Check(m)) {
821
52
        return m;
822
52
    }
823
26
    m = PyModule_NewObject(name);
824
26
    if (m == NULL)
825
0
        return NULL;
826
26
    if (PyObject_SetItem(modules, name, m) != 0) {
827
0
        Py_DECREF(m);
828
0
        return NULL;
829
0
    }
830
26
    Py_DECREF(m); /* Yes, it still exists, in modules! */
831
832
26
    return m;
833
26
}
834
835
PyObject *
836
PyImport_AddModule(const char *name)
837
39
{
838
39
    PyObject *nameobj, *module;
839
39
    nameobj = PyUnicode_FromString(name);
840
39
    if (nameobj == NULL)
841
0
        return NULL;
842
39
    module = PyImport_AddModuleObject(nameobj);
843
39
    Py_DECREF(nameobj);
844
39
    return module;
845
39
}
846
847
848
/* Remove name from sys.modules, if it's there. */
849
static void
850
remove_module(PyObject *name)
851
0
{
852
0
    PyObject *type, *value, *traceback;
853
0
    PyErr_Fetch(&type, &value, &traceback);
854
0
    PyObject *modules = PyImport_GetModuleDict();
855
0
    if (!PyMapping_HasKey(modules, name)) {
856
0
        goto out;
857
0
    }
858
0
    if (PyMapping_DelItem(modules, name) < 0) {
859
0
        Py_FatalError("import:  deleting existing key in "
860
0
                      "sys.modules failed");
861
0
    }
862
0
out:
863
0
    PyErr_Restore(type, value, traceback);
864
0
}
865
866
867
/* Execute a code object in a module and return the module object
868
 * WITH INCREMENTED REFERENCE COUNT.  If an error occurs, name is
869
 * removed from sys.modules, to avoid leaving damaged module objects
870
 * in sys.modules.  The caller may wish to restore the original
871
 * module object (if any) in this case; PyImport_ReloadModule is an
872
 * example.
873
 *
874
 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
875
 * interface.  The other two exist primarily for backward compatibility.
876
 */
877
PyObject *
878
PyImport_ExecCodeModule(const char *name, PyObject *co)
879
0
{
880
0
    return PyImport_ExecCodeModuleWithPathnames(
881
0
        name, co, (char *)NULL, (char *)NULL);
882
0
}
883
884
PyObject *
885
PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
886
0
{
887
0
    return PyImport_ExecCodeModuleWithPathnames(
888
0
        name, co, pathname, (char *)NULL);
889
0
}
890
891
PyObject *
892
PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
893
                                     const char *pathname,
894
                                     const char *cpathname)
895
0
{
896
0
    PyObject *m = NULL;
897
0
    PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
898
899
0
    nameobj = PyUnicode_FromString(name);
900
0
    if (nameobj == NULL)
901
0
        return NULL;
902
903
0
    if (cpathname != NULL) {
904
0
        cpathobj = PyUnicode_DecodeFSDefault(cpathname);
905
0
        if (cpathobj == NULL)
906
0
            goto error;
907
0
    }
908
0
    else
909
0
        cpathobj = NULL;
910
911
0
    if (pathname != NULL) {
912
0
        pathobj = PyUnicode_DecodeFSDefault(pathname);
913
0
        if (pathobj == NULL)
914
0
            goto error;
915
0
    }
916
0
    else if (cpathobj != NULL) {
917
0
        PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
918
0
        _Py_IDENTIFIER(_get_sourcefile);
919
920
0
        if (interp == NULL) {
921
0
            Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
922
0
                          "no interpreter!");
923
0
        }
924
925
0
        external= PyObject_GetAttrString(interp->importlib,
926
0
                                         "_bootstrap_external");
927
0
        if (external != NULL) {
928
0
            pathobj = _PyObject_CallMethodIdObjArgs(external,
929
0
                                                    &PyId__get_sourcefile, cpathobj,
930
0
                                                    NULL);
931
0
            Py_DECREF(external);
932
0
        }
933
0
        if (pathobj == NULL)
934
0
            PyErr_Clear();
935
0
    }
936
0
    else
937
0
        pathobj = NULL;
938
939
0
    m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
940
0
error:
941
0
    Py_DECREF(nameobj);
942
0
    Py_XDECREF(pathobj);
943
0
    Py_XDECREF(cpathobj);
944
0
    return m;
945
0
}
946
947
static PyObject *
948
module_dict_for_exec(PyObject *name)
949
13
{
950
13
    _Py_IDENTIFIER(__builtins__);
951
13
    PyObject *m, *d = NULL;
952
953
13
    m = PyImport_AddModuleObject(name);
954
13
    if (m == NULL)
955
0
        return NULL;
956
    /* If the module is being reloaded, we get the old module back
957
       and re-use its dict to exec the new code. */
958
13
    d = PyModule_GetDict(m);
959
13
    if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
960
13
        if (PyErr_Occurred() ||
961
13
            _PyDict_SetItemId(d, &PyId___builtins__,
962
13
                              PyEval_GetBuiltins()) != 0)
963
0
        {
964
0
            remove_module(name);
965
0
            return NULL;
966
0
        }
967
13
    }
968
969
13
    return d;  /* Return a borrowed reference. */
970
13
}
971
972
static PyObject *
973
exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
974
13
{
975
13
    PyObject *v, *m;
976
977
13
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
978
13
    if (v == NULL) {
979
0
        remove_module(name);
980
0
        return NULL;
981
0
    }
982
13
    Py_DECREF(v);
983
984
13
    m = PyImport_GetModule(name);
985
13
    if (m == NULL && !PyErr_Occurred()) {
986
0
        PyErr_Format(PyExc_ImportError,
987
0
                     "Loaded module %R not found in sys.modules",
988
0
                     name);
989
0
    }
990
991
13
    return m;
992
13
}
993
994
PyObject*
995
PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
996
                              PyObject *cpathname)
997
0
{
998
0
    PyObject *d, *external, *res;
999
0
    PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1000
0
    _Py_IDENTIFIER(_fix_up_module);
1001
1002
0
    d = module_dict_for_exec(name);
1003
0
    if (d == NULL) {
1004
0
        return NULL;
1005
0
    }
1006
1007
0
    if (pathname == NULL) {
1008
0
        pathname = ((PyCodeObject *)co)->co_filename;
1009
0
    }
1010
0
    external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
1011
0
    if (external == NULL)
1012
0
        return NULL;
1013
0
    res = _PyObject_CallMethodIdObjArgs(external,
1014
0
                                        &PyId__fix_up_module,
1015
0
                                        d, name, pathname, cpathname, NULL);
1016
0
    Py_DECREF(external);
1017
0
    if (res != NULL) {
1018
0
        Py_DECREF(res);
1019
0
        res = exec_code_in_module(name, d, co);
1020
0
    }
1021
0
    return res;
1022
0
}
1023
1024
1025
static void
1026
update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1027
0
{
1028
0
    PyObject *constants, *tmp;
1029
0
    Py_ssize_t i, n;
1030
1031
0
    if (PyUnicode_Compare(co->co_filename, oldname))
1032
0
        return;
1033
1034
0
    Py_INCREF(newname);
1035
0
    Py_XSETREF(co->co_filename, newname);
1036
1037
0
    constants = co->co_consts;
1038
0
    n = PyTuple_GET_SIZE(constants);
1039
0
    for (i = 0; i < n; i++) {
1040
0
        tmp = PyTuple_GET_ITEM(constants, i);
1041
0
        if (PyCode_Check(tmp))
1042
0
            update_code_filenames((PyCodeObject *)tmp,
1043
0
                                  oldname, newname);
1044
0
    }
1045
0
}
1046
1047
static void
1048
update_compiled_module(PyCodeObject *co, PyObject *newname)
1049
220
{
1050
220
    PyObject *oldname;
1051
1052
220
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
1053
220
        return;
1054
1055
0
    oldname = co->co_filename;
1056
0
    Py_INCREF(oldname);
1057
0
    update_code_filenames(co, oldname, newname);
1058
0
    Py_DECREF(oldname);
1059
0
}
1060
1061
/*[clinic input]
1062
_imp._fix_co_filename
1063
1064
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1065
        Code object to change.
1066
1067
    path: unicode
1068
        File path to use.
1069
    /
1070
1071
Changes code.co_filename to specify the passed-in file path.
1072
[clinic start generated code]*/
1073
1074
static PyObject *
1075
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
1076
                           PyObject *path)
1077
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
1078
1079
220
{
1080
220
    update_compiled_module(code, path);
1081
1082
220
    Py_RETURN_NONE;
1083
220
}
1084
1085
1086
/* Forward */
1087
static const struct _frozen * find_frozen(PyObject *);
1088
1089
1090
/* Helper to test for built-in module */
1091
1092
static int
1093
is_builtin(PyObject *name)
1094
391
{
1095
391
    int i;
1096
9.20k
    for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1097
8.97k
        if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
1098
164
            if (PyImport_Inittab[i].initfunc == NULL)
1099
0
                return -1;
1100
164
            else
1101
164
                return 1;
1102
164
        }
1103
8.97k
    }
1104
227
    return 0;
1105
391
}
1106
1107
1108
/* Return a finder object for a sys.path/pkg.__path__ item 'p',
1109
   possibly by fetching it from the path_importer_cache dict. If it
1110
   wasn't yet cached, traverse path_hooks until a hook is found
1111
   that can handle the path item. Return None if no hook could;
1112
   this tells our caller that the path based finder could not find
1113
   a finder for this path item. Cache the result in
1114
   path_importer_cache.
1115
   Returns a borrowed reference. */
1116
1117
static PyObject *
1118
get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1119
                  PyObject *p)
1120
0
{
1121
0
    PyObject *importer;
1122
0
    Py_ssize_t j, nhooks;
1123
1124
    /* These conditions are the caller's responsibility: */
1125
0
    assert(PyList_Check(path_hooks));
1126
0
    assert(PyDict_Check(path_importer_cache));
1127
1128
0
    nhooks = PyList_Size(path_hooks);
1129
0
    if (nhooks < 0)
1130
0
        return NULL; /* Shouldn't happen */
1131
1132
0
    importer = PyDict_GetItemWithError(path_importer_cache, p);
1133
0
    if (importer != NULL || PyErr_Occurred())
1134
0
        return importer;
1135
1136
    /* set path_importer_cache[p] to None to avoid recursion */
1137
0
    if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1138
0
        return NULL;
1139
1140
0
    for (j = 0; j < nhooks; j++) {
1141
0
        PyObject *hook = PyList_GetItem(path_hooks, j);
1142
0
        if (hook == NULL)
1143
0
            return NULL;
1144
0
        importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1145
0
        if (importer != NULL)
1146
0
            break;
1147
1148
0
        if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1149
0
            return NULL;
1150
0
        }
1151
0
        PyErr_Clear();
1152
0
    }
1153
0
    if (importer == NULL) {
1154
0
        return Py_None;
1155
0
    }
1156
0
    if (importer != NULL) {
1157
0
        int err = PyDict_SetItem(path_importer_cache, p, importer);
1158
0
        Py_DECREF(importer);
1159
0
        if (err != 0)
1160
0
            return NULL;
1161
0
    }
1162
0
    return importer;
1163
0
}
1164
1165
PyObject *
1166
0
PyImport_GetImporter(PyObject *path) {
1167
0
    PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1168
1169
0
    path_importer_cache = PySys_GetObject("path_importer_cache");
1170
0
    path_hooks = PySys_GetObject("path_hooks");
1171
0
    if (path_importer_cache != NULL && path_hooks != NULL) {
1172
0
        importer = get_path_importer(path_importer_cache,
1173
0
                                     path_hooks, path);
1174
0
    }
1175
0
    Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1176
0
    return importer;
1177
0
}
1178
1179
/*[clinic input]
1180
_imp.create_builtin
1181
1182
    spec: object
1183
    /
1184
1185
Create an extension module.
1186
[clinic start generated code]*/
1187
1188
static PyObject *
1189
_imp_create_builtin(PyObject *module, PyObject *spec)
1190
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
1191
164
{
1192
164
    struct _inittab *p;
1193
164
    PyObject *name;
1194
164
    const char *namestr;
1195
164
    PyObject *mod;
1196
1197
164
    name = PyObject_GetAttrString(spec, "name");
1198
164
    if (name == NULL) {
1199
0
        return NULL;
1200
0
    }
1201
1202
164
    mod = _PyImport_FindExtensionObject(name, name);
1203
164
    if (mod || PyErr_Occurred()) {
1204
26
        Py_DECREF(name);
1205
26
        Py_XINCREF(mod);
1206
26
        return mod;
1207
26
    }
1208
1209
138
    namestr = PyUnicode_AsUTF8(name);
1210
138
    if (namestr == NULL) {
1211
0
        Py_DECREF(name);
1212
0
        return NULL;
1213
0
    }
1214
1215
138
    PyObject *modules = NULL;
1216
1.87k
    for (p = PyImport_Inittab; p->name != NULL; p++) {
1217
1.87k
        PyModuleDef *def;
1218
1.87k
        if (_PyUnicode_EqualToASCIIString(name, p->name)) {
1219
138
            if (p->initfunc == NULL) {
1220
                /* Cannot re-init internal module ("sys" or "builtins") */
1221
0
                mod = PyImport_AddModule(namestr);
1222
0
                Py_DECREF(name);
1223
0
                return mod;
1224
0
            }
1225
138
            mod = (*p->initfunc)();
1226
138
            if (mod == NULL) {
1227
0
                Py_DECREF(name);
1228
0
                return NULL;
1229
0
            }
1230
138
            if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1231
1
                Py_DECREF(name);
1232
1
                return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1233
137
            } else {
1234
                /* Remember pointer to module init function. */
1235
137
                def = PyModule_GetDef(mod);
1236
137
                if (def == NULL) {
1237
0
                    Py_DECREF(name);
1238
0
                    return NULL;
1239
0
                }
1240
137
                def->m_base.m_init = p->initfunc;
1241
137
                if (modules == NULL) {
1242
137
                    modules = PyImport_GetModuleDict();
1243
137
                }
1244
137
                if (_PyImport_FixupExtensionObject(mod, name, name,
1245
137
                                                   modules) < 0) {
1246
0
                    Py_DECREF(name);
1247
0
                    return NULL;
1248
0
                }
1249
137
                Py_DECREF(name);
1250
137
                return mod;
1251
137
            }
1252
138
        }
1253
1.87k
    }
1254
0
    Py_DECREF(name);
1255
0
    Py_RETURN_NONE;
1256
138
}
1257
1258
1259
/* Frozen modules */
1260
1261
static const struct _frozen *
1262
find_frozen(PyObject *name)
1263
410
{
1264
410
    const struct _frozen *p;
1265
1266
410
    if (name == NULL)
1267
0
        return NULL;
1268
1269
2.12k
    for (p = PyImport_FrozenModules; ; p++) {
1270
2.12k
        if (p->name == NULL)
1271
254
            return NULL;
1272
1.87k
        if (_PyUnicode_EqualToASCIIString(name, p->name))
1273
156
            break;
1274
1.87k
    }
1275
156
    return p;
1276
410
}
1277
1278
static PyObject *
1279
get_frozen_object(PyObject *name)
1280
26
{
1281
26
    const struct _frozen *p = find_frozen(name);
1282
26
    int size;
1283
1284
26
    if (p == NULL) {
1285
0
        PyErr_Format(PyExc_ImportError,
1286
0
                     "No such frozen object named %R",
1287
0
                     name);
1288
0
        return NULL;
1289
0
    }
1290
26
    if (p->code == NULL) {
1291
0
        PyErr_Format(PyExc_ImportError,
1292
0
                     "Excluded frozen object named %R",
1293
0
                     name);
1294
0
        return NULL;
1295
0
    }
1296
26
    size = p->size;
1297
26
    if (size < 0)
1298
0
        size = -size;
1299
26
    return PyMarshal_ReadObjectFromString((const char *)p->code, size);
1300
26
}
1301
1302
static PyObject *
1303
is_frozen_package(PyObject *name)
1304
26
{
1305
26
    const struct _frozen *p = find_frozen(name);
1306
26
    int size;
1307
1308
26
    if (p == NULL) {
1309
0
        PyErr_Format(PyExc_ImportError,
1310
0
                     "No such frozen object named %R",
1311
0
                     name);
1312
0
        return NULL;
1313
0
    }
1314
1315
26
    size = p->size;
1316
1317
26
    if (size < 0)
1318
0
        Py_RETURN_TRUE;
1319
26
    else
1320
26
        Py_RETURN_FALSE;
1321
26
}
1322
1323
1324
/* Initialize a frozen module.
1325
   Return 1 for success, 0 if the module is not found, and -1 with
1326
   an exception set if the initialization failed.
1327
   This function is also used from frozenmain.c */
1328
1329
int
1330
PyImport_ImportFrozenModuleObject(PyObject *name)
1331
13
{
1332
13
    const struct _frozen *p;
1333
13
    PyObject *co, *m, *d;
1334
13
    int ispackage;
1335
13
    int size;
1336
1337
13
    p = find_frozen(name);
1338
1339
13
    if (p == NULL)
1340
0
        return 0;
1341
13
    if (p->code == NULL) {
1342
0
        PyErr_Format(PyExc_ImportError,
1343
0
                     "Excluded frozen object named %R",
1344
0
                     name);
1345
0
        return -1;
1346
0
    }
1347
13
    size = p->size;
1348
13
    ispackage = (size < 0);
1349
13
    if (ispackage)
1350
0
        size = -size;
1351
13
    co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
1352
13
    if (co == NULL)
1353
0
        return -1;
1354
13
    if (!PyCode_Check(co)) {
1355
0
        PyErr_Format(PyExc_TypeError,
1356
0
                     "frozen object %R is not a code object",
1357
0
                     name);
1358
0
        goto err_return;
1359
0
    }
1360
13
    if (ispackage) {
1361
        /* Set __path__ to the empty list */
1362
0
        PyObject *l;
1363
0
        int err;
1364
0
        m = PyImport_AddModuleObject(name);
1365
0
        if (m == NULL)
1366
0
            goto err_return;
1367
0
        d = PyModule_GetDict(m);
1368
0
        l = PyList_New(0);
1369
0
        if (l == NULL) {
1370
0
            goto err_return;
1371
0
        }
1372
0
        err = PyDict_SetItemString(d, "__path__", l);
1373
0
        Py_DECREF(l);
1374
0
        if (err != 0)
1375
0
            goto err_return;
1376
0
    }
1377
13
    d = module_dict_for_exec(name);
1378
13
    if (d == NULL) {
1379
0
        goto err_return;
1380
0
    }
1381
13
    m = exec_code_in_module(name, d, co);
1382
13
    if (m == NULL)
1383
0
        goto err_return;
1384
13
    Py_DECREF(co);
1385
13
    Py_DECREF(m);
1386
13
    return 1;
1387
0
err_return:
1388
0
    Py_DECREF(co);
1389
0
    return -1;
1390
13
}
1391
1392
int
1393
PyImport_ImportFrozenModule(const char *name)
1394
13
{
1395
13
    PyObject *nameobj;
1396
13
    int ret;
1397
13
    nameobj = PyUnicode_InternFromString(name);
1398
13
    if (nameobj == NULL)
1399
0
        return -1;
1400
13
    ret = PyImport_ImportFrozenModuleObject(nameobj);
1401
13
    Py_DECREF(nameobj);
1402
13
    return ret;
1403
13
}
1404
1405
1406
/* Import a module, either built-in, frozen, or external, and return
1407
   its module object WITH INCREMENTED REFERENCE COUNT */
1408
1409
PyObject *
1410
PyImport_ImportModule(const char *name)
1411
510
{
1412
510
    PyObject *pname;
1413
510
    PyObject *result;
1414
1415
510
    pname = PyUnicode_FromString(name);
1416
510
    if (pname == NULL)
1417
0
        return NULL;
1418
510
    result = PyImport_Import(pname);
1419
510
    Py_DECREF(pname);
1420
510
    return result;
1421
510
}
1422
1423
/* Import a module without blocking
1424
 *
1425
 * At first it tries to fetch the module from sys.modules. If the module was
1426
 * never loaded before it loads it with PyImport_ImportModule() unless another
1427
 * thread holds the import lock. In the latter case the function raises an
1428
 * ImportError instead of blocking.
1429
 *
1430
 * Returns the module object with incremented ref count.
1431
 */
1432
PyObject *
1433
PyImport_ImportModuleNoBlock(const char *name)
1434
13
{
1435
13
    return PyImport_ImportModule(name);
1436
13
}
1437
1438
1439
/* Remove importlib frames from the traceback,
1440
 * except in Verbose mode. */
1441
static void
1442
remove_importlib_frames(PyInterpreterState *interp)
1443
34
{
1444
34
    const char *importlib_filename = "<frozen importlib._bootstrap>";
1445
34
    const char *external_filename = "<frozen importlib._bootstrap_external>";
1446
34
    const char *remove_frames = "_call_with_frames_removed";
1447
34
    int always_trim = 0;
1448
34
    int in_importlib = 0;
1449
34
    PyObject *exception, *value, *base_tb, *tb;
1450
34
    PyObject **prev_link, **outer_link = NULL;
1451
1452
    /* Synopsis: if it's an ImportError, we trim all importlib chunks
1453
       from the traceback. We always trim chunks
1454
       which end with a call to "_call_with_frames_removed". */
1455
1456
34
    PyErr_Fetch(&exception, &value, &base_tb);
1457
34
    if (!exception || interp->config.verbose) {
1458
0
        goto done;
1459
0
    }
1460
1461
34
    if (PyType_IsSubtype((PyTypeObject *) exception,
1462
34
                         (PyTypeObject *) PyExc_ImportError))
1463
34
        always_trim = 1;
1464
1465
34
    prev_link = &base_tb;
1466
34
    tb = base_tb;
1467
102
    while (tb != NULL) {
1468
68
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
1469
68
        PyObject *next = (PyObject *) traceback->tb_next;
1470
68
        PyFrameObject *frame = traceback->tb_frame;
1471
68
        PyCodeObject *code = frame->f_code;
1472
68
        int now_in_importlib;
1473
1474
68
        assert(PyTraceBack_Check(tb));
1475
68
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1476
0
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
1477
68
        if (now_in_importlib && !in_importlib) {
1478
            /* This is the link to this chunk of importlib tracebacks */
1479
34
            outer_link = prev_link;
1480
34
        }
1481
68
        in_importlib = now_in_importlib;
1482
1483
68
        if (in_importlib &&
1484
68
            (always_trim ||
1485
68
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
1486
68
            Py_XINCREF(next);
1487
68
            Py_XSETREF(*outer_link, next);
1488
68
            prev_link = outer_link;
1489
68
        }
1490
0
        else {
1491
0
            prev_link = (PyObject **) &traceback->tb_next;
1492
0
        }
1493
68
        tb = next;
1494
68
    }
1495
34
done:
1496
34
    PyErr_Restore(exception, value, base_tb);
1497
34
}
1498
1499
1500
static PyObject *
1501
resolve_name(PyObject *name, PyObject *globals, int level)
1502
13
{
1503
13
    _Py_IDENTIFIER(__spec__);
1504
13
    _Py_IDENTIFIER(__package__);
1505
13
    _Py_IDENTIFIER(__path__);
1506
13
    _Py_IDENTIFIER(__name__);
1507
13
    _Py_IDENTIFIER(parent);
1508
13
    PyObject *abs_name;
1509
13
    PyObject *package = NULL;
1510
13
    PyObject *spec;
1511
13
    Py_ssize_t last_dot;
1512
13
    PyObject *base;
1513
13
    int level_up;
1514
1515
13
    if (globals == NULL) {
1516
0
        PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1517
0
        goto error;
1518
0
    }
1519
13
    if (!PyDict_Check(globals)) {
1520
0
        PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1521
0
        goto error;
1522
0
    }
1523
13
    package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
1524
13
    if (package == Py_None) {
1525
0
        package = NULL;
1526
0
    }
1527
13
    else if (package == NULL && PyErr_Occurred()) {
1528
0
        goto error;
1529
0
    }
1530
13
    spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
1531
13
    if (spec == NULL && PyErr_Occurred()) {
1532
0
        goto error;
1533
0
    }
1534
1535
13
    if (package != NULL) {
1536
13
        Py_INCREF(package);
1537
13
        if (!PyUnicode_Check(package)) {
1538
0
            PyErr_SetString(PyExc_TypeError, "package must be a string");
1539
0
            goto error;
1540
0
        }
1541
13
        else if (spec != NULL && spec != Py_None) {
1542
13
            int equal;
1543
13
            PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1544
13
            if (parent == NULL) {
1545
0
                goto error;
1546
0
            }
1547
1548
13
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1549
13
            Py_DECREF(parent);
1550
13
            if (equal < 0) {
1551
0
                goto error;
1552
0
            }
1553
13
            else if (equal == 0) {
1554
0
                if (PyErr_WarnEx(PyExc_ImportWarning,
1555
0
                        "__package__ != __spec__.parent", 1) < 0) {
1556
0
                    goto error;
1557
0
                }
1558
0
            }
1559
13
        }
1560
13
    }
1561
0
    else if (spec != NULL && spec != Py_None) {
1562
0
        package = _PyObject_GetAttrId(spec, &PyId_parent);
1563
0
        if (package == NULL) {
1564
0
            goto error;
1565
0
        }
1566
0
        else if (!PyUnicode_Check(package)) {
1567
0
            PyErr_SetString(PyExc_TypeError,
1568
0
                    "__spec__.parent must be a string");
1569
0
            goto error;
1570
0
        }
1571
0
    }
1572
0
    else {
1573
0
        if (PyErr_WarnEx(PyExc_ImportWarning,
1574
0
                    "can't resolve package from __spec__ or __package__, "
1575
0
                    "falling back on __name__ and __path__", 1) < 0) {
1576
0
            goto error;
1577
0
        }
1578
1579
0
        package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
1580
0
        if (package == NULL) {
1581
0
            if (!PyErr_Occurred()) {
1582
0
                PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1583
0
            }
1584
0
            goto error;
1585
0
        }
1586
1587
0
        Py_INCREF(package);
1588
0
        if (!PyUnicode_Check(package)) {
1589
0
            PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1590
0
            goto error;
1591
0
        }
1592
1593
0
        if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
1594
0
            Py_ssize_t dot;
1595
1596
0
            if (PyErr_Occurred() || PyUnicode_READY(package) < 0) {
1597
0
                goto error;
1598
0
            }
1599
1600
0
            dot = PyUnicode_FindChar(package, '.',
1601
0
                                        0, PyUnicode_GET_LENGTH(package), -1);
1602
0
            if (dot == -2) {
1603
0
                goto error;
1604
0
            }
1605
0
            else if (dot == -1) {
1606
0
                goto no_parent_error;
1607
0
            }
1608
0
            PyObject *substr = PyUnicode_Substring(package, 0, dot);
1609
0
            if (substr == NULL) {
1610
0
                goto error;
1611
0
            }
1612
0
            Py_SETREF(package, substr);
1613
0
        }
1614
0
    }
1615
1616
13
    last_dot = PyUnicode_GET_LENGTH(package);
1617
13
    if (last_dot == 0) {
1618
0
        goto no_parent_error;
1619
0
    }
1620
1621
13
    for (level_up = 1; level_up < level; level_up += 1) {
1622
0
        last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1623
0
        if (last_dot == -2) {
1624
0
            goto error;
1625
0
        }
1626
0
        else if (last_dot == -1) {
1627
0
            PyErr_SetString(PyExc_ValueError,
1628
0
                            "attempted relative import beyond top-level "
1629
0
                            "package");
1630
0
            goto error;
1631
0
        }
1632
0
    }
1633
1634
13
    base = PyUnicode_Substring(package, 0, last_dot);
1635
13
    Py_DECREF(package);
1636
13
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1637
13
        return base;
1638
13
    }
1639
1640
0
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1641
0
    Py_DECREF(base);
1642
0
    return abs_name;
1643
1644
0
  no_parent_error:
1645
0
    PyErr_SetString(PyExc_ImportError,
1646
0
                     "attempted relative import "
1647
0
                     "with no known parent package");
1648
1649
0
  error:
1650
0
    Py_XDECREF(package);
1651
0
    return NULL;
1652
0
}
1653
1654
static PyObject *
1655
import_find_and_load(PyObject *abs_name)
1656
340
{
1657
340
    _Py_IDENTIFIER(_find_and_load);
1658
340
    PyObject *mod = NULL;
1659
340
    PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1660
340
    int import_time = interp->config.import_time;
1661
340
    static int import_level;
1662
340
    static _PyTime_t accumulated;
1663
1664
340
    _PyTime_t t1 = 0, accumulated_copy = accumulated;
1665
1666
340
    PyObject *sys_path = PySys_GetObject("path");
1667
340
    PyObject *sys_meta_path = PySys_GetObject("meta_path");
1668
340
    PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1669
340
    if (PySys_Audit("import", "OOOOO",
1670
340
                    abs_name, Py_None, sys_path ? sys_path : Py_None,
1671
340
                    sys_meta_path ? sys_meta_path : Py_None,
1672
340
                    sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1673
0
        return NULL;
1674
0
    }
1675
1676
1677
    /* XOptions is initialized after first some imports.
1678
     * So we can't have negative cache before completed initialization.
1679
     * Anyway, importlib._find_and_load is much slower than
1680
     * _PyDict_GetItemIdWithError().
1681
     */
1682
340
    if (import_time) {
1683
0
        static int header = 1;
1684
0
        if (header) {
1685
0
            fputs("import time: self [us] | cumulative | imported package\n",
1686
0
                  stderr);
1687
0
            header = 0;
1688
0
        }
1689
1690
0
        import_level++;
1691
0
        t1 = _PyTime_GetPerfCounter();
1692
0
        accumulated = 0;
1693
0
    }
1694
1695
340
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1696
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1697
1698
340
    mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1699
340
                                        &PyId__find_and_load, abs_name,
1700
340
                                        interp->import_func, NULL);
1701
1702
340
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1703
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1704
0
                                       mod != NULL);
1705
1706
340
    if (import_time) {
1707
0
        _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1708
1709
0
        import_level--;
1710
0
        fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1711
0
                (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1712
0
                (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1713
0
                import_level*2, "", PyUnicode_AsUTF8(abs_name));
1714
1715
0
        accumulated = accumulated_copy + cum;
1716
0
    }
1717
1718
340
    return mod;
1719
340
}
1720
1721
PyObject *
1722
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1723
                                 PyObject *locals, PyObject *fromlist,
1724
                                 int level)
1725
1.53k
{
1726
1.53k
    _Py_IDENTIFIER(_handle_fromlist);
1727
1.53k
    PyObject *abs_name = NULL;
1728
1.53k
    PyObject *final_mod = NULL;
1729
1.53k
    PyObject *mod = NULL;
1730
1.53k
    PyObject *package = NULL;
1731
1.53k
    PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1732
1.53k
    int has_from;
1733
1734
1.53k
    if (name == NULL) {
1735
0
        PyErr_SetString(PyExc_ValueError, "Empty module name");
1736
0
        goto error;
1737
0
    }
1738
1739
    /* The below code is importlib.__import__() & _gcd_import(), ported to C
1740
       for added performance. */
1741
1742
1.53k
    if (!PyUnicode_Check(name)) {
1743
0
        PyErr_SetString(PyExc_TypeError, "module name must be a string");
1744
0
        goto error;
1745
0
    }
1746
1.53k
    if (PyUnicode_READY(name) < 0) {
1747
0
        goto error;
1748
0
    }
1749
1.53k
    if (level < 0) {
1750
0
        PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1751
0
        goto error;
1752
0
    }
1753
1754
1.53k
    if (level > 0) {
1755
13
        abs_name = resolve_name(name, globals, level);
1756
13
        if (abs_name == NULL)
1757
0
            goto error;
1758
13
    }
1759
1.52k
    else {  /* level == 0 */
1760
1.52k
        if (PyUnicode_GET_LENGTH(name) == 0) {
1761
0
            PyErr_SetString(PyExc_ValueError, "Empty module name");
1762
0
            goto error;
1763
0
        }
1764
1.52k
        abs_name = name;
1765
1.52k
        Py_INCREF(abs_name);
1766
1.52k
    }
1767
1768
1.53k
    mod = PyImport_GetModule(abs_name);
1769
1.53k
    if (mod == NULL && PyErr_Occurred()) {
1770
0
        goto error;
1771
0
    }
1772
1773
1.53k
    if (mod != NULL && mod != Py_None) {
1774
1.19k
        _Py_IDENTIFIER(__spec__);
1775
1.19k
        _Py_IDENTIFIER(_lock_unlock_module);
1776
1.19k
        PyObject *spec;
1777
1778
        /* Optimization: only call _bootstrap._lock_unlock_module() if
1779
           __spec__._initializing is true.
1780
           NOTE: because of this, initializing must be set *before*
1781
           stuffing the new module in sys.modules.
1782
         */
1783
1.19k
        spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1784
1.19k
        if (_PyModuleSpec_IsInitializing(spec)) {
1785
52
            PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1786
52
                                            &PyId__lock_unlock_module, abs_name,
1787
52
                                            NULL);
1788
52
            if (value == NULL) {
1789
0
                Py_DECREF(spec);
1790
0
                goto error;
1791
0
            }
1792
52
            Py_DECREF(value);
1793
52
        }
1794
1.19k
        Py_XDECREF(spec);
1795
1.19k
    }
1796
340
    else {
1797
340
        Py_XDECREF(mod);
1798
340
        mod = import_find_and_load(abs_name);
1799
340
        if (mod == NULL) {
1800
34
            goto error;
1801
34
        }
1802
340
    }
1803
1804
1.50k
    has_from = 0;
1805
1.50k
    if (fromlist != NULL && fromlist != Py_None) {
1806
780
        has_from = PyObject_IsTrue(fromlist);
1807
780
        if (has_from < 0)
1808
0
            goto error;
1809
780
    }
1810
1.50k
    if (!has_from) {
1811
1.23k
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1812
1.23k
        if (level == 0 || len > 0) {
1813
1.23k
            Py_ssize_t dot;
1814
1815
1.23k
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1816
1.23k
            if (dot == -2) {
1817
0
                goto error;
1818
0
            }
1819
1820
1.23k
            if (dot == -1) {
1821
                /* No dot in module name, simple exit */
1822
1.19k
                final_mod = mod;
1823
1.19k
                Py_INCREF(mod);
1824
1.19k
                goto error;
1825
1.19k
            }
1826
1827
40
            if (level == 0) {
1828
40
                PyObject *front = PyUnicode_Substring(name, 0, dot);
1829
40
                if (front == NULL) {
1830
0
                    goto error;
1831
0
                }
1832
1833
40
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
1834
40
                Py_DECREF(front);
1835
40
            }
1836
0
            else {
1837
0
                Py_ssize_t cut_off = len - dot;
1838
0
                Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
1839
0
                PyObject *to_return = PyUnicode_Substring(abs_name, 0,
1840
0
                                                        abs_name_len - cut_off);
1841
0
                if (to_return == NULL) {
1842
0
                    goto error;
1843
0
                }
1844
1845
0
                final_mod = PyImport_GetModule(to_return);
1846
0
                Py_DECREF(to_return);
1847
0
                if (final_mod == NULL) {
1848
0
                    if (!PyErr_Occurred()) {
1849
0
                        PyErr_Format(PyExc_KeyError,
1850
0
                                     "%R not in sys.modules as expected",
1851
0
                                     to_return);
1852
0
                    }
1853
0
                    goto error;
1854
0
                }
1855
0
            }
1856
40
        }
1857
0
        else {
1858
0
            final_mod = mod;
1859
0
            Py_INCREF(mod);
1860
0
        }
1861
1.23k
    }
1862
270
    else {
1863
270
        _Py_IDENTIFIER(__path__);
1864
270
        PyObject *path;
1865
270
        if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1866
0
            goto error;
1867
0
        }
1868
270
        if (path) {
1869
15
            Py_DECREF(path);
1870
15
            final_mod = _PyObject_CallMethodIdObjArgs(
1871
15
                        interp->importlib, &PyId__handle_fromlist,
1872
15
                        mod, fromlist, interp->import_func, NULL);
1873
15
        }
1874
255
        else {
1875
255
            final_mod = mod;
1876
255
            Py_INCREF(mod);
1877
255
        }
1878
270
    }
1879
1880
1.53k
  error:
1881
1.53k
    Py_XDECREF(abs_name);
1882
1.53k
    Py_XDECREF(mod);
1883
1.53k
    Py_XDECREF(package);
1884
1.53k
    if (final_mod == NULL) {
1885
34
        remove_importlib_frames(interp);
1886
34
    }
1887
1.53k
    return final_mod;
1888
1.50k
}
1889
1890
PyObject *
1891
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
1892
                           PyObject *fromlist, int level)
1893
117
{
1894
117
    PyObject *nameobj, *mod;
1895
117
    nameobj = PyUnicode_FromString(name);
1896
117
    if (nameobj == NULL)
1897
0
        return NULL;
1898
117
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1899
117
                                           fromlist, level);
1900
117
    Py_DECREF(nameobj);
1901
117
    return mod;
1902
117
}
1903
1904
1905
/* Re-import a module of any kind and return its module object, WITH
1906
   INCREMENTED REFERENCE COUNT */
1907
1908
PyObject *
1909
PyImport_ReloadModule(PyObject *m)
1910
0
{
1911
0
    _Py_IDENTIFIER(importlib);
1912
0
    _Py_IDENTIFIER(reload);
1913
0
    PyObject *reloaded_module = NULL;
1914
0
    PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1915
0
    if (importlib == NULL) {
1916
0
        if (PyErr_Occurred()) {
1917
0
            return NULL;
1918
0
        }
1919
1920
0
        importlib = PyImport_ImportModule("importlib");
1921
0
        if (importlib == NULL) {
1922
0
            return NULL;
1923
0
        }
1924
0
    }
1925
1926
0
    reloaded_module = _PyObject_CallMethodIdObjArgs(importlib, &PyId_reload, m, NULL);
1927
0
    Py_DECREF(importlib);
1928
0
    return reloaded_module;
1929
0
}
1930
1931
1932
/* Higher-level import emulator which emulates the "import" statement
1933
   more accurately -- it invokes the __import__() function from the
1934
   builtins of the current globals.  This means that the import is
1935
   done using whatever import hooks are installed in the current
1936
   environment.
1937
   A dummy list ["__doc__"] is passed as the 4th argument so that
1938
   e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
1939
   will return <module "gencache"> instead of <module "win32com">. */
1940
1941
PyObject *
1942
PyImport_Import(PyObject *module_name)
1943
510
{
1944
510
    static PyObject *silly_list = NULL;
1945
510
    static PyObject *builtins_str = NULL;
1946
510
    static PyObject *import_str = NULL;
1947
510
    PyObject *globals = NULL;
1948
510
    PyObject *import = NULL;
1949
510
    PyObject *builtins = NULL;
1950
510
    PyObject *r = NULL;
1951
1952
    /* Initialize constant string objects */
1953
510
    if (silly_list == NULL) {
1954
13
        import_str = PyUnicode_InternFromString("__import__");
1955
13
        if (import_str == NULL)
1956
0
            return NULL;
1957
13
        builtins_str = PyUnicode_InternFromString("__builtins__");
1958
13
        if (builtins_str == NULL)
1959
0
            return NULL;
1960
13
        silly_list = PyList_New(0);
1961
13
        if (silly_list == NULL)
1962
0
            return NULL;
1963
13
    }
1964
1965
    /* Get the builtins from current globals */
1966
510
    globals = PyEval_GetGlobals();
1967
510
    if (globals != NULL) {
1968
393
        Py_INCREF(globals);
1969
393
        builtins = PyObject_GetItem(globals, builtins_str);
1970
393
        if (builtins == NULL)
1971
0
            goto err;
1972
393
    }
1973
117
    else {
1974
        /* No globals -- use standard builtins, and fake globals */
1975
117
        builtins = PyImport_ImportModuleLevel("builtins",
1976
117
                                              NULL, NULL, NULL, 0);
1977
117
        if (builtins == NULL)
1978
0
            return NULL;
1979
117
        globals = Py_BuildValue("{OO}", builtins_str, builtins);
1980
117
        if (globals == NULL)
1981
0
            goto err;
1982
117
    }
1983
1984
    /* Get the __import__ function from the builtins */
1985
510
    if (PyDict_Check(builtins)) {
1986
220
        import = PyObject_GetItem(builtins, import_str);
1987
220
        if (import == NULL)
1988
0
            PyErr_SetObject(PyExc_KeyError, import_str);
1989
220
    }
1990
290
    else
1991
290
        import = PyObject_GetAttr(builtins, import_str);
1992
510
    if (import == NULL)
1993
0
        goto err;
1994
1995
    /* Call the __import__ function with the proper argument list
1996
       Always use absolute import here.
1997
       Calling for side-effect of import. */
1998
510
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1999
510
                              globals, silly_list, 0, NULL);
2000
510
    if (r == NULL)
2001
0
        goto err;
2002
510
    Py_DECREF(r);
2003
2004
510
    r = PyImport_GetModule(module_name);
2005
510
    if (r == NULL && !PyErr_Occurred()) {
2006
0
        PyErr_SetObject(PyExc_KeyError, module_name);
2007
0
    }
2008
2009
510
  err:
2010
510
    Py_XDECREF(globals);
2011
510
    Py_XDECREF(builtins);
2012
510
    Py_XDECREF(import);
2013
2014
510
    return r;
2015
510
}
2016
2017
/*[clinic input]
2018
_imp.extension_suffixes
2019
2020
Returns the list of file suffixes used to identify extension modules.
2021
[clinic start generated code]*/
2022
2023
static PyObject *
2024
_imp_extension_suffixes_impl(PyObject *module)
2025
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
2026
26
{
2027
26
    PyObject *list;
2028
2029
26
    list = PyList_New(0);
2030
26
    if (list == NULL)
2031
0
        return NULL;
2032
26
#ifdef HAVE_DYNAMIC_LOADING
2033
26
    const char *suffix;
2034
26
    unsigned int index = 0;
2035
2036
104
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
2037
78
        PyObject *item = PyUnicode_FromString(suffix);
2038
78
        if (item == NULL) {
2039
0
            Py_DECREF(list);
2040
0
            return NULL;
2041
0
        }
2042
78
        if (PyList_Append(list, item) < 0) {
2043
0
            Py_DECREF(list);
2044
0
            Py_DECREF(item);
2045
0
            return NULL;
2046
0
        }
2047
78
        Py_DECREF(item);
2048
78
        index += 1;
2049
78
    }
2050
26
#endif
2051
26
    return list;
2052
26
}
2053
2054
/*[clinic input]
2055
_imp.init_frozen
2056
2057
    name: unicode
2058
    /
2059
2060
Initializes a frozen module.
2061
[clinic start generated code]*/
2062
2063
static PyObject *
2064
_imp_init_frozen_impl(PyObject *module, PyObject *name)
2065
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
2066
0
{
2067
0
    int ret;
2068
0
    PyObject *m;
2069
2070
0
    ret = PyImport_ImportFrozenModuleObject(name);
2071
0
    if (ret < 0)
2072
0
        return NULL;
2073
0
    if (ret == 0) {
2074
0
        Py_RETURN_NONE;
2075
0
    }
2076
0
    m = PyImport_AddModuleObject(name);
2077
0
    Py_XINCREF(m);
2078
0
    return m;
2079
0
}
2080
2081
/*[clinic input]
2082
_imp.get_frozen_object
2083
2084
    name: unicode
2085
    /
2086
2087
Create a code object for a frozen module.
2088
[clinic start generated code]*/
2089
2090
static PyObject *
2091
_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2092
/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
2093
26
{
2094
26
    return get_frozen_object(name);
2095
26
}
2096
2097
/*[clinic input]
2098
_imp.is_frozen_package
2099
2100
    name: unicode
2101
    /
2102
2103
Returns True if the module name is of a frozen package.
2104
[clinic start generated code]*/
2105
2106
static PyObject *
2107
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2108
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
2109
26
{
2110
26
    return is_frozen_package(name);
2111
26
}
2112
2113
/*[clinic input]
2114
_imp.is_builtin
2115
2116
    name: unicode
2117
    /
2118
2119
Returns True if the module name corresponds to a built-in module.
2120
[clinic start generated code]*/
2121
2122
static PyObject *
2123
_imp_is_builtin_impl(PyObject *module, PyObject *name)
2124
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
2125
391
{
2126
391
    return PyLong_FromLong(is_builtin(name));
2127
391
}
2128
2129
/*[clinic input]
2130
_imp.is_frozen
2131
2132
    name: unicode
2133
    /
2134
2135
Returns True if the module name corresponds to a frozen module.
2136
[clinic start generated code]*/
2137
2138
static PyObject *
2139
_imp_is_frozen_impl(PyObject *module, PyObject *name)
2140
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
2141
345
{
2142
345
    const struct _frozen *p;
2143
2144
345
    p = find_frozen(name);
2145
345
    return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2146
345
}
2147
2148
/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2149
static int
2150
164
exec_builtin_or_dynamic(PyObject *mod) {
2151
164
    PyModuleDef *def;
2152
164
    void *state;
2153
2154
164
    if (!PyModule_Check(mod)) {
2155
0
        return 0;
2156
0
    }
2157
2158
164
    def = PyModule_GetDef(mod);
2159
164
    if (def == NULL) {
2160
0
        return 0;
2161
0
    }
2162
2163
164
    state = PyModule_GetState(mod);
2164
164
    if (state) {
2165
        /* Already initialized; skip reload */
2166
13
        return 0;
2167
13
    }
2168
2169
151
    return PyModule_ExecDef(mod, def);
2170
164
}
2171
2172
#ifdef HAVE_DYNAMIC_LOADING
2173
2174
/*[clinic input]
2175
_imp.create_dynamic
2176
2177
    spec: object
2178
    file: object = NULL
2179
    /
2180
2181
Create an extension module.
2182
[clinic start generated code]*/
2183
2184
static PyObject *
2185
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2186
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
2187
0
{
2188
0
    PyObject *mod, *name, *path;
2189
0
    FILE *fp;
2190
2191
0
    name = PyObject_GetAttrString(spec, "name");
2192
0
    if (name == NULL) {
2193
0
        return NULL;
2194
0
    }
2195
2196
0
    path = PyObject_GetAttrString(spec, "origin");
2197
0
    if (path == NULL) {
2198
0
        Py_DECREF(name);
2199
0
        return NULL;
2200
0
    }
2201
2202
0
    mod = _PyImport_FindExtensionObject(name, path);
2203
0
    if (mod != NULL || PyErr_Occurred()) {
2204
0
        Py_DECREF(name);
2205
0
        Py_DECREF(path);
2206
0
        Py_XINCREF(mod);
2207
0
        return mod;
2208
0
    }
2209
2210
0
    if (file != NULL) {
2211
0
        fp = _Py_fopen_obj(path, "r");
2212
0
        if (fp == NULL) {
2213
0
            Py_DECREF(name);
2214
0
            Py_DECREF(path);
2215
0
            return NULL;
2216
0
        }
2217
0
    }
2218
0
    else
2219
0
        fp = NULL;
2220
2221
0
    mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2222
2223
0
    Py_DECREF(name);
2224
0
    Py_DECREF(path);
2225
0
    if (fp)
2226
0
        fclose(fp);
2227
0
    return mod;
2228
0
}
2229
2230
/*[clinic input]
2231
_imp.exec_dynamic -> int
2232
2233
    mod: object
2234
    /
2235
2236
Initialize an extension module.
2237
[clinic start generated code]*/
2238
2239
static int
2240
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2241
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
2242
0
{
2243
0
    return exec_builtin_or_dynamic(mod);
2244
0
}
2245
2246
2247
#endif /* HAVE_DYNAMIC_LOADING */
2248
2249
/*[clinic input]
2250
_imp.exec_builtin -> int
2251
2252
    mod: object
2253
    /
2254
2255
Initialize a built-in module.
2256
[clinic start generated code]*/
2257
2258
static int
2259
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2260
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
2261
164
{
2262
164
    return exec_builtin_or_dynamic(mod);
2263
164
}
2264
2265
/*[clinic input]
2266
_imp.source_hash
2267
2268
    key: long
2269
    source: Py_buffer
2270
[clinic start generated code]*/
2271
2272
static PyObject *
2273
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2274
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2275
0
{
2276
0
    union {
2277
0
        uint64_t x;
2278
0
        char data[sizeof(uint64_t)];
2279
0
    } hash;
2280
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
2281
#if !PY_LITTLE_ENDIAN
2282
    // Force to little-endian. There really ought to be a succinct standard way
2283
    // to do this.
2284
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2285
        char tmp = hash.data[i];
2286
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2287
        hash.data[sizeof(hash.data) - i - 1] = tmp;
2288
    }
2289
#endif
2290
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
2291
0
}
2292
2293
2294
PyDoc_STRVAR(doc_imp,
2295
"(Extremely) low-level import machinery bits as used by importlib and imp.");
2296
2297
static PyMethodDef imp_methods[] = {
2298
    _IMP_EXTENSION_SUFFIXES_METHODDEF
2299
    _IMP_LOCK_HELD_METHODDEF
2300
    _IMP_ACQUIRE_LOCK_METHODDEF
2301
    _IMP_RELEASE_LOCK_METHODDEF
2302
    _IMP_GET_FROZEN_OBJECT_METHODDEF
2303
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
2304
    _IMP_CREATE_BUILTIN_METHODDEF
2305
    _IMP_INIT_FROZEN_METHODDEF
2306
    _IMP_IS_BUILTIN_METHODDEF
2307
    _IMP_IS_FROZEN_METHODDEF
2308
    _IMP_CREATE_DYNAMIC_METHODDEF
2309
    _IMP_EXEC_DYNAMIC_METHODDEF
2310
    _IMP_EXEC_BUILTIN_METHODDEF
2311
    _IMP__FIX_CO_FILENAME_METHODDEF
2312
    _IMP_SOURCE_HASH_METHODDEF
2313
    {NULL, NULL}  /* sentinel */
2314
};
2315
2316
2317
static struct PyModuleDef impmodule = {
2318
    PyModuleDef_HEAD_INIT,
2319
    "_imp",
2320
    doc_imp,
2321
    0,
2322
    imp_methods,
2323
    NULL,
2324
    NULL,
2325
    NULL,
2326
    NULL
2327
};
2328
2329
PyMODINIT_FUNC
2330
PyInit__imp(void)
2331
13
{
2332
13
    PyObject *m, *d;
2333
2334
13
    m = PyModule_Create(&impmodule);
2335
13
    if (m == NULL) {
2336
0
        goto failure;
2337
0
    }
2338
13
    d = PyModule_GetDict(m);
2339
13
    if (d == NULL) {
2340
0
        goto failure;
2341
0
    }
2342
2343
13
    const wchar_t *mode = _PyInterpreterState_Get()->config.check_hash_pycs_mode;
2344
13
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
2345
13
    if (pyc_mode == NULL) {
2346
0
        goto failure;
2347
0
    }
2348
13
    if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2349
0
        Py_DECREF(pyc_mode);
2350
0
        goto failure;
2351
0
    }
2352
13
    Py_DECREF(pyc_mode);
2353
2354
13
    return m;
2355
0
  failure:
2356
0
    Py_XDECREF(m);
2357
0
    return NULL;
2358
13
}
2359
2360
2361
/* API for embedding applications that want to add their own entries
2362
   to the table of built-in modules.  This should normally be called
2363
   *before* Py_Initialize().  When the table resize fails, -1 is
2364
   returned and the existing table is unchanged.
2365
2366
   After a similar function by Just van Rossum. */
2367
2368
int
2369
PyImport_ExtendInittab(struct _inittab *newtab)
2370
0
{
2371
0
    struct _inittab *p;
2372
0
    size_t i, n;
2373
0
    int res = 0;
2374
2375
    /* Count the number of entries in both tables */
2376
0
    for (n = 0; newtab[n].name != NULL; n++)
2377
0
        ;
2378
0
    if (n == 0)
2379
0
        return 0; /* Nothing to do */
2380
0
    for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2381
0
        ;
2382
2383
    /* Force default raw memory allocator to get a known allocator to be able
2384
       to release the memory in _PyImport_Fini2() */
2385
0
    PyMemAllocatorEx old_alloc;
2386
0
    _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2387
2388
    /* Allocate new memory for the combined table */
2389
0
    p = NULL;
2390
0
    if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
2391
0
        size_t size = sizeof(struct _inittab) * (i + n + 1);
2392
0
        p = PyMem_RawRealloc(inittab_copy, size);
2393
0
    }
2394
0
    if (p == NULL) {
2395
0
        res = -1;
2396
0
        goto done;
2397
0
    }
2398
2399
    /* Copy the tables into the new memory at the first call
2400
       to PyImport_ExtendInittab(). */
2401
0
    if (inittab_copy != PyImport_Inittab) {
2402
0
        memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2403
0
    }
2404
0
    memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2405
0
    PyImport_Inittab = inittab_copy = p;
2406
2407
0
done:
2408
0
    PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2409
0
    return res;
2410
0
}
2411
2412
/* Shorthand to add a single entry given a name and a function */
2413
2414
int
2415
PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
2416
0
{
2417
0
    struct _inittab newtab[2];
2418
2419
0
    memset(newtab, '\0', sizeof newtab);
2420
2421
0
    newtab[0].name = name;
2422
0
    newtab[0].initfunc = initfunc;
2423
2424
0
    return PyImport_ExtendInittab(newtab);
2425
0
}
2426
2427
#ifdef __cplusplus
2428
}
2429
#endif