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