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