blob: 2aacf659351bb66e3aa34c9c6d382a170be203b2 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06008#include "internal/pystate.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000010#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020012#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000013#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000014#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000015
Guido van Rossum55a83382000-09-20 20:31:38 +000016#ifdef HAVE_FCNTL_H
17#include <fcntl.h>
18#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000020extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000022
Barry Warsaw28a691b2010-04-17 00:19:56 +000023#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000024
Victor Stinner95872862011-03-07 18:20:56 +010025/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000026static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000027
Guido van Rossum771c6c81997-10-31 18:37:24 +000028/* This table is defined in config.c: */
29extern struct _inittab _PyImport_Inittab[];
30
31struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000032
Victor Stinnerd0296212011-03-14 14:04:10 -040033static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000034
Brett Cannon4caa61d2014-01-09 19:03:32 -050035/*[clinic input]
36module _imp
37[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030038/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040039
40#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050041
Guido van Rossum1ae940a1995-01-02 19:04:15 +000042/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043
44void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000045_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020047 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040048 initstr = PyUnicode_InternFromString("__init__");
49 if (initstr == NULL)
50 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020051 interp->builtins_copy = PyDict_Copy(interp->builtins);
52 if (interp->builtins_copy == NULL)
53 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054}
55
Guido van Rossum25ce5661997-08-02 03:10:38 +000056void
Just van Rossum52e14d62002-12-30 22:08:05 +000057_PyImportHooks_Init(void)
58{
Brett Cannonfd074152012-04-14 14:10:13 -040059 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000061
Brett Cannonfd074152012-04-14 14:10:13 -040062 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 v = PyList_New(0);
64 if (v == NULL)
65 goto error;
66 err = PySys_SetObject("meta_path", v);
67 Py_DECREF(v);
68 if (err)
69 goto error;
70 v = PyDict_New();
71 if (v == NULL)
72 goto error;
73 err = PySys_SetObject("path_importer_cache", v);
74 Py_DECREF(v);
75 if (err)
76 goto error;
77 path_hooks = PyList_New(0);
78 if (path_hooks == NULL)
79 goto error;
80 err = PySys_SetObject("path_hooks", path_hooks);
81 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000082 error:
Brett Cannonfd074152012-04-14 14:10:13 -040083 PyErr_Print();
84 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020085 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 }
Brett Cannonfd074152012-04-14 14:10:13 -040087 Py_DECREF(path_hooks);
88}
89
90void
91_PyImportZip_Init(void)
92{
93 PyObject *path_hooks, *zimpimport;
94 int err = 0;
95
96 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020097 if (path_hooks == NULL) {
98 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040099 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200100 }
Brett Cannonfd074152012-04-14 14:10:13 -0400101
102 if (Py_VerboseFlag)
103 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 zimpimport = PyImport_ImportModule("zipimport");
106 if (zimpimport == NULL) {
107 PyErr_Clear(); /* No zip import module -- okay */
108 if (Py_VerboseFlag)
109 PySys_WriteStderr("# can't import zipimport\n");
110 }
111 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200112 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200113 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
114 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_DECREF(zimpimport);
116 if (zipimporter == NULL) {
117 PyErr_Clear(); /* No zipimporter object -- okay */
118 if (Py_VerboseFlag)
119 PySys_WriteStderr(
120 "# can't import zipimport.zipimporter\n");
121 }
122 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400123 /* sys.path_hooks.insert(0, zipimporter) */
124 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400126 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 if (Py_VerboseFlag)
130 PySys_WriteStderr(
131 "# installed zipimport hook\n");
132 }
133 }
Brett Cannonfd074152012-04-14 14:10:13 -0400134
135 return;
136
137 error:
138 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400139 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000140}
141
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000142/* Locking primitives to prevent parallel imports of the same module
143 in different threads to return with a partially loaded module.
144 These calls are serialized by the global interpreter lock. */
145
Guido van Rossum49b56061998-10-01 20:42:43 +0000146#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147
Guido van Rossum65d5b571998-12-21 19:32:43 +0000148static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200149static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000150static int import_lock_level = 0;
151
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000152void
153_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200155 unsigned long me = PyThread_get_thread_ident();
156 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 return; /* Too bad */
158 if (import_lock == NULL) {
159 import_lock = PyThread_allocate_lock();
160 if (import_lock == NULL)
161 return; /* Nothing much we can do. */
162 }
163 if (import_lock_thread == me) {
164 import_lock_level++;
165 return;
166 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200167 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
168 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 {
170 PyThreadState *tstate = PyEval_SaveThread();
171 PyThread_acquire_lock(import_lock, 1);
172 PyEval_RestoreThread(tstate);
173 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100174 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 import_lock_thread = me;
176 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000177}
178
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000179int
180_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000181{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200182 unsigned long me = PyThread_get_thread_ident();
183 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 return 0; /* Too bad */
185 if (import_lock_thread != me)
186 return -1;
187 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100188 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200190 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 PyThread_release_lock(import_lock);
192 }
193 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000194}
195
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200196/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000197 created child processes do not share locks with the parent.
198 We now acquire the import lock around fork() calls but on some platforms
199 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000200
201void
202_PyImport_ReInitLock(void)
203{
Christian Heimes418fd742015-04-19 21:08:42 +0200204 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200206 if (import_lock == NULL) {
207 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
208 }
209 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000210 if (import_lock_level > 1) {
211 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200212 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500213 /* The following could fail if the lock is already held, but forking as
214 a side-effect of an import is a) rare, b) nuts, and c) difficult to
215 do thanks to the lock only being held when doing individual module
216 locks per import. */
217 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000218 import_lock_thread = me;
219 import_lock_level--;
220 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200221 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000222 import_lock_level = 0;
223 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000224}
225
Brett Cannon4caa61d2014-01-09 19:03:32 -0500226/*[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
Brett Cannon4caa61d2014-01-09 19:03:32 -0500234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300235_imp_lock_held_impl(PyObject *module)
236/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000237{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200238 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000239}
240
Brett Cannon4caa61d2014-01-09 19:03:32 -0500241/*[clinic input]
242_imp.acquire_lock
243
244Acquires the interpreter's import lock for the current thread.
245
246This lock should be used by import hooks to ensure thread-safety when importing
247modules. On platforms without threads, this function does nothing.
248[clinic start generated code]*/
249
Brett Cannon4caa61d2014-01-09 19:03:32 -0500250static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300251_imp_acquire_lock_impl(PyObject *module)
252/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200255 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000256}
257
Brett Cannon4caa61d2014-01-09 19:03:32 -0500258/*[clinic input]
259_imp.release_lock
260
261Release the interpreter's import lock.
262
263On platforms without threads, this function does nothing.
264[clinic start generated code]*/
265
Brett Cannon4caa61d2014-01-09 19:03:32 -0500266static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300267_imp_release_lock_impl(PyObject *module)
268/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (_PyImport_ReleaseLock() < 0) {
271 PyErr_SetString(PyExc_RuntimeError,
272 "not holding the import lock");
273 return NULL;
274 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200275 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000276}
277
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100278void
279_PyImport_Fini(void)
280{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200281 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100282 if (import_lock != NULL) {
283 PyThread_free_lock(import_lock);
284 import_lock = NULL;
285 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100286}
287
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288/* Helper for sys */
289
290PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000291PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000292{
Eric Snow93c92f72017-09-13 23:46:04 -0700293 PyInterpreterState *interp = PyThreadState_GET()->interp;
294 if (interp->modules == NULL)
295 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
296 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000297}
298
Guido van Rossum3f5da241990-12-20 15:06:42 +0000299
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000300/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200301static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 "path", "argv", "ps1", "ps2",
303 "last_type", "last_value", "last_traceback",
304 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200305 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 /* misc stuff */
307 "flags", "float_info",
308 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000309};
310
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200311static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 "stdin", "__stdin__",
313 "stdout", "__stdout__",
314 "stderr", "__stderr__",
315 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000316};
317
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000318/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000319
Guido van Rossum3f5da241990-12-20 15:06:42 +0000320void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000321PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000322{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200323 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyObject *key, *value, *dict;
325 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snow93c92f72017-09-13 23:46:04 -0700326 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200327 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200328 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (modules == NULL)
331 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 /* Delete some special variables first. These are common
334 places where user values hide and people complain when their
335 destructors fail. Since the modules containing them are
336 deleted *last* of all, they would come too late in the normal
337 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000338
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200339 /* XXX Perhaps these precautions are obsolete. Who knows? */
340
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200341 if (Py_VerboseFlag)
342 PySys_WriteStderr("# clear builtins._\n");
343 PyDict_SetItemString(interp->builtins, "_", Py_None);
344
345 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200347 PySys_WriteStderr("# clear sys.%s\n", *p);
348 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200350 for (p = sys_files; *p != NULL; p+=2) {
351 if (Py_VerboseFlag)
352 PySys_WriteStderr("# restore sys.%s\n", *p);
353 value = PyDict_GetItemString(interp->sysdict, *(p+1));
354 if (value == NULL)
355 value = Py_None;
356 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000358
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200359 /* We prepare a list which will receive (name, weakref) tuples of
360 modules when they are removed from sys.modules. The name is used
361 for diagnosis messages (in verbose mode), while the weakref helps
362 detect those modules which have been held alive. */
363 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200364 if (weaklist == NULL)
365 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200366
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200367#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200368 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200369 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
370 if (name && wr) { \
371 PyObject *tup = PyTuple_Pack(2, name, wr); \
372 PyList_Append(weaklist, tup); \
373 Py_XDECREF(tup); \
374 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200375 Py_XDECREF(wr); \
376 if (PyErr_Occurred()) \
377 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000379
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200380 /* Remove all modules from sys.modules, hoping that garbage collection
381 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 pos = 0;
383 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200384 if (PyModule_Check(value)) {
385 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200386 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200387 STORE_MODULE_WEAKREF(key, value);
Eric Snow93c92f72017-09-13 23:46:04 -0700388 PyDict_SetItem(modules, key, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 }
390 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000391
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200392 /* Clear the modules dict. */
393 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200394 /* Restore the original builtins dict, to ensure that any
395 user data gets cleared. */
396 dict = PyDict_Copy(interp->builtins);
397 if (dict == NULL)
398 PyErr_Clear();
399 PyDict_Clear(interp->builtins);
400 if (PyDict_Update(interp->builtins, interp->builtins_copy))
401 PyErr_Clear();
402 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200403 /* Clear module dict copies stored in the interpreter state */
404 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200405 /* Collect references */
406 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200407 /* Dump GC stats before it's too late, since it uses the warnings
408 machinery. */
409 _PyGC_DumpShutdownStats();
410
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200411 /* Now, if there are any modules left alive, clear their globals to
412 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200413 up here, since they are kept alive in the interpreter state.
414
415 The special treatment of "builtins" here is because even
416 when it's not referenced as a module, its dictionary is
417 referenced by almost every module's __builtins__. Since
418 deleting a module clears its dictionary (even if there are
419 references left to it), we need to delete the "builtins"
420 module last. Likewise, we don't delete sys until the very
421 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200422 if (weaklist != NULL) {
423 Py_ssize_t i, n;
424 n = PyList_GET_SIZE(weaklist);
425 for (i = 0; i < n; i++) {
426 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200427 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200428 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
429 if (mod == Py_None)
430 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200431 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200432 dict = PyModule_GetDict(mod);
433 if (dict == interp->builtins || dict == interp->sysdict)
434 continue;
435 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200436 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200437 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200438 _PyModule_Clear(mod);
439 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200440 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200441 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000443
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200444 /* Next, delete sys and builtins (in that order) */
445 if (Py_VerboseFlag)
446 PySys_FormatStderr("# cleanup[3] wiping sys\n");
447 _PyModule_ClearDict(interp->sysdict);
448 if (Py_VerboseFlag)
449 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
450 _PyModule_ClearDict(interp->builtins);
451
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200452 /* Clear and delete the modules directory. Actual modules will
453 still be there only if imported during the execution of some
454 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700455 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457
458 /* Once more */
459 _PyGC_CollectNoFail();
460
461#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000462}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000463
464
Barry Warsaw28a691b2010-04-17 00:19:56 +0000465/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000466
467long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000468PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000469{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200470 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400471 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600472 PyObject *external, *pyc_magic;
473
474 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
475 if (external == NULL)
476 return -1;
477 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
478 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400479 if (pyc_magic == NULL)
480 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200481 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700482 Py_DECREF(pyc_magic);
483 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000484}
485
486
Brett Cannon3adc7b72012-07-09 14:22:12 -0400487extern const char * _PySys_ImplCacheTag;
488
Barry Warsaw28a691b2010-04-17 00:19:56 +0000489const char *
490PyImport_GetMagicTag(void)
491{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400492 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000493}
494
Brett Cannon98979b82012-07-02 15:13:11 -0400495
Guido van Rossum25ce5661997-08-02 03:10:38 +0000496/* Magic for extension modules (built-in as well as dynamically
497 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200498 once, we keep a static dictionary 'extensions' keyed by the tuple
499 (module name, module name) (for built-in modules) or by
500 (filename, module name) (for dynamically loaded modules), containing these
501 modules. A copy of the module's dictionary is stored by calling
502 _PyImport_FixupExtensionObject() immediately after the module initialization
503 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100504 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000505
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000506 Modules which do support multiple initialization set their m_size
507 field to a non-negative number (indicating the size of the
508 module-specific state). They are still recorded in the extensions
509 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000510*/
511
512int
Victor Stinner95872862011-03-07 18:20:56 +0100513_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snow93c92f72017-09-13 23:46:04 -0700514 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000515{
Eric Snow93c92f72017-09-13 23:46:04 -0700516 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500518 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (extensions == NULL) {
520 extensions = PyDict_New();
521 if (extensions == NULL)
522 return -1;
523 }
524 if (mod == NULL || !PyModule_Check(mod)) {
525 PyErr_BadInternalCall();
526 return -1;
527 }
528 def = PyModule_GetDef(mod);
529 if (!def) {
530 PyErr_BadInternalCall();
531 return -1;
532 }
Eric Snow93c92f72017-09-13 23:46:04 -0700533 modules = PyImport_GetModuleDict();
534 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return -1;
536 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow93c92f72017-09-13 23:46:04 -0700537 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return -1;
539 }
540 if (def->m_size == -1) {
541 if (def->m_base.m_copy) {
542 /* Somebody already imported the module,
543 likely under a different name.
544 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200545 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 }
547 dict = PyModule_GetDict(mod);
548 if (dict == NULL)
549 return -1;
550 def->m_base.m_copy = PyDict_Copy(dict);
551 if (def->m_base.m_copy == NULL)
552 return -1;
553 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500554 key = PyTuple_Pack(2, filename, name);
555 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200556 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500557 res = PyDict_SetItem(extensions, key, (PyObject *)def);
558 Py_DECREF(key);
559 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200560 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562}
563
Victor Stinner49d3f252010-10-17 01:24:53 +0000564int
Eric Snow93c92f72017-09-13 23:46:04 -0700565_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000566{
567 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100568 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100569 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100570 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000571 return -1;
Eric Snow93c92f72017-09-13 23:46:04 -0700572 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100573 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000574 return res;
575}
576
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100578_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500580 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyModuleDef* def;
582 if (extensions == NULL)
583 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500584 key = PyTuple_Pack(2, filename, name);
585 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200586 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500587 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
588 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (def == NULL)
590 return NULL;
591 if (def->m_size == -1) {
592 /* Module does not support repeated initialization */
593 if (def->m_base.m_copy == NULL)
594 return NULL;
Eric Snow93c92f72017-09-13 23:46:04 -0700595 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (mod == NULL)
597 return NULL;
598 mdict = PyModule_GetDict(mod);
599 if (mdict == NULL)
600 return NULL;
601 if (PyDict_Update(mdict, def->m_base.m_copy))
602 return NULL;
603 }
604 else {
605 if (def->m_base.m_init == NULL)
606 return NULL;
607 mod = def->m_base.m_init();
608 if (mod == NULL)
609 return NULL;
Eric Snow93c92f72017-09-13 23:46:04 -0700610 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200611 Py_DECREF(mod);
612 return NULL;
613 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 Py_DECREF(mod);
615 }
616 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow93c92f72017-09-13 23:46:04 -0700617 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 Py_DECREF(mod);
619 return NULL;
620 }
621 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100622 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 name, filename);
624 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000625
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000626}
627
Victor Stinner49d3f252010-10-17 01:24:53 +0000628PyObject *
Eric Snow93c92f72017-09-13 23:46:04 -0700629_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000630{
Victor Stinner95872862011-03-07 18:20:56 +0100631 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100632 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100633 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000634 return NULL;
Eric Snow93c92f72017-09-13 23:46:04 -0700635 res = _PyImport_FindExtensionObject(nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100636 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000637 return res;
638}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000639
640/* Get the module object corresponding to a module name.
641 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000642 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000643 Because the former action is most common, THIS DOES NOT RETURN A
644 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000645
Guido van Rossum79f25d91997-04-29 20:08:16 +0000646PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000647PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *modules = PyImport_GetModuleDict();
Eric Snow86b7afd2017-09-04 17:54:09 -0600650 PyObject *m;
Eric Snow93c92f72017-09-13 23:46:04 -0700651
652 if ((m = PyDict_GetItemWithError(modules, name)) != NULL &&
653 PyModule_Check(m)) {
654 return m;
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200655 }
656 if (PyErr_Occurred()) {
657 return NULL;
658 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000659 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (m == NULL)
661 return NULL;
Eric Snow93c92f72017-09-13 23:46:04 -0700662 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 Py_DECREF(m);
664 return NULL;
665 }
666 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000669}
670
Victor Stinner27ee0892011-03-04 12:57:09 +0000671PyObject *
672PyImport_AddModule(const char *name)
673{
674 PyObject *nameobj, *module;
675 nameobj = PyUnicode_FromString(name);
676 if (nameobj == NULL)
677 return NULL;
678 module = PyImport_AddModuleObject(nameobj);
679 Py_DECREF(nameobj);
680 return module;
681}
682
683
Tim Peters1cd70172004-08-02 03:52:12 +0000684/* Remove name from sys.modules, if it's there. */
685static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000686remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyObject *modules = PyImport_GetModuleDict();
Eric Snow93c92f72017-09-13 23:46:04 -0700689 if (PyDict_GetItem(modules, name) == NULL)
690 return;
691 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 Py_FatalError("import: deleting existing key in"
693 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000694}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000695
Christian Heimes3b06e532008-01-07 20:12:44 +0000696
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000697/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000698 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
699 * removed from sys.modules, to avoid leaving damaged module objects
700 * in sys.modules. The caller may wish to restore the original
701 * module object (if any) in this case; PyImport_ReloadModule is an
702 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000703 *
704 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
705 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000706 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000707PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300708PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 return PyImport_ExecCodeModuleWithPathnames(
711 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000712}
713
714PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300715PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return PyImport_ExecCodeModuleWithPathnames(
718 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000719}
720
721PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300722PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
723 const char *pathname,
724 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000725{
Victor Stinner27ee0892011-03-04 12:57:09 +0000726 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600727 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000728
729 nameobj = PyUnicode_FromString(name);
730 if (nameobj == NULL)
731 return NULL;
732
Victor Stinner27ee0892011-03-04 12:57:09 +0000733 if (cpathname != NULL) {
734 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
735 if (cpathobj == NULL)
736 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400737 }
738 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000739 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400740
741 if (pathname != NULL) {
742 pathobj = PyUnicode_DecodeFSDefault(pathname);
743 if (pathobj == NULL)
744 goto error;
745 }
746 else if (cpathobj != NULL) {
747 PyInterpreterState *interp = PyThreadState_GET()->interp;
748 _Py_IDENTIFIER(_get_sourcefile);
749
750 if (interp == NULL) {
751 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
752 "no interpreter!");
753 }
754
Eric Snow32439d62015-05-02 19:15:18 -0600755 external= PyObject_GetAttrString(interp->importlib,
756 "_bootstrap_external");
757 if (external != NULL) {
758 pathobj = _PyObject_CallMethodIdObjArgs(external,
759 &PyId__get_sourcefile, cpathobj,
760 NULL);
761 Py_DECREF(external);
762 }
Brett Cannona6473f92012-07-13 13:57:03 -0400763 if (pathobj == NULL)
764 PyErr_Clear();
765 }
766 else
767 pathobj = NULL;
768
Victor Stinner27ee0892011-03-04 12:57:09 +0000769 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
770error:
771 Py_DECREF(nameobj);
772 Py_XDECREF(pathobj);
773 Py_XDECREF(cpathobj);
774 return m;
775}
776
Brett Cannon18fc4e72014-04-04 10:01:46 -0400777static PyObject *
778module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000779{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400780 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781
Victor Stinner27ee0892011-03-04 12:57:09 +0000782 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (m == NULL)
784 return NULL;
785 /* If the module is being reloaded, we get the old module back
786 and re-use its dict to exec the new code. */
787 d = PyModule_GetDict(m);
788 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
789 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400790 PyEval_GetBuiltins()) != 0) {
791 remove_module(name);
792 return NULL;
793 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400795
Eric Snow08197a42014-05-12 17:54:55 -0600796 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400797}
798
799static PyObject *
800exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
801{
Eric Snow93c92f72017-09-13 23:46:04 -0700802 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon18fc4e72014-04-04 10:01:46 -0400803 PyObject *v, *m;
804
805 v = PyEval_EvalCode(code_object, module_dict, module_dict);
806 if (v == NULL) {
807 remove_module(name);
808 return NULL;
809 }
810 Py_DECREF(v);
811
Eric Snow93c92f72017-09-13 23:46:04 -0700812 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400813 PyErr_Format(PyExc_ImportError,
814 "Loaded module %R not found in sys.modules",
815 name);
816 return NULL;
817 }
818
819 Py_INCREF(m);
820
821 return m;
822}
823
824PyObject*
825PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
826 PyObject *cpathname)
827{
Eric Snow32439d62015-05-02 19:15:18 -0600828 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600829 PyInterpreterState *interp = PyThreadState_GET()->interp;
830 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400831
832 d = module_dict_for_exec(name);
833 if (d == NULL) {
834 return NULL;
835 }
836
Eric Snow08197a42014-05-12 17:54:55 -0600837 if (pathname == NULL) {
838 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
Eric Snow32439d62015-05-02 19:15:18 -0600840 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
841 if (external == NULL)
842 return NULL;
843 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600844 &PyId__fix_up_module,
845 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600846 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600847 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600848 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600849 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 }
Eric Snow08197a42014-05-12 17:54:55 -0600851 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000852}
853
854
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000855static void
856update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyObject *constants, *tmp;
859 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (PyUnicode_Compare(co->co_filename, oldname))
862 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000863
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200864 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300865 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 constants = co->co_consts;
868 n = PyTuple_GET_SIZE(constants);
869 for (i = 0; i < n; i++) {
870 tmp = PyTuple_GET_ITEM(constants, i);
871 if (PyCode_Check(tmp))
872 update_code_filenames((PyCodeObject *)tmp,
873 oldname, newname);
874 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000875}
876
Victor Stinner2f42ae52011-03-20 00:41:24 +0100877static void
878update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000879{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100880 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000881
Victor Stinner2f42ae52011-03-20 00:41:24 +0100882 if (PyUnicode_Compare(co->co_filename, newname) == 0)
883 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 oldname = co->co_filename;
886 Py_INCREF(oldname);
887 update_code_filenames(co, oldname, newname);
888 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000889}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000890
Brett Cannon4caa61d2014-01-09 19:03:32 -0500891/*[clinic input]
892_imp._fix_co_filename
893
894 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
895 Code object to change.
896
897 path: unicode
898 File path to use.
899 /
900
901Changes code.co_filename to specify the passed-in file path.
902[clinic start generated code]*/
903
Brett Cannon4caa61d2014-01-09 19:03:32 -0500904static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300905_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400906 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300907/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700908
Brett Cannon4caa61d2014-01-09 19:03:32 -0500909{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500910 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700911
912 Py_RETURN_NONE;
913}
914
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000915
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000916/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700917static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000918
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000919
920/* Helper to test for built-in module */
921
922static int
Victor Stinner95872862011-03-07 18:20:56 +0100923is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000924{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200925 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200927 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (PyImport_Inittab[i].initfunc == NULL)
929 return -1;
930 else
931 return 1;
932 }
933 }
934 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000935}
936
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000937
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700938/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000939 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000940 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000941 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700942 this tells our caller that the path based finder could not find
943 a finder for this path item. Cache the result in
944 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +0000945 Returns a borrowed reference. */
946
947static PyObject *
948get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyObject *importer;
952 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* These conditions are the caller's responsibility: */
955 assert(PyList_Check(path_hooks));
956 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 nhooks = PyList_Size(path_hooks);
959 if (nhooks < 0)
960 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 importer = PyDict_GetItem(path_importer_cache, p);
963 if (importer != NULL)
964 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* set path_importer_cache[p] to None to avoid recursion */
967 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
968 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 for (j = 0; j < nhooks; j++) {
971 PyObject *hook = PyList_GetItem(path_hooks, j);
972 if (hook == NULL)
973 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100974 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (importer != NULL)
976 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
979 return NULL;
980 }
981 PyErr_Clear();
982 }
983 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400984 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 }
986 if (importer != NULL) {
987 int err = PyDict_SetItem(path_importer_cache, p, importer);
988 Py_DECREF(importer);
989 if (err != 0)
990 return NULL;
991 }
992 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000993}
994
Christian Heimes9cd17752007-11-18 19:35:23 +0000995PyAPI_FUNC(PyObject *)
996PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +0000998
Victor Stinner1e53bba2013-07-16 22:26:05 +0200999 path_importer_cache = PySys_GetObject("path_importer_cache");
1000 path_hooks = PySys_GetObject("path_hooks");
1001 if (path_importer_cache != NULL && path_hooks != NULL) {
1002 importer = get_path_importer(path_importer_cache,
1003 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 }
1005 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1006 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001007}
1008
Nick Coghland5cacbb2015-05-23 22:24:10 +10001009/*[clinic input]
1010_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001011
Nick Coghland5cacbb2015-05-23 22:24:10 +10001012 spec: object
1013 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001014
Nick Coghland5cacbb2015-05-23 22:24:10 +10001015Create an extension module.
1016[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001017
Nick Coghland5cacbb2015-05-23 22:24:10 +10001018static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001019_imp_create_builtin(PyObject *module, PyObject *spec)
1020/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001023 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001024 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001025 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001026
Nick Coghland5cacbb2015-05-23 22:24:10 +10001027 name = PyObject_GetAttrString(spec, "name");
1028 if (name == NULL) {
1029 return NULL;
1030 }
1031
Victor Stinner5eb4f592013-11-14 22:38:52 +01001032 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001033 if (mod || PyErr_Occurred()) {
1034 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001035 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001036 return mod;
1037 }
1038
1039 namestr = PyUnicode_AsUTF8(name);
1040 if (namestr == NULL) {
1041 Py_DECREF(name);
1042 return NULL;
1043 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001046 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001047 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001049 /* Cannot re-init internal module ("sys" or "builtins") */
1050 mod = PyImport_AddModule(namestr);
1051 Py_DECREF(name);
1052 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001055 if (mod == NULL) {
1056 Py_DECREF(name);
1057 return NULL;
1058 }
1059 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1060 Py_DECREF(name);
1061 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1062 } else {
1063 /* Remember pointer to module init function. */
1064 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001065 if (def == NULL) {
1066 Py_DECREF(name);
1067 return NULL;
1068 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001069 def->m_base.m_init = p->initfunc;
Eric Snow93c92f72017-09-13 23:46:04 -07001070 if (_PyImport_FixupExtensionObject(mod, name, name) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001071 Py_DECREF(name);
1072 return NULL;
1073 }
1074 Py_DECREF(name);
1075 return mod;
1076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 }
1078 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001079 Py_DECREF(name);
1080 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001081}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001082
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001083
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001084/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001085
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001086static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001087find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001088{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001089 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001090
Victor Stinner53dc7352011-03-20 01:50:21 +01001091 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 for (p = PyImport_FrozenModules; ; p++) {
1095 if (p->name == NULL)
1096 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001097 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 break;
1099 }
1100 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001101}
1102
Guido van Rossum79f25d91997-04-29 20:08:16 +00001103static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001104get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001105{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001106 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (p == NULL) {
1110 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001111 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 name);
1113 return NULL;
1114 }
1115 if (p->code == NULL) {
1116 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001117 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 name);
1119 return NULL;
1120 }
1121 size = p->size;
1122 if (size < 0)
1123 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001124 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001125}
1126
Brett Cannon8d110132009-03-15 02:20:16 +00001127static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001128is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001129{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001130 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (p == NULL) {
1134 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001135 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 name);
1137 return NULL;
1138 }
Brett Cannon8d110132009-03-15 02:20:16 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (size < 0)
1143 Py_RETURN_TRUE;
1144 else
1145 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001146}
1147
1148
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001149/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001150 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001151 an exception set if the initialization failed.
1152 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001153
1154int
Victor Stinner53dc7352011-03-20 01:50:21 +01001155PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001156{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001157 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001158 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 int ispackage;
1160 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001161
Victor Stinner53dc7352011-03-20 01:50:21 +01001162 p = find_frozen(name);
1163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (p == NULL)
1165 return 0;
1166 if (p->code == NULL) {
1167 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001168 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 name);
1170 return -1;
1171 }
1172 size = p->size;
1173 ispackage = (size < 0);
1174 if (ispackage)
1175 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001176 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (co == NULL)
1178 return -1;
1179 if (!PyCode_Check(co)) {
1180 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001181 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 name);
1183 goto err_return;
1184 }
1185 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001186 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001187 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001189 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (m == NULL)
1191 goto err_return;
1192 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001193 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 goto err_return;
1196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 err = PyDict_SetItemString(d, "__path__", l);
1198 Py_DECREF(l);
1199 if (err != 0)
1200 goto err_return;
1201 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001202 d = module_dict_for_exec(name);
1203 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001204 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001205 }
1206 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (m == NULL)
1208 goto err_return;
1209 Py_DECREF(co);
1210 Py_DECREF(m);
1211 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001212err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 Py_DECREF(co);
1214 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001215}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001216
Victor Stinner53dc7352011-03-20 01:50:21 +01001217int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001218PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001219{
1220 PyObject *nameobj;
1221 int ret;
1222 nameobj = PyUnicode_InternFromString(name);
1223 if (nameobj == NULL)
1224 return -1;
1225 ret = PyImport_ImportFrozenModuleObject(nameobj);
1226 Py_DECREF(nameobj);
1227 return ret;
1228}
1229
Guido van Rossum74e6a111994-08-29 12:54:38 +00001230
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001231/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001232 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001233
Guido van Rossum79f25d91997-04-29 20:08:16 +00001234PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001235PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyObject *pname;
1238 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 pname = PyUnicode_FromString(name);
1241 if (pname == NULL)
1242 return NULL;
1243 result = PyImport_Import(pname);
1244 Py_DECREF(pname);
1245 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001246}
1247
Christian Heimes072c0f12008-01-03 23:01:04 +00001248/* Import a module without blocking
1249 *
1250 * At first it tries to fetch the module from sys.modules. If the module was
1251 * never loaded before it loads it with PyImport_ImportModule() unless another
1252 * thread holds the import lock. In the latter case the function raises an
1253 * ImportError instead of blocking.
1254 *
1255 * Returns the module object with incremented ref count.
1256 */
1257PyObject *
1258PyImport_ImportModuleNoBlock(const char *name)
1259{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001260 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001261}
1262
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001263
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001264/* Remove importlib frames from the traceback,
1265 * except in Verbose mode. */
1266static void
1267remove_importlib_frames(void)
1268{
1269 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001270 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001271 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001272 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001273 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001274 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001275 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001276
1277 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001278 from the traceback. We always trim chunks
1279 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001280
1281 PyErr_Fetch(&exception, &value, &base_tb);
1282 if (!exception || Py_VerboseFlag)
1283 goto done;
1284 if (PyType_IsSubtype((PyTypeObject *) exception,
1285 (PyTypeObject *) PyExc_ImportError))
1286 always_trim = 1;
1287
1288 prev_link = &base_tb;
1289 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001290 while (tb != NULL) {
1291 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1292 PyObject *next = (PyObject *) traceback->tb_next;
1293 PyFrameObject *frame = traceback->tb_frame;
1294 PyCodeObject *code = frame->f_code;
1295 int now_in_importlib;
1296
1297 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001298 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1299 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001300 if (now_in_importlib && !in_importlib) {
1301 /* This is the link to this chunk of importlib tracebacks */
1302 outer_link = prev_link;
1303 }
1304 in_importlib = now_in_importlib;
1305
1306 if (in_importlib &&
1307 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001308 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001309 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001310 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001311 prev_link = outer_link;
1312 }
1313 else {
1314 prev_link = (PyObject **) &traceback->tb_next;
1315 }
1316 tb = next;
1317 }
1318done:
1319 PyErr_Restore(exception, value, base_tb);
1320}
1321
1322
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001323static PyObject *
1324resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001325{
Eric Snowb523f842013-11-22 09:05:39 -07001326 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001327 _Py_IDENTIFIER(__package__);
1328 _Py_IDENTIFIER(__path__);
1329 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001330 _Py_IDENTIFIER(parent);
1331 PyObject *abs_name;
1332 PyObject *package = NULL;
1333 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001334 Py_ssize_t last_dot;
1335 PyObject *base;
1336 int level_up;
1337
1338 if (globals == NULL) {
1339 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1340 goto error;
1341 }
1342 if (!PyDict_Check(globals)) {
1343 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1344 goto error;
1345 }
1346 package = _PyDict_GetItemId(globals, &PyId___package__);
1347 if (package == Py_None) {
1348 package = NULL;
1349 }
1350 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1351
1352 if (package != NULL) {
1353 Py_INCREF(package);
1354 if (!PyUnicode_Check(package)) {
1355 PyErr_SetString(PyExc_TypeError, "package must be a string");
1356 goto error;
1357 }
1358 else if (spec != NULL && spec != Py_None) {
1359 int equal;
1360 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1361 if (parent == NULL) {
1362 goto error;
1363 }
1364
1365 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1366 Py_DECREF(parent);
1367 if (equal < 0) {
1368 goto error;
1369 }
1370 else if (equal == 0) {
1371 if (PyErr_WarnEx(PyExc_ImportWarning,
1372 "__package__ != __spec__.parent", 1) < 0) {
1373 goto error;
1374 }
1375 }
1376 }
1377 }
1378 else if (spec != NULL && spec != Py_None) {
1379 package = _PyObject_GetAttrId(spec, &PyId_parent);
1380 if (package == NULL) {
1381 goto error;
1382 }
1383 else if (!PyUnicode_Check(package)) {
1384 PyErr_SetString(PyExc_TypeError,
1385 "__spec__.parent must be a string");
1386 goto error;
1387 }
1388 }
1389 else {
1390 if (PyErr_WarnEx(PyExc_ImportWarning,
1391 "can't resolve package from __spec__ or __package__, "
1392 "falling back on __name__ and __path__", 1) < 0) {
1393 goto error;
1394 }
1395
1396 package = _PyDict_GetItemId(globals, &PyId___name__);
1397 if (package == NULL) {
1398 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1399 goto error;
1400 }
1401
1402 Py_INCREF(package);
1403 if (!PyUnicode_Check(package)) {
1404 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1405 goto error;
1406 }
1407
1408 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1409 Py_ssize_t dot;
1410
1411 if (PyUnicode_READY(package) < 0) {
1412 goto error;
1413 }
1414
1415 dot = PyUnicode_FindChar(package, '.',
1416 0, PyUnicode_GET_LENGTH(package), -1);
1417 if (dot == -2) {
1418 goto error;
1419 }
1420
1421 if (dot >= 0) {
1422 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1423 if (substr == NULL) {
1424 goto error;
1425 }
1426 Py_SETREF(package, substr);
1427 }
1428 }
1429 }
1430
1431 last_dot = PyUnicode_GET_LENGTH(package);
1432 if (last_dot == 0) {
1433 PyErr_SetString(PyExc_ImportError,
1434 "attempted relative import with no known parent package");
1435 goto error;
1436 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001437
1438 for (level_up = 1; level_up < level; level_up += 1) {
1439 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1440 if (last_dot == -2) {
1441 goto error;
1442 }
1443 else if (last_dot == -1) {
1444 PyErr_SetString(PyExc_ValueError,
1445 "attempted relative import beyond top-level "
1446 "package");
1447 goto error;
1448 }
1449 }
1450
1451 base = PyUnicode_Substring(package, 0, last_dot);
1452 Py_DECREF(package);
1453 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1454 return base;
1455 }
1456
1457 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1458 Py_DECREF(base);
1459 return abs_name;
1460
1461 error:
1462 Py_XDECREF(package);
1463 return NULL;
1464}
1465
1466PyObject *
1467PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1468 PyObject *locals, PyObject *fromlist,
1469 int level)
1470{
Brett Cannonfd074152012-04-14 14:10:13 -04001471 _Py_IDENTIFIER(_find_and_load);
1472 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001473 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001474 PyObject *final_mod = NULL;
1475 PyObject *mod = NULL;
1476 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001477 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001478 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001479
Brett Cannonfd074152012-04-14 14:10:13 -04001480 if (name == NULL) {
1481 PyErr_SetString(PyExc_ValueError, "Empty module name");
1482 goto error;
1483 }
1484
1485 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1486 for added performance. */
1487
1488 if (!PyUnicode_Check(name)) {
1489 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1490 goto error;
1491 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001492 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001493 goto error;
1494 }
1495 if (level < 0) {
1496 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1497 goto error;
1498 }
Brett Cannon849113a2016-01-22 15:25:50 -08001499
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001500 if (level > 0) {
1501 abs_name = resolve_name(name, globals, level);
1502 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001503 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001504 }
1505 else { /* level == 0 */
1506 if (PyUnicode_GET_LENGTH(name) == 0) {
1507 PyErr_SetString(PyExc_ValueError, "Empty module name");
1508 goto error;
1509 }
Brett Cannonfd074152012-04-14 14:10:13 -04001510 abs_name = name;
1511 Py_INCREF(abs_name);
1512 }
1513
Eric Snow93c92f72017-09-13 23:46:04 -07001514 mod = PyDict_GetItem(interp->modules, abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001515 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001516 _Py_IDENTIFIER(__spec__);
1517 _Py_IDENTIFIER(_initializing);
1518 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001519 PyObject *value = NULL;
1520 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001521 int initializing = 0;
1522
Brett Cannonfd074152012-04-14 14:10:13 -04001523 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001524 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001525 __spec__._initializing is true.
1526 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001527 stuffing the new module in sys.modules.
1528 */
Eric Snowb523f842013-11-22 09:05:39 -07001529 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1530 if (spec != NULL) {
1531 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1532 Py_DECREF(spec);
1533 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001534 if (value == NULL)
1535 PyErr_Clear();
1536 else {
1537 initializing = PyObject_IsTrue(value);
1538 Py_DECREF(value);
1539 if (initializing == -1)
1540 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001541 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001542 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1543 &PyId__lock_unlock_module, abs_name,
1544 NULL);
1545 if (value == NULL)
1546 goto error;
1547 Py_DECREF(value);
1548 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001549 }
Brett Cannonfd074152012-04-14 14:10:13 -04001550 }
1551 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001552 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001553 &PyId__find_and_load, abs_name,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001554 interp->import_func, NULL);
Brett Cannonfd074152012-04-14 14:10:13 -04001555 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001556 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001557 }
1558 }
1559
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001560 has_from = 0;
1561 if (fromlist != NULL && fromlist != Py_None) {
1562 has_from = PyObject_IsTrue(fromlist);
1563 if (has_from < 0)
1564 goto error;
1565 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001566 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001567 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1568 if (level == 0 || len > 0) {
1569 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001570
Victor Stinner744c34e2016-05-20 11:36:13 +02001571 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1572 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001573 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001574 }
1575
Victor Stinner744c34e2016-05-20 11:36:13 +02001576 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001577 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001578 final_mod = mod;
1579 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001580 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001581 }
1582
Brett Cannonfd074152012-04-14 14:10:13 -04001583 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001584 PyObject *front = PyUnicode_Substring(name, 0, dot);
1585 if (front == NULL) {
1586 goto error;
1587 }
1588
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001589 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001590 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001591 }
1592 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001593 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001594 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001595 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001596 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001597 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001598 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001599 }
Brett Cannonfd074152012-04-14 14:10:13 -04001600
Eric Snow93c92f72017-09-13 23:46:04 -07001601 final_mod = PyDict_GetItem(interp->modules, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001602 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001603 if (final_mod == NULL) {
1604 PyErr_Format(PyExc_KeyError,
1605 "%R not in sys.modules as expected",
1606 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001607 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001608 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001609 Py_INCREF(final_mod);
Brett Cannonfd074152012-04-14 14:10:13 -04001610 }
1611 }
1612 else {
1613 final_mod = mod;
1614 Py_INCREF(mod);
1615 }
1616 }
1617 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001618 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001619 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001620 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001621 NULL);
1622 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001623
Brett Cannonfd074152012-04-14 14:10:13 -04001624 error:
1625 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001626 Py_XDECREF(mod);
1627 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001628 if (final_mod == NULL)
1629 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001630 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001631}
1632
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001633PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001634PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001635 PyObject *fromlist, int level)
1636{
1637 PyObject *nameobj, *mod;
1638 nameobj = PyUnicode_FromString(name);
1639 if (nameobj == NULL)
1640 return NULL;
1641 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1642 fromlist, level);
1643 Py_DECREF(nameobj);
1644 return mod;
1645}
1646
1647
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001648/* Re-import a module of any kind and return its module object, WITH
1649 INCREMENTED REFERENCE COUNT */
1650
Guido van Rossum79f25d91997-04-29 20:08:16 +00001651PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001652PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001653{
Brett Cannon62228db2012-04-29 14:38:11 -04001654 _Py_IDENTIFIER(reload);
1655 PyObject *reloaded_module = NULL;
Eric Snow93c92f72017-09-13 23:46:04 -07001656 PyObject *modules = PyImport_GetModuleDict();
1657 PyObject *imp = PyDict_GetItemString(modules, "imp");
Brett Cannon62228db2012-04-29 14:38:11 -04001658 if (imp == NULL) {
1659 imp = PyImport_ImportModule("imp");
1660 if (imp == NULL) {
1661 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 }
Brett Cannon62228db2012-04-29 14:38:11 -04001664 else {
1665 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001667
Victor Stinner55ba38a2016-12-09 16:09:30 +01001668 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001669 Py_DECREF(imp);
1670 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001671}
1672
1673
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001674/* Higher-level import emulator which emulates the "import" statement
1675 more accurately -- it invokes the __import__() function from the
1676 builtins of the current globals. This means that the import is
1677 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001678 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001679 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001680 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001681 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001682
1683PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001684PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 static PyObject *silly_list = NULL;
1687 static PyObject *builtins_str = NULL;
1688 static PyObject *import_str = NULL;
1689 PyObject *globals = NULL;
1690 PyObject *import = NULL;
1691 PyObject *builtins = NULL;
Eric Snow93c92f72017-09-13 23:46:04 -07001692 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 /* Initialize constant string objects */
1696 if (silly_list == NULL) {
1697 import_str = PyUnicode_InternFromString("__import__");
1698 if (import_str == NULL)
1699 return NULL;
1700 builtins_str = PyUnicode_InternFromString("__builtins__");
1701 if (builtins_str == NULL)
1702 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001703 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (silly_list == NULL)
1705 return NULL;
1706 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* Get the builtins from current globals */
1709 globals = PyEval_GetGlobals();
1710 if (globals != NULL) {
1711 Py_INCREF(globals);
1712 builtins = PyObject_GetItem(globals, builtins_str);
1713 if (builtins == NULL)
1714 goto err;
1715 }
1716 else {
1717 /* No globals -- use standard builtins, and fake globals */
1718 builtins = PyImport_ImportModuleLevel("builtins",
1719 NULL, NULL, NULL, 0);
1720 if (builtins == NULL)
1721 return NULL;
1722 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1723 if (globals == NULL)
1724 goto err;
1725 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* Get the __import__ function from the builtins */
1728 if (PyDict_Check(builtins)) {
1729 import = PyObject_GetItem(builtins, import_str);
1730 if (import == NULL)
1731 PyErr_SetObject(PyExc_KeyError, import_str);
1732 }
1733 else
1734 import = PyObject_GetAttr(builtins, import_str);
1735 if (import == NULL)
1736 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001739 Always use absolute import here.
1740 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1742 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001743 if (r == NULL)
1744 goto err;
1745 Py_DECREF(r);
1746
Eric Snow93c92f72017-09-13 23:46:04 -07001747 modules = PyImport_GetModuleDict();
1748 r = PyDict_GetItemWithError(modules, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001749 if (r != NULL) {
Brett Cannonbc2eff32010-09-19 21:39:02 +00001750 Py_INCREF(r);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001751 }
1752 else if (!PyErr_Occurred()) {
1753 PyErr_SetObject(PyExc_KeyError, module_name);
1754 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001755
1756 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_XDECREF(globals);
1758 Py_XDECREF(builtins);
1759 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001762}
1763
Brett Cannon4caa61d2014-01-09 19:03:32 -05001764/*[clinic input]
1765_imp.extension_suffixes
1766
1767Returns the list of file suffixes used to identify extension modules.
1768[clinic start generated code]*/
1769
Brett Cannon4caa61d2014-01-09 19:03:32 -05001770static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001771_imp_extension_suffixes_impl(PyObject *module)
1772/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001775 const char *suffix;
1776 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 list = PyList_New(0);
1779 if (list == NULL)
1780 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001781#ifdef HAVE_DYNAMIC_LOADING
1782 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1783 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (item == NULL) {
1785 Py_DECREF(list);
1786 return NULL;
1787 }
1788 if (PyList_Append(list, item) < 0) {
1789 Py_DECREF(list);
1790 Py_DECREF(item);
1791 return NULL;
1792 }
1793 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001794 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 }
Brett Cannon2657df42012-05-04 15:20:40 -04001796#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001798}
1799
Brett Cannon4caa61d2014-01-09 19:03:32 -05001800/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001801_imp.init_frozen
1802
1803 name: unicode
1804 /
1805
1806Initializes a frozen module.
1807[clinic start generated code]*/
1808
Brett Cannon4caa61d2014-01-09 19:03:32 -05001809static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001810_imp_init_frozen_impl(PyObject *module, PyObject *name)
1811/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 int ret;
1814 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001815
Victor Stinner53dc7352011-03-20 01:50:21 +01001816 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (ret < 0)
1818 return NULL;
1819 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001820 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001822 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 Py_XINCREF(m);
1824 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001825}
1826
Brett Cannon4caa61d2014-01-09 19:03:32 -05001827/*[clinic input]
1828_imp.get_frozen_object
1829
1830 name: unicode
1831 /
1832
1833Create a code object for a frozen module.
1834[clinic start generated code]*/
1835
Brett Cannon4caa61d2014-01-09 19:03:32 -05001836static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001837_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1838/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001841}
1842
Brett Cannon4caa61d2014-01-09 19:03:32 -05001843/*[clinic input]
1844_imp.is_frozen_package
1845
1846 name: unicode
1847 /
1848
1849Returns True if the module name is of a frozen package.
1850[clinic start generated code]*/
1851
Brett Cannon4caa61d2014-01-09 19:03:32 -05001852static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001853_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1854/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001857}
1858
Brett Cannon4caa61d2014-01-09 19:03:32 -05001859/*[clinic input]
1860_imp.is_builtin
1861
1862 name: unicode
1863 /
1864
1865Returns True if the module name corresponds to a built-in module.
1866[clinic start generated code]*/
1867
Guido van Rossum79f25d91997-04-29 20:08:16 +00001868static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001869_imp_is_builtin_impl(PyObject *module, PyObject *name)
1870/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001871{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001872 return PyLong_FromLong(is_builtin(name));
1873}
1874
1875/*[clinic input]
1876_imp.is_frozen
1877
1878 name: unicode
1879 /
1880
1881Returns True if the module name corresponds to a frozen module.
1882[clinic start generated code]*/
1883
Brett Cannon4caa61d2014-01-09 19:03:32 -05001884static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001885_imp_is_frozen_impl(PyObject *module, PyObject *name)
1886/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001887{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001888 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 p = find_frozen(name);
1891 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001892}
1893
Larry Hastings1df0b352015-08-24 19:53:56 -07001894/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1895static int
1896exec_builtin_or_dynamic(PyObject *mod) {
1897 PyModuleDef *def;
1898 void *state;
1899
1900 if (!PyModule_Check(mod)) {
1901 return 0;
1902 }
1903
1904 def = PyModule_GetDef(mod);
1905 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001906 return 0;
1907 }
Brett Cannon52794db2016-09-07 17:00:43 -07001908
Larry Hastings1df0b352015-08-24 19:53:56 -07001909 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001910 if (state) {
1911 /* Already initialized; skip reload */
1912 return 0;
1913 }
Brett Cannon52794db2016-09-07 17:00:43 -07001914
Larry Hastings1df0b352015-08-24 19:53:56 -07001915 return PyModule_ExecDef(mod, def);
1916}
1917
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001918#ifdef HAVE_DYNAMIC_LOADING
1919
Brett Cannon4caa61d2014-01-09 19:03:32 -05001920/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10001921_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05001922
Nick Coghland5cacbb2015-05-23 22:24:10 +10001923 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05001924 file: object = NULL
1925 /
1926
Nick Coghland5cacbb2015-05-23 22:24:10 +10001927Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05001928[clinic start generated code]*/
1929
Brett Cannon4caa61d2014-01-09 19:03:32 -05001930static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001931_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
1932/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001933{
Nick Coghland5cacbb2015-05-23 22:24:10 +10001934 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001935 FILE *fp;
1936
Nick Coghland5cacbb2015-05-23 22:24:10 +10001937 name = PyObject_GetAttrString(spec, "name");
1938 if (name == NULL) {
1939 return NULL;
1940 }
1941
1942 path = PyObject_GetAttrString(spec, "origin");
1943 if (path == NULL) {
1944 Py_DECREF(name);
1945 return NULL;
1946 }
1947
1948 mod = _PyImport_FindExtensionObject(name, path);
1949 if (mod != NULL) {
1950 Py_DECREF(name);
1951 Py_DECREF(path);
1952 Py_INCREF(mod);
1953 return mod;
1954 }
1955
Brett Cannon4caa61d2014-01-09 19:03:32 -05001956 if (file != NULL) {
1957 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001958 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001959 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001960 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001962 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001964 else
1965 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001966
1967 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
1968
1969 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001970 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (fp)
1972 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001973 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001974}
1975
Nick Coghland5cacbb2015-05-23 22:24:10 +10001976/*[clinic input]
1977_imp.exec_dynamic -> int
1978
1979 mod: object
1980 /
1981
1982Initialize an extension module.
1983[clinic start generated code]*/
1984
1985static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001986_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
1987/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10001988{
Larry Hastings1df0b352015-08-24 19:53:56 -07001989 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001990}
1991
1992
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001993#endif /* HAVE_DYNAMIC_LOADING */
1994
Larry Hastings7726ac92014-01-31 22:03:12 -08001995/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07001996_imp.exec_builtin -> int
1997
1998 mod: object
1999 /
2000
2001Initialize a built-in module.
2002[clinic start generated code]*/
2003
2004static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002005_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2006/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002007{
2008 return exec_builtin_or_dynamic(mod);
2009}
2010
Barry Warsaw28a691b2010-04-17 00:19:56 +00002011
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002012PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002013"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002014
Guido van Rossum79f25d91997-04-29 20:08:16 +00002015static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002016 _IMP_EXTENSION_SUFFIXES_METHODDEF
2017 _IMP_LOCK_HELD_METHODDEF
2018 _IMP_ACQUIRE_LOCK_METHODDEF
2019 _IMP_RELEASE_LOCK_METHODDEF
2020 _IMP_GET_FROZEN_OBJECT_METHODDEF
2021 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002022 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002023 _IMP_INIT_FROZEN_METHODDEF
2024 _IMP_IS_BUILTIN_METHODDEF
2025 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002026 _IMP_CREATE_DYNAMIC_METHODDEF
2027 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002028 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002029 _IMP__FIX_CO_FILENAME_METHODDEF
2030 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002031};
2032
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002033
Martin v. Löwis1a214512008-06-11 05:26:20 +00002034static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002036 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 doc_imp,
2038 0,
2039 imp_methods,
2040 NULL,
2041 NULL,
2042 NULL,
2043 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002044};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002045
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002046PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002047PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 m = PyModule_Create(&impmodule);
2052 if (m == NULL)
2053 goto failure;
2054 d = PyModule_GetDict(m);
2055 if (d == NULL)
2056 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002059 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 Py_XDECREF(m);
2061 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002062}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002063
2064
Guido van Rossumb18618d2000-05-03 23:44:39 +00002065/* API for embedding applications that want to add their own entries
2066 to the table of built-in modules. This should normally be called
2067 *before* Py_Initialize(). When the table resize fails, -1 is
2068 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002069
2070 After a similar function by Just van Rossum. */
2071
2072int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002073PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 static struct _inittab *our_copy = NULL;
2076 struct _inittab *p;
2077 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 /* Count the number of entries in both tables */
2080 for (n = 0; newtab[n].name != NULL; n++)
2081 ;
2082 if (n == 0)
2083 return 0; /* Nothing to do */
2084 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2085 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 /* Allocate new memory for the combined table */
2088 p = our_copy;
2089 PyMem_RESIZE(p, struct _inittab, i+n+1);
2090 if (p == NULL)
2091 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 /* Copy the tables into the new memory */
2094 if (our_copy != PyImport_Inittab)
2095 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2096 PyImport_Inittab = our_copy = p;
2097 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002100}
2101
2102/* Shorthand to add a single entry given a name and a function */
2103
2104int
Brett Cannona826f322009-04-02 03:41:46 +00002105PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002110
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002111 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002115}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002116
2117#ifdef __cplusplus
2118}
2119#endif