ยปCore Development>Code coverage>Python/import.c

Python code coverage for Python/import.c

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