blob: c3b9e12572a730b8d7c12934c8ebdc42bcef8723 [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 */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020011#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000014
Guido van Rossum55a83382000-09-20 20:31:38 +000015#ifdef HAVE_FCNTL_H
16#include <fcntl.h>
17#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000019extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000021
Barry Warsaw28a691b2010-04-17 00:19:56 +000022#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000023
Victor Stinner95872862011-03-07 18:20:56 +010024/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000025static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Guido van Rossum771c6c81997-10-31 18:37:24 +000027/* This table is defined in config.c: */
28extern struct _inittab _PyImport_Inittab[];
29
30struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000031
Victor Stinnerd0296212011-03-14 14:04:10 -040032static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033
Brett Cannon4caa61d2014-01-09 19:03:32 -050034/*[clinic input]
Brett Cannonfd4d0502014-05-30 11:21:14 -040035output preset file
Brett Cannon4caa61d2014-01-09 19:03:32 -050036module _imp
37[clinic start generated code]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040038/*[clinic end generated code: output=da39a3ee5e6b4b0d input=98c38221164579d5]*/
39
40#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050041
42/*[python input]
43class fs_unicode_converter(CConverter):
44 type = 'PyObject *'
45 converter = 'PyUnicode_FSDecoder'
46
47[python start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080048/*[python end generated code: output=da39a3ee5e6b4b0d input=9d6786230166006e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050049
Guido van Rossum1ae940a1995-01-02 19:04:15 +000050/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051
52void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000053_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020055 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040056 initstr = PyUnicode_InternFromString("__init__");
57 if (initstr == NULL)
58 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020059 interp->builtins_copy = PyDict_Copy(interp->builtins);
60 if (interp->builtins_copy == NULL)
61 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062}
63
Guido van Rossum25ce5661997-08-02 03:10:38 +000064void
Just van Rossum52e14d62002-12-30 22:08:05 +000065_PyImportHooks_Init(void)
66{
Brett Cannonfd074152012-04-14 14:10:13 -040067 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000069
Brett Cannonfd074152012-04-14 14:10:13 -040070 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 v = PyList_New(0);
72 if (v == NULL)
73 goto error;
74 err = PySys_SetObject("meta_path", v);
75 Py_DECREF(v);
76 if (err)
77 goto error;
78 v = PyDict_New();
79 if (v == NULL)
80 goto error;
81 err = PySys_SetObject("path_importer_cache", v);
82 Py_DECREF(v);
83 if (err)
84 goto error;
85 path_hooks = PyList_New(0);
86 if (path_hooks == NULL)
87 goto error;
88 err = PySys_SetObject("path_hooks", path_hooks);
89 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000090 error:
Brett Cannonfd074152012-04-14 14:10:13 -040091 PyErr_Print();
92 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020093 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 }
Brett Cannonfd074152012-04-14 14:10:13 -040095 Py_DECREF(path_hooks);
96}
97
98void
99_PyImportZip_Init(void)
100{
101 PyObject *path_hooks, *zimpimport;
102 int err = 0;
103
104 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200105 if (path_hooks == NULL) {
106 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400107 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200108 }
Brett Cannonfd074152012-04-14 14:10:13 -0400109
110 if (Py_VerboseFlag)
111 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 zimpimport = PyImport_ImportModule("zipimport");
114 if (zimpimport == NULL) {
115 PyErr_Clear(); /* No zip import module -- okay */
116 if (Py_VerboseFlag)
117 PySys_WriteStderr("# can't import zipimport\n");
118 }
119 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200120 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200121 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
122 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 Py_DECREF(zimpimport);
124 if (zipimporter == NULL) {
125 PyErr_Clear(); /* No zipimporter object -- okay */
126 if (Py_VerboseFlag)
127 PySys_WriteStderr(
128 "# can't import zipimport.zipimporter\n");
129 }
130 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400131 /* sys.path_hooks.insert(0, zipimporter) */
132 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400134 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (Py_VerboseFlag)
138 PySys_WriteStderr(
139 "# installed zipimport hook\n");
140 }
141 }
Brett Cannonfd074152012-04-14 14:10:13 -0400142
143 return;
144
145 error:
146 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400147 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000148}
149
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000150/* Locking primitives to prevent parallel imports of the same module
151 in different threads to return with a partially loaded module.
152 These calls are serialized by the global interpreter lock. */
153
154#ifdef WITH_THREAD
155
Guido van Rossum49b56061998-10-01 20:42:43 +0000156#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000157
Guido van Rossum65d5b571998-12-21 19:32:43 +0000158static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000159static long import_lock_thread = -1;
160static int import_lock_level = 0;
161
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000162void
163_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 long me = PyThread_get_thread_ident();
166 if (me == -1)
167 return; /* Too bad */
168 if (import_lock == NULL) {
169 import_lock = PyThread_allocate_lock();
170 if (import_lock == NULL)
171 return; /* Nothing much we can do. */
172 }
173 if (import_lock_thread == me) {
174 import_lock_level++;
175 return;
176 }
177 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
178 {
179 PyThreadState *tstate = PyEval_SaveThread();
180 PyThread_acquire_lock(import_lock, 1);
181 PyEval_RestoreThread(tstate);
182 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100183 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 import_lock_thread = me;
185 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000186}
187
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000188int
189_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 long me = PyThread_get_thread_ident();
192 if (me == -1 || import_lock == NULL)
193 return 0; /* Too bad */
194 if (import_lock_thread != me)
195 return -1;
196 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100197 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 if (import_lock_level == 0) {
199 import_lock_thread = -1;
200 PyThread_release_lock(import_lock);
201 }
202 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000203}
204
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000205/* This function is called from PyOS_AfterFork to ensure that newly
206 created child processes do not share locks with the parent.
207 We now acquire the import lock around fork() calls but on some platforms
208 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000209
210void
211_PyImport_ReInitLock(void)
212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (import_lock != NULL)
214 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000215 if (import_lock_level > 1) {
216 /* Forked as a side effect of import */
217 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500218 /* The following could fail if the lock is already held, but forking as
219 a side-effect of an import is a) rare, b) nuts, and c) difficult to
220 do thanks to the lock only being held when doing individual module
221 locks per import. */
222 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000223 import_lock_thread = me;
224 import_lock_level--;
225 } else {
226 import_lock_thread = -1;
227 import_lock_level = 0;
228 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000229}
230
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000231#endif
232
Brett Cannon4caa61d2014-01-09 19:03:32 -0500233/*[clinic input]
234_imp.lock_held
235
236Return True if the import lock is currently held, else False.
237
238On platforms without threads, return False.
239[clinic start generated code]*/
240
Brett Cannon4caa61d2014-01-09 19:03:32 -0500241static PyObject *
242_imp_lock_held_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400243/*[clinic end generated code: output=d7a8cc3a5169081a input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000244{
Tim Peters69232342001-08-30 05:16:13 +0000245#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000247#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000249#endif
250}
251
Brett Cannon4caa61d2014-01-09 19:03:32 -0500252/*[clinic input]
253_imp.acquire_lock
254
255Acquires the interpreter's import lock for the current thread.
256
257This lock should be used by import hooks to ensure thread-safety when importing
258modules. On platforms without threads, this function does nothing.
259[clinic start generated code]*/
260
Brett Cannon4caa61d2014-01-09 19:03:32 -0500261static PyObject *
262_imp_acquire_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400263/*[clinic end generated code: output=cc143b1d16422cae input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000264{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000267#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 Py_INCREF(Py_None);
269 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270}
271
Brett Cannon4caa61d2014-01-09 19:03:32 -0500272/*[clinic input]
273_imp.release_lock
274
275Release the interpreter's import lock.
276
277On platforms without threads, this function does nothing.
278[clinic start generated code]*/
279
Brett Cannon4caa61d2014-01-09 19:03:32 -0500280static PyObject *
281_imp_release_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400282/*[clinic end generated code: output=74d28e38ebe2b224 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000283{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000284#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (_PyImport_ReleaseLock() < 0) {
286 PyErr_SetString(PyExc_RuntimeError,
287 "not holding the import lock");
288 return NULL;
289 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000290#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 Py_INCREF(Py_None);
292 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000293}
294
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100295void
296_PyImport_Fini(void)
297{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200298 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100299#ifdef WITH_THREAD
300 if (import_lock != NULL) {
301 PyThread_free_lock(import_lock);
302 import_lock = NULL;
303 }
304#endif
305}
306
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307/* Helper for sys */
308
309PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000310PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 PyInterpreterState *interp = PyThreadState_GET()->interp;
313 if (interp->modules == NULL)
314 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
315 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316}
317
Guido van Rossum3f5da241990-12-20 15:06:42 +0000318
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000319/* List of names to clear in sys */
320static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 "path", "argv", "ps1", "ps2",
322 "last_type", "last_value", "last_traceback",
323 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200324 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 /* misc stuff */
326 "flags", "float_info",
327 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000328};
329
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000330static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 "stdin", "__stdin__",
332 "stdout", "__stdout__",
333 "stderr", "__stderr__",
334 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000335};
336
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000337/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000338
Guido van Rossum3f5da241990-12-20 15:06:42 +0000339void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000340PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000341{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200342 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 PyObject *key, *value, *dict;
344 PyInterpreterState *interp = PyThreadState_GET()->interp;
345 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200346 PyObject *weaklist = NULL;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200347 char **p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (modules == NULL)
350 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* Delete some special variables first. These are common
353 places where user values hide and people complain when their
354 destructors fail. Since the modules containing them are
355 deleted *last* of all, they would come too late in the normal
356 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000357
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200358 /* XXX Perhaps these precautions are obsolete. Who knows? */
359
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200360 if (Py_VerboseFlag)
361 PySys_WriteStderr("# clear builtins._\n");
362 PyDict_SetItemString(interp->builtins, "_", Py_None);
363
364 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200366 PySys_WriteStderr("# clear sys.%s\n", *p);
367 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200369 for (p = sys_files; *p != NULL; p+=2) {
370 if (Py_VerboseFlag)
371 PySys_WriteStderr("# restore sys.%s\n", *p);
372 value = PyDict_GetItemString(interp->sysdict, *(p+1));
373 if (value == NULL)
374 value = Py_None;
375 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000377
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200378 /* We prepare a list which will receive (name, weakref) tuples of
379 modules when they are removed from sys.modules. The name is used
380 for diagnosis messages (in verbose mode), while the weakref helps
381 detect those modules which have been held alive. */
382 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200383 if (weaklist == NULL)
384 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200385
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200386#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200387 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200388 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
389 if (name && wr) { \
390 PyObject *tup = PyTuple_Pack(2, name, wr); \
391 PyList_Append(weaklist, tup); \
392 Py_XDECREF(tup); \
393 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200394 Py_XDECREF(wr); \
395 if (PyErr_Occurred()) \
396 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000398
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200399 /* Remove all modules from sys.modules, hoping that garbage collection
400 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 pos = 0;
402 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200403 if (PyModule_Check(value)) {
404 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200405 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200406 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 PyDict_SetItem(modules, key, Py_None);
408 }
409 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000410
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200411 /* Clear the modules dict. */
412 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200413 /* Restore the original builtins dict, to ensure that any
414 user data gets cleared. */
415 dict = PyDict_Copy(interp->builtins);
416 if (dict == NULL)
417 PyErr_Clear();
418 PyDict_Clear(interp->builtins);
419 if (PyDict_Update(interp->builtins, interp->builtins_copy))
420 PyErr_Clear();
421 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200422 /* Clear module dict copies stored in the interpreter state */
423 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200424 /* Collect references */
425 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200426 /* Dump GC stats before it's too late, since it uses the warnings
427 machinery. */
428 _PyGC_DumpShutdownStats();
429
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200430 /* Now, if there are any modules left alive, clear their globals to
431 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200432 up here, since they are kept alive in the interpreter state.
433
434 The special treatment of "builtins" here is because even
435 when it's not referenced as a module, its dictionary is
436 referenced by almost every module's __builtins__. Since
437 deleting a module clears its dictionary (even if there are
438 references left to it), we need to delete the "builtins"
439 module last. Likewise, we don't delete sys until the very
440 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200441 if (weaklist != NULL) {
442 Py_ssize_t i, n;
443 n = PyList_GET_SIZE(weaklist);
444 for (i = 0; i < n; i++) {
445 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200446 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200447 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
448 if (mod == Py_None)
449 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200451 dict = PyModule_GetDict(mod);
452 if (dict == interp->builtins || dict == interp->sysdict)
453 continue;
454 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200455 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200456 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457 _PyModule_Clear(mod);
458 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200459 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200460 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000462
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200463 /* Next, delete sys and builtins (in that order) */
464 if (Py_VerboseFlag)
465 PySys_FormatStderr("# cleanup[3] wiping sys\n");
466 _PyModule_ClearDict(interp->sysdict);
467 if (Py_VerboseFlag)
468 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
469 _PyModule_ClearDict(interp->builtins);
470
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200471 /* Clear and delete the modules directory. Actual modules will
472 still be there only if imported during the execution of some
473 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 interp->modules = NULL;
475 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200476
477 /* Once more */
478 _PyGC_CollectNoFail();
479
480#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000481}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000482
483
Barry Warsaw28a691b2010-04-17 00:19:56 +0000484/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000485
486long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000487PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000488{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200489 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400490 PyInterpreterState *interp = PyThreadState_Get()->interp;
491 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
492 "_RAW_MAGIC_NUMBER");
493 if (pyc_magic == NULL)
494 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200495 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700496 Py_DECREF(pyc_magic);
497 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000498}
499
500
Brett Cannon3adc7b72012-07-09 14:22:12 -0400501extern const char * _PySys_ImplCacheTag;
502
Barry Warsaw28a691b2010-04-17 00:19:56 +0000503const char *
504PyImport_GetMagicTag(void)
505{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400506 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000507}
508
Brett Cannon98979b82012-07-02 15:13:11 -0400509
Guido van Rossum25ce5661997-08-02 03:10:38 +0000510/* Magic for extension modules (built-in as well as dynamically
511 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200512 once, we keep a static dictionary 'extensions' keyed by the tuple
513 (module name, module name) (for built-in modules) or by
514 (filename, module name) (for dynamically loaded modules), containing these
515 modules. A copy of the module's dictionary is stored by calling
516 _PyImport_FixupExtensionObject() immediately after the module initialization
517 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100518 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000519
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000520 Modules which do support multiple initialization set their m_size
521 field to a non-negative number (indicating the size of the
522 module-specific state). They are still recorded in the extensions
523 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000524*/
525
526int
Victor Stinner95872862011-03-07 18:20:56 +0100527_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
528 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000529{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500530 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500532 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (extensions == NULL) {
534 extensions = PyDict_New();
535 if (extensions == NULL)
536 return -1;
537 }
538 if (mod == NULL || !PyModule_Check(mod)) {
539 PyErr_BadInternalCall();
540 return -1;
541 }
542 def = PyModule_GetDef(mod);
543 if (!def) {
544 PyErr_BadInternalCall();
545 return -1;
546 }
547 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100548 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return -1;
550 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100551 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return -1;
553 }
554 if (def->m_size == -1) {
555 if (def->m_base.m_copy) {
556 /* Somebody already imported the module,
557 likely under a different name.
558 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200559 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 }
561 dict = PyModule_GetDict(mod);
562 if (dict == NULL)
563 return -1;
564 def->m_base.m_copy = PyDict_Copy(dict);
565 if (def->m_base.m_copy == NULL)
566 return -1;
567 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500568 key = PyTuple_Pack(2, filename, name);
569 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200570 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500571 res = PyDict_SetItem(extensions, key, (PyObject *)def);
572 Py_DECREF(key);
573 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200574 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576}
577
Victor Stinner49d3f252010-10-17 01:24:53 +0000578int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300579_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000580{
581 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100582 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100583 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100584 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000585 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100586 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
587 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000588 return res;
589}
590
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100592_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500594 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyModuleDef* def;
596 if (extensions == NULL)
597 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500598 key = PyTuple_Pack(2, filename, name);
599 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200600 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500601 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
602 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (def == NULL)
604 return NULL;
605 if (def->m_size == -1) {
606 /* Module does not support repeated initialization */
607 if (def->m_base.m_copy == NULL)
608 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100609 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (mod == NULL)
611 return NULL;
612 mdict = PyModule_GetDict(mod);
613 if (mdict == NULL)
614 return NULL;
615 if (PyDict_Update(mdict, def->m_base.m_copy))
616 return NULL;
617 }
618 else {
619 if (def->m_base.m_init == NULL)
620 return NULL;
621 mod = def->m_base.m_init();
622 if (mod == NULL)
623 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200624 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
625 Py_DECREF(mod);
626 return NULL;
627 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 Py_DECREF(mod);
629 }
630 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100631 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 Py_DECREF(mod);
633 return NULL;
634 }
635 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100636 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 name, filename);
638 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000639
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000640}
641
Victor Stinner49d3f252010-10-17 01:24:53 +0000642PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000643_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000644{
Victor Stinner95872862011-03-07 18:20:56 +0100645 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100646 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100647 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000648 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100649 res = _PyImport_FindExtensionObject(nameobj, nameobj);
650 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000651 return res;
652}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000653
654/* Get the module object corresponding to a module name.
655 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000656 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000657 Because the former action is most common, THIS DOES NOT RETURN A
658 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000659
Guido van Rossum79f25d91997-04-29 20:08:16 +0000660PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000661PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyObject *modules = PyImport_GetModuleDict();
664 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000665
Victor Stinner27ee0892011-03-04 12:57:09 +0000666 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyModule_Check(m))
668 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000669 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (m == NULL)
671 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000672 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 Py_DECREF(m);
674 return NULL;
675 }
676 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000679}
680
Victor Stinner27ee0892011-03-04 12:57:09 +0000681PyObject *
682PyImport_AddModule(const char *name)
683{
684 PyObject *nameobj, *module;
685 nameobj = PyUnicode_FromString(name);
686 if (nameobj == NULL)
687 return NULL;
688 module = PyImport_AddModuleObject(nameobj);
689 Py_DECREF(nameobj);
690 return module;
691}
692
693
Tim Peters1cd70172004-08-02 03:52:12 +0000694/* Remove name from sys.modules, if it's there. */
695static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000696remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000699 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000701 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 Py_FatalError("import: deleting existing key in"
703 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000704}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000705
Christian Heimes3b06e532008-01-07 20:12:44 +0000706
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000707/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000708 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
709 * removed from sys.modules, to avoid leaving damaged module objects
710 * in sys.modules. The caller may wish to restore the original
711 * module object (if any) in this case; PyImport_ReloadModule is an
712 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000713 *
714 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
715 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000716 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000717PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300718PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return PyImport_ExecCodeModuleWithPathnames(
721 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000722}
723
724PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300725PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 return PyImport_ExecCodeModuleWithPathnames(
728 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000729}
730
731PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300732PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
733 const char *pathname,
734 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000735{
Victor Stinner27ee0892011-03-04 12:57:09 +0000736 PyObject *m = NULL;
737 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
738
739 nameobj = PyUnicode_FromString(name);
740 if (nameobj == NULL)
741 return NULL;
742
Victor Stinner27ee0892011-03-04 12:57:09 +0000743 if (cpathname != NULL) {
744 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
745 if (cpathobj == NULL)
746 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400747 }
748 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000749 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400750
751 if (pathname != NULL) {
752 pathobj = PyUnicode_DecodeFSDefault(pathname);
753 if (pathobj == NULL)
754 goto error;
755 }
756 else if (cpathobj != NULL) {
757 PyInterpreterState *interp = PyThreadState_GET()->interp;
758 _Py_IDENTIFIER(_get_sourcefile);
759
760 if (interp == NULL) {
761 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
762 "no interpreter!");
763 }
764
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -0700765 pathobj = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannona6473f92012-07-13 13:57:03 -0400766 &PyId__get_sourcefile, cpathobj,
767 NULL);
768 if (pathobj == NULL)
769 PyErr_Clear();
770 }
771 else
772 pathobj = NULL;
773
Victor Stinner27ee0892011-03-04 12:57:09 +0000774 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
775error:
776 Py_DECREF(nameobj);
777 Py_XDECREF(pathobj);
778 Py_XDECREF(cpathobj);
779 return m;
780}
781
Brett Cannon18fc4e72014-04-04 10:01:46 -0400782static PyObject *
783module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000784{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400785 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000786
Victor Stinner27ee0892011-03-04 12:57:09 +0000787 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (m == NULL)
789 return NULL;
790 /* If the module is being reloaded, we get the old module back
791 and re-use its dict to exec the new code. */
792 d = PyModule_GetDict(m);
793 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
794 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400795 PyEval_GetBuiltins()) != 0) {
796 remove_module(name);
797 return NULL;
798 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400800
Eric Snow08197a42014-05-12 17:54:55 -0600801 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400802}
803
804static PyObject *
805exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
806{
807 PyObject *modules = PyImport_GetModuleDict();
808 PyObject *v, *m;
809
810 v = PyEval_EvalCode(code_object, module_dict, module_dict);
811 if (v == NULL) {
812 remove_module(name);
813 return NULL;
814 }
815 Py_DECREF(v);
816
817 if ((m = PyDict_GetItem(modules, name)) == NULL) {
818 PyErr_Format(PyExc_ImportError,
819 "Loaded module %R not found in sys.modules",
820 name);
821 return NULL;
822 }
823
824 Py_INCREF(m);
825
826 return m;
827}
828
829PyObject*
830PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
831 PyObject *cpathname)
832{
Eric Snow08197a42014-05-12 17:54:55 -0600833 PyObject *d, *res;
834 PyInterpreterState *interp = PyThreadState_GET()->interp;
835 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400836
837 d = module_dict_for_exec(name);
838 if (d == NULL) {
839 return NULL;
840 }
841
Eric Snow08197a42014-05-12 17:54:55 -0600842 if (pathname == NULL) {
843 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 }
Eric Snow08197a42014-05-12 17:54:55 -0600845 res = _PyObject_CallMethodIdObjArgs(interp->importlib,
846 &PyId__fix_up_module,
847 d, name, pathname, cpathname, NULL);
848 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600849 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600850 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 }
Eric Snow08197a42014-05-12 17:54:55 -0600852 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000853}
854
855
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000856static void
857update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject *constants, *tmp;
860 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (PyUnicode_Compare(co->co_filename, oldname))
863 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 tmp = co->co_filename;
866 co->co_filename = newname;
867 Py_INCREF(co->co_filename);
868 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 constants = co->co_consts;
871 n = PyTuple_GET_SIZE(constants);
872 for (i = 0; i < n; i++) {
873 tmp = PyTuple_GET_ITEM(constants, i);
874 if (PyCode_Check(tmp))
875 update_code_filenames((PyCodeObject *)tmp,
876 oldname, newname);
877 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000878}
879
Victor Stinner2f42ae52011-03-20 00:41:24 +0100880static void
881update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000882{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100883 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000884
Victor Stinner2f42ae52011-03-20 00:41:24 +0100885 if (PyUnicode_Compare(co->co_filename, newname) == 0)
886 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 oldname = co->co_filename;
889 Py_INCREF(oldname);
890 update_code_filenames(co, oldname, newname);
891 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000892}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000893
Brett Cannon4caa61d2014-01-09 19:03:32 -0500894/*[clinic input]
895_imp._fix_co_filename
896
897 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
898 Code object to change.
899
900 path: unicode
901 File path to use.
902 /
903
904Changes code.co_filename to specify the passed-in file path.
905[clinic start generated code]*/
906
Brett Cannon4caa61d2014-01-09 19:03:32 -0500907static PyObject *
908_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400909/*[clinic end generated code: output=7afe5ba6b9d383e4 input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700910
Brett Cannon4caa61d2014-01-09 19:03:32 -0500911{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500912 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700913
914 Py_RETURN_NONE;
915}
916
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000917
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000918/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700919static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000920
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000921
922/* Helper to test for built-in module */
923
924static int
Victor Stinner95872862011-03-07 18:20:56 +0100925is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000926{
Victor Stinner95872862011-03-07 18:20:56 +0100927 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +0100929 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
930 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (PyImport_Inittab[i].initfunc == NULL)
932 return -1;
933 else
934 return 1;
935 }
936 }
937 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000938}
939
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000940
Just van Rossum52e14d62002-12-30 22:08:05 +0000941/* Return an importer object for a sys.path/pkg.__path__ item 'p',
942 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000943 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000944 that can handle the path item. Return None if no hook could;
945 this tells our caller it should fall back to the builtin
946 import mechanism. Cache the result in path_importer_cache.
947 Returns a borrowed reference. */
948
949static PyObject *
950get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 PyObject *importer;
954 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* These conditions are the caller's responsibility: */
957 assert(PyList_Check(path_hooks));
958 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 nhooks = PyList_Size(path_hooks);
961 if (nhooks < 0)
962 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 importer = PyDict_GetItem(path_importer_cache, p);
965 if (importer != NULL)
966 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* set path_importer_cache[p] to None to avoid recursion */
969 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
970 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 for (j = 0; j < nhooks; j++) {
973 PyObject *hook = PyList_GetItem(path_hooks, j);
974 if (hook == NULL)
975 return NULL;
976 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
977 if (importer != NULL)
978 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
981 return NULL;
982 }
983 PyErr_Clear();
984 }
985 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400986 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 }
988 if (importer != NULL) {
989 int err = PyDict_SetItem(path_importer_cache, p, importer);
990 Py_DECREF(importer);
991 if (err != 0)
992 return NULL;
993 }
994 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000995}
996
Christian Heimes9cd17752007-11-18 19:35:23 +0000997PyAPI_FUNC(PyObject *)
998PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001000
Victor Stinner1e53bba2013-07-16 22:26:05 +02001001 path_importer_cache = PySys_GetObject("path_importer_cache");
1002 path_hooks = PySys_GetObject("path_hooks");
1003 if (path_importer_cache != NULL && path_hooks != NULL) {
1004 importer = get_path_importer(path_importer_cache,
1005 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 }
1007 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1008 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001009}
1010
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001011
Victor Stinner95872862011-03-07 18:20:56 +01001012static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001013
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001014/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001015 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001016 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001017
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001018static int
Victor Stinner95872862011-03-07 18:20:56 +01001019init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001022 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001023
Victor Stinner5eb4f592013-11-14 22:38:52 +01001024 mod = _PyImport_FindExtensionObject(name, name);
1025 if (PyErr_Occurred())
1026 return -1;
1027 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 for (p = PyImport_Inittab; p->name != NULL; p++) {
1031 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001032 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001033 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (p->initfunc == NULL) {
1035 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001036 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 name);
1038 return -1;
1039 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 mod = (*p->initfunc)();
1041 if (mod == 0)
1042 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001043 /* Remember pointer to module init function. */
1044 def = PyModule_GetDef(mod);
1045 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001046 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return -1;
1048 /* FixupExtension has put the module into sys.modules,
1049 so we can release our own reference. */
1050 Py_DECREF(mod);
1051 return 1;
1052 }
1053 }
1054 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001055}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001056
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001057
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001058/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001059
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001060static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001061find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001062{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001063 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001064
Victor Stinner53dc7352011-03-20 01:50:21 +01001065 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 for (p = PyImport_FrozenModules; ; p++) {
1069 if (p->name == NULL)
1070 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001071 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 break;
1073 }
1074 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001075}
1076
Guido van Rossum79f25d91997-04-29 20:08:16 +00001077static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001078get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001079{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001080 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (p == NULL) {
1084 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001085 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 name);
1087 return NULL;
1088 }
1089 if (p->code == NULL) {
1090 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001091 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 name);
1093 return NULL;
1094 }
1095 size = p->size;
1096 if (size < 0)
1097 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001098 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001099}
1100
Brett Cannon8d110132009-03-15 02:20:16 +00001101static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001102is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001103{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001104 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (p == NULL) {
1108 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001109 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 name);
1111 return NULL;
1112 }
Brett Cannon8d110132009-03-15 02:20:16 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (size < 0)
1117 Py_RETURN_TRUE;
1118 else
1119 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001120}
1121
1122
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001123/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001124 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001125 an exception set if the initialization failed.
1126 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001127
1128int
Victor Stinner53dc7352011-03-20 01:50:21 +01001129PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001130{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001131 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001132 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 int ispackage;
1134 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001135
Victor Stinner53dc7352011-03-20 01:50:21 +01001136 p = find_frozen(name);
1137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 if (p == NULL)
1139 return 0;
1140 if (p->code == NULL) {
1141 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001142 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 name);
1144 return -1;
1145 }
1146 size = p->size;
1147 ispackage = (size < 0);
1148 if (ispackage)
1149 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001150 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (co == NULL)
1152 return -1;
1153 if (!PyCode_Check(co)) {
1154 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001155 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 name);
1157 goto err_return;
1158 }
1159 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001160 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001161 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001163 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (m == NULL)
1165 goto err_return;
1166 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001167 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 goto err_return;
1170 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 err = PyDict_SetItemString(d, "__path__", l);
1172 Py_DECREF(l);
1173 if (err != 0)
1174 goto err_return;
1175 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001176 d = module_dict_for_exec(name);
1177 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001178 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001179 }
1180 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (m == NULL)
1182 goto err_return;
1183 Py_DECREF(co);
1184 Py_DECREF(m);
1185 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001186err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_DECREF(co);
1188 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001189}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001190
Victor Stinner53dc7352011-03-20 01:50:21 +01001191int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001192PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001193{
1194 PyObject *nameobj;
1195 int ret;
1196 nameobj = PyUnicode_InternFromString(name);
1197 if (nameobj == NULL)
1198 return -1;
1199 ret = PyImport_ImportFrozenModuleObject(nameobj);
1200 Py_DECREF(nameobj);
1201 return ret;
1202}
1203
Guido van Rossum74e6a111994-08-29 12:54:38 +00001204
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001205/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001206 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001207
Guido van Rossum79f25d91997-04-29 20:08:16 +00001208PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001209PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 PyObject *pname;
1212 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 pname = PyUnicode_FromString(name);
1215 if (pname == NULL)
1216 return NULL;
1217 result = PyImport_Import(pname);
1218 Py_DECREF(pname);
1219 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001220}
1221
Christian Heimes072c0f12008-01-03 23:01:04 +00001222/* Import a module without blocking
1223 *
1224 * At first it tries to fetch the module from sys.modules. If the module was
1225 * never loaded before it loads it with PyImport_ImportModule() unless another
1226 * thread holds the import lock. In the latter case the function raises an
1227 * ImportError instead of blocking.
1228 *
1229 * Returns the module object with incremented ref count.
1230 */
1231PyObject *
1232PyImport_ImportModuleNoBlock(const char *name)
1233{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001234 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001235}
1236
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001237
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001238/* Remove importlib frames from the traceback,
1239 * except in Verbose mode. */
1240static void
1241remove_importlib_frames(void)
1242{
1243 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001244 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001245 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001246 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001247 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001248 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001249
1250 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001251 from the traceback. We always trim chunks
1252 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001253
1254 PyErr_Fetch(&exception, &value, &base_tb);
1255 if (!exception || Py_VerboseFlag)
1256 goto done;
1257 if (PyType_IsSubtype((PyTypeObject *) exception,
1258 (PyTypeObject *) PyExc_ImportError))
1259 always_trim = 1;
1260
1261 prev_link = &base_tb;
1262 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001263 while (tb != NULL) {
1264 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1265 PyObject *next = (PyObject *) traceback->tb_next;
1266 PyFrameObject *frame = traceback->tb_frame;
1267 PyCodeObject *code = frame->f_code;
1268 int now_in_importlib;
1269
1270 assert(PyTraceBack_Check(tb));
1271 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1272 code->co_filename,
1273 importlib_filename) == 0);
1274 if (now_in_importlib && !in_importlib) {
1275 /* This is the link to this chunk of importlib tracebacks */
1276 outer_link = prev_link;
1277 }
1278 in_importlib = now_in_importlib;
1279
1280 if (in_importlib &&
1281 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001282 PyUnicode_CompareWithASCIIString(code->co_name,
1283 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001284 PyObject *tmp = *outer_link;
1285 *outer_link = next;
1286 Py_XINCREF(next);
1287 Py_DECREF(tmp);
1288 prev_link = outer_link;
1289 }
1290 else {
1291 prev_link = (PyObject **) &traceback->tb_next;
1292 }
1293 tb = next;
1294 }
1295done:
1296 PyErr_Restore(exception, value, base_tb);
1297}
1298
1299
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001300PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001301PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1302 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001303 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001304{
Brett Cannonfd074152012-04-14 14:10:13 -04001305 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001306 _Py_IDENTIFIER(__spec__);
1307 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001308 _Py_IDENTIFIER(__package__);
1309 _Py_IDENTIFIER(__path__);
1310 _Py_IDENTIFIER(__name__);
1311 _Py_IDENTIFIER(_find_and_load);
1312 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001313 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001314 _Py_static_string(single_dot, ".");
1315 PyObject *abs_name = NULL;
1316 PyObject *builtins_import = NULL;
1317 PyObject *final_mod = NULL;
1318 PyObject *mod = NULL;
1319 PyObject *package = NULL;
1320 PyObject *globals = NULL;
1321 PyObject *fromlist = NULL;
1322 PyInterpreterState *interp = PyThreadState_GET()->interp;
1323
1324 /* Make sure to use default values so as to not have
1325 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1326 NULL argument. */
1327 if (given_globals == NULL) {
1328 globals = PyDict_New();
1329 if (globals == NULL) {
1330 goto error;
1331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 }
Brett Cannonfd074152012-04-14 14:10:13 -04001333 else {
1334 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001335 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001336 if (level > 0 && !PyDict_Check(given_globals)) {
1337 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1338 goto error;
1339 }
1340 globals = given_globals;
1341 Py_INCREF(globals);
1342 }
1343
1344 if (given_fromlist == NULL) {
1345 fromlist = PyList_New(0);
1346 if (fromlist == NULL) {
1347 goto error;
1348 }
1349 }
1350 else {
1351 fromlist = given_fromlist;
1352 Py_INCREF(fromlist);
1353 }
1354 if (name == NULL) {
1355 PyErr_SetString(PyExc_ValueError, "Empty module name");
1356 goto error;
1357 }
1358
1359 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1360 for added performance. */
1361
1362 if (!PyUnicode_Check(name)) {
1363 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1364 goto error;
1365 }
1366 else if (PyUnicode_READY(name) < 0) {
1367 goto error;
1368 }
1369 if (level < 0) {
1370 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1371 goto error;
1372 }
1373 else if (level > 0) {
1374 package = _PyDict_GetItemId(globals, &PyId___package__);
1375 if (package != NULL && package != Py_None) {
1376 Py_INCREF(package);
1377 if (!PyUnicode_Check(package)) {
1378 PyErr_SetString(PyExc_TypeError, "package must be a string");
1379 goto error;
1380 }
1381 }
1382 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001383 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001384 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001385 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001386 goto error;
1387 }
1388 else if (!PyUnicode_Check(package)) {
1389 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1390 }
1391 Py_INCREF(package);
1392
1393 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001394 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001395 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1396 if (borrowed_dot == NULL) {
1397 goto error;
1398 }
Brett Cannon740fce02012-04-14 14:23:49 -04001399 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001400 Py_DECREF(package);
1401 if (partition == NULL) {
1402 goto error;
1403 }
1404 package = PyTuple_GET_ITEM(partition, 0);
1405 Py_INCREF(package);
1406 Py_DECREF(partition);
1407 }
1408 }
1409
1410 if (PyDict_GetItem(interp->modules, package) == NULL) {
1411 PyErr_Format(PyExc_SystemError,
1412 "Parent module %R not loaded, cannot perform relative "
1413 "import", package);
1414 goto error;
1415 }
1416 }
1417 else { /* level == 0 */
1418 if (PyUnicode_GET_LENGTH(name) == 0) {
1419 PyErr_SetString(PyExc_ValueError, "Empty module name");
1420 goto error;
1421 }
1422 package = Py_None;
1423 Py_INCREF(package);
1424 }
1425
1426 if (level > 0) {
1427 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1428 PyObject *base = NULL;
1429 int level_up = 1;
1430
1431 for (level_up = 1; level_up < level; level_up += 1) {
1432 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1433 if (last_dot == -2) {
1434 goto error;
1435 }
1436 else if (last_dot == -1) {
1437 PyErr_SetString(PyExc_ValueError,
1438 "attempted relative import beyond top-level "
1439 "package");
1440 goto error;
1441 }
1442 }
Victor Stinner22af2592013-11-13 12:11:36 +01001443
Brett Cannonfd074152012-04-14 14:10:13 -04001444 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001445 if (base == NULL)
1446 goto error;
1447
Brett Cannonfd074152012-04-14 14:10:13 -04001448 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001449 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001450
1451 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001452 seq = PyTuple_Pack(2, base, name);
1453 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001454 if (borrowed_dot == NULL || seq == NULL) {
1455 goto error;
1456 }
1457
1458 abs_name = PyUnicode_Join(borrowed_dot, seq);
1459 Py_DECREF(seq);
1460 if (abs_name == NULL) {
1461 goto error;
1462 }
1463 }
1464 else {
1465 abs_name = base;
1466 }
1467 }
1468 else {
1469 abs_name = name;
1470 Py_INCREF(abs_name);
1471 }
1472
Brian Curtine6b299f2012-04-14 14:19:33 -05001473#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001474 _PyImport_AcquireLock();
1475#endif
1476 /* From this point forward, goto error_with_unlock! */
1477 if (PyDict_Check(globals)) {
1478 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1479 }
1480 if (builtins_import == NULL) {
1481 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1482 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001483 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1484 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001485 }
1486 }
1487 Py_INCREF(builtins_import);
1488
1489 mod = PyDict_GetItem(interp->modules, abs_name);
1490 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001491 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1492 "None in sys.modules", abs_name);
1493 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001494 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001495 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001496 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001497 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001498 goto error_with_unlock;
1499 }
1500 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001501 PyObject *value = NULL;
1502 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001503 int initializing = 0;
1504
Brett Cannonfd074152012-04-14 14:10:13 -04001505 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001506 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001507 __spec__._initializing is true.
1508 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001509 stuffing the new module in sys.modules.
1510 */
Eric Snowb523f842013-11-22 09:05:39 -07001511 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1512 if (spec != NULL) {
1513 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1514 Py_DECREF(spec);
1515 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001516 if (value == NULL)
1517 PyErr_Clear();
1518 else {
1519 initializing = PyObject_IsTrue(value);
1520 Py_DECREF(value);
1521 if (initializing == -1)
1522 PyErr_Clear();
1523 }
1524 if (initializing > 0) {
1525 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001526 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001527 &PyId__lock_unlock_module, abs_name,
1528 NULL);
1529 if (value == NULL)
1530 goto error;
1531 Py_DECREF(value);
1532 }
1533 else {
1534#ifdef WITH_THREAD
1535 if (_PyImport_ReleaseLock() < 0) {
1536 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1537 goto error;
1538 }
1539#endif
1540 }
Brett Cannonfd074152012-04-14 14:10:13 -04001541 }
1542 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001543 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001544 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001545 &PyId__find_and_load, abs_name,
1546 builtins_import, NULL);
1547 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001548 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001549 }
1550 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001551 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001552
1553 if (PyObject_Not(fromlist)) {
1554 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1555 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001556 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001557 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1558
1559 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001560 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001561 }
1562
Brian Curtine6b299f2012-04-14 14:19:33 -05001563 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001564 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001565 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001566 }
1567
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001568 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1569 /* No dot in module name, simple exit */
1570 Py_DECREF(partition);
1571 final_mod = mod;
1572 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001573 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001574 }
1575
Brett Cannonfd074152012-04-14 14:10:13 -04001576 front = PyTuple_GET_ITEM(partition, 0);
1577 Py_INCREF(front);
1578 Py_DECREF(partition);
1579
1580 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001581 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001582 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001583 }
1584 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001585 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1586 PyUnicode_GET_LENGTH(front);
1587 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001588 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001589 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001590 Py_DECREF(front);
1591 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001592 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001593 }
Brett Cannonfd074152012-04-14 14:10:13 -04001594
1595 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001596 if (final_mod == NULL) {
1597 PyErr_Format(PyExc_KeyError,
1598 "%R not in sys.modules as expected",
1599 to_return);
1600 }
1601 else {
1602 Py_INCREF(final_mod);
1603 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001604 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001605 }
1606 }
1607 else {
1608 final_mod = mod;
1609 Py_INCREF(mod);
1610 }
1611 }
1612 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001613 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001614 &PyId__handle_fromlist, mod,
1615 fromlist, builtins_import,
1616 NULL);
1617 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001618 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001619
Brett Cannonfd074152012-04-14 14:10:13 -04001620 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001621#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001622 if (_PyImport_ReleaseLock() < 0) {
1623 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1624 }
1625#endif
1626 error:
1627 Py_XDECREF(abs_name);
1628 Py_XDECREF(builtins_import);
1629 Py_XDECREF(mod);
1630 Py_XDECREF(package);
1631 Py_XDECREF(globals);
1632 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001633 if (final_mod == NULL)
1634 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001635 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001636}
1637
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001638PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001639PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001640 PyObject *fromlist, int level)
1641{
1642 PyObject *nameobj, *mod;
1643 nameobj = PyUnicode_FromString(name);
1644 if (nameobj == NULL)
1645 return NULL;
1646 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1647 fromlist, level);
1648 Py_DECREF(nameobj);
1649 return mod;
1650}
1651
1652
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001653/* Re-import a module of any kind and return its module object, WITH
1654 INCREMENTED REFERENCE COUNT */
1655
Guido van Rossum79f25d91997-04-29 20:08:16 +00001656PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001657PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001658{
Brett Cannon62228db2012-04-29 14:38:11 -04001659 _Py_IDENTIFIER(reload);
1660 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001662 PyObject *imp = PyDict_GetItemString(modules, "imp");
1663 if (imp == NULL) {
1664 imp = PyImport_ImportModule("imp");
1665 if (imp == NULL) {
1666 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 }
Brett Cannon62228db2012-04-29 14:38:11 -04001669 else {
1670 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001672
Brett Cannon62228db2012-04-29 14:38:11 -04001673 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1674 Py_DECREF(imp);
1675 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001676}
1677
1678
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001679/* Higher-level import emulator which emulates the "import" statement
1680 more accurately -- it invokes the __import__() function from the
1681 builtins of the current globals. This means that the import is
1682 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001683 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001684 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001685 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001686 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001687
1688PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001689PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 static PyObject *silly_list = NULL;
1692 static PyObject *builtins_str = NULL;
1693 static PyObject *import_str = NULL;
1694 PyObject *globals = NULL;
1695 PyObject *import = NULL;
1696 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001697 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* Initialize constant string objects */
1701 if (silly_list == NULL) {
1702 import_str = PyUnicode_InternFromString("__import__");
1703 if (import_str == NULL)
1704 return NULL;
1705 builtins_str = PyUnicode_InternFromString("__builtins__");
1706 if (builtins_str == NULL)
1707 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001708 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (silly_list == NULL)
1710 return NULL;
1711 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 /* Get the builtins from current globals */
1714 globals = PyEval_GetGlobals();
1715 if (globals != NULL) {
1716 Py_INCREF(globals);
1717 builtins = PyObject_GetItem(globals, builtins_str);
1718 if (builtins == NULL)
1719 goto err;
1720 }
1721 else {
1722 /* No globals -- use standard builtins, and fake globals */
1723 builtins = PyImport_ImportModuleLevel("builtins",
1724 NULL, NULL, NULL, 0);
1725 if (builtins == NULL)
1726 return NULL;
1727 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1728 if (globals == NULL)
1729 goto err;
1730 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 /* Get the __import__ function from the builtins */
1733 if (PyDict_Check(builtins)) {
1734 import = PyObject_GetItem(builtins, import_str);
1735 if (import == NULL)
1736 PyErr_SetObject(PyExc_KeyError, import_str);
1737 }
1738 else
1739 import = PyObject_GetAttr(builtins, import_str);
1740 if (import == NULL)
1741 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001744 Always use absolute import here.
1745 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1747 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001748 if (r == NULL)
1749 goto err;
1750 Py_DECREF(r);
1751
1752 modules = PyImport_GetModuleDict();
1753 r = PyDict_GetItem(modules, module_name);
1754 if (r != NULL)
1755 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001756
1757 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 Py_XDECREF(globals);
1759 Py_XDECREF(builtins);
1760 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001763}
1764
Brett Cannon4caa61d2014-01-09 19:03:32 -05001765/*[clinic input]
1766_imp.extension_suffixes
1767
1768Returns the list of file suffixes used to identify extension modules.
1769[clinic start generated code]*/
1770
Brett Cannon4caa61d2014-01-09 19:03:32 -05001771static PyObject *
1772_imp_extension_suffixes_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001773/*[clinic end generated code: output=d44c1566ef362229 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001776 const char *suffix;
1777 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 list = PyList_New(0);
1780 if (list == NULL)
1781 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001782#ifdef HAVE_DYNAMIC_LOADING
1783 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1784 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (item == NULL) {
1786 Py_DECREF(list);
1787 return NULL;
1788 }
1789 if (PyList_Append(list, item) < 0) {
1790 Py_DECREF(list);
1791 Py_DECREF(item);
1792 return NULL;
1793 }
1794 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001795 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 }
Brett Cannon2657df42012-05-04 15:20:40 -04001797#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001799}
1800
Brett Cannon4caa61d2014-01-09 19:03:32 -05001801/*[clinic input]
1802_imp.init_builtin
1803
1804 name: unicode
1805 /
1806
1807Initializes a built-in module.
1808[clinic start generated code]*/
1809
Brett Cannon4caa61d2014-01-09 19:03:32 -05001810static PyObject *
1811_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001812/*[clinic end generated code: output=1868f473685f6d67 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 int ret;
1815 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 ret = init_builtin(name);
1818 if (ret < 0)
1819 return NULL;
1820 if (ret == 0) {
1821 Py_INCREF(Py_None);
1822 return Py_None;
1823 }
Victor Stinner95872862011-03-07 18:20:56 +01001824 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 Py_XINCREF(m);
1826 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001827}
1828
Brett Cannon4caa61d2014-01-09 19:03:32 -05001829/*[clinic input]
1830_imp.init_frozen
1831
1832 name: unicode
1833 /
1834
1835Initializes a frozen module.
1836[clinic start generated code]*/
1837
Brett Cannon4caa61d2014-01-09 19:03:32 -05001838static PyObject *
1839_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001840/*[clinic end generated code: output=a9de493bdd711878 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 int ret;
1843 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001844
Victor Stinner53dc7352011-03-20 01:50:21 +01001845 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (ret < 0)
1847 return NULL;
1848 if (ret == 0) {
1849 Py_INCREF(Py_None);
1850 return Py_None;
1851 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001852 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 Py_XINCREF(m);
1854 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001855}
1856
Brett Cannon4caa61d2014-01-09 19:03:32 -05001857/*[clinic input]
1858_imp.get_frozen_object
1859
1860 name: unicode
1861 /
1862
1863Create a code object for a frozen module.
1864[clinic start generated code]*/
1865
Brett Cannon4caa61d2014-01-09 19:03:32 -05001866static PyObject *
1867_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001868/*[clinic end generated code: output=3114c970a47f2e3c input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001871}
1872
Brett Cannon4caa61d2014-01-09 19:03:32 -05001873/*[clinic input]
1874_imp.is_frozen_package
1875
1876 name: unicode
1877 /
1878
1879Returns True if the module name is of a frozen package.
1880[clinic start generated code]*/
1881
Brett Cannon4caa61d2014-01-09 19:03:32 -05001882static PyObject *
1883_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001884/*[clinic end generated code: output=3e4cab802b56d649 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001887}
1888
Brett Cannon4caa61d2014-01-09 19:03:32 -05001889/*[clinic input]
1890_imp.is_builtin
1891
1892 name: unicode
1893 /
1894
1895Returns True if the module name corresponds to a built-in module.
1896[clinic start generated code]*/
1897
Guido van Rossum79f25d91997-04-29 20:08:16 +00001898static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001899_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001900/*[clinic end generated code: output=2deec9cac6fb9a7e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001901{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001902 return PyLong_FromLong(is_builtin(name));
1903}
1904
1905/*[clinic input]
1906_imp.is_frozen
1907
1908 name: unicode
1909 /
1910
1911Returns True if the module name corresponds to a frozen module.
1912[clinic start generated code]*/
1913
Brett Cannon4caa61d2014-01-09 19:03:32 -05001914static PyObject *
1915_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001916/*[clinic end generated code: output=7de8e260c8e36aed input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001917{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001918 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 p = find_frozen(name);
1921 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001922}
1923
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001924#ifdef HAVE_DYNAMIC_LOADING
1925
Brett Cannon4caa61d2014-01-09 19:03:32 -05001926/*[clinic input]
1927_imp.load_dynamic
1928
1929 name: unicode
1930 path: fs_unicode
1931 file: object = NULL
1932 /
1933
1934Loads an extension module.
1935[clinic start generated code]*/
1936
Brett Cannon4caa61d2014-01-09 19:03:32 -05001937static PyObject *
1938_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001939/*[clinic end generated code: output=8b7ae431d795e1ba input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001940{
1941 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001942 FILE *fp;
1943
Brett Cannon4caa61d2014-01-09 19:03:32 -05001944 if (file != NULL) {
1945 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001946 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05001947 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02001948 if (!PyErr_Occurred())
1949 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001953 else
1954 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001955 mod = _PyImport_LoadDynamicModule(name, path, fp);
1956 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (fp)
1958 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001959 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001960}
1961
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001962#endif /* HAVE_DYNAMIC_LOADING */
1963
Larry Hastings7726ac92014-01-31 22:03:12 -08001964/*[clinic input]
1965dump buffer
1966[clinic start generated code]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -04001967/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
Larry Hastings7726ac92014-01-31 22:03:12 -08001968
Barry Warsaw28a691b2010-04-17 00:19:56 +00001969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001970PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04001971"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001972
Guido van Rossum79f25d91997-04-29 20:08:16 +00001973static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05001974 _IMP_EXTENSION_SUFFIXES_METHODDEF
1975 _IMP_LOCK_HELD_METHODDEF
1976 _IMP_ACQUIRE_LOCK_METHODDEF
1977 _IMP_RELEASE_LOCK_METHODDEF
1978 _IMP_GET_FROZEN_OBJECT_METHODDEF
1979 _IMP_IS_FROZEN_PACKAGE_METHODDEF
1980 _IMP_INIT_BUILTIN_METHODDEF
1981 _IMP_INIT_FROZEN_METHODDEF
1982 _IMP_IS_BUILTIN_METHODDEF
1983 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05001984 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05001985 _IMP__FIX_CO_FILENAME_METHODDEF
1986 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001987};
1988
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001989
Martin v. Löwis1a214512008-06-11 05:26:20 +00001990static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04001992 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 doc_imp,
1994 0,
1995 imp_methods,
1996 NULL,
1997 NULL,
1998 NULL,
1999 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002000};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002001
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002002PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002003PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 m = PyModule_Create(&impmodule);
2008 if (m == NULL)
2009 goto failure;
2010 d = PyModule_GetDict(m);
2011 if (d == NULL)
2012 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002015 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 Py_XDECREF(m);
2017 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002018}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002019
2020
Guido van Rossumb18618d2000-05-03 23:44:39 +00002021/* API for embedding applications that want to add their own entries
2022 to the table of built-in modules. This should normally be called
2023 *before* Py_Initialize(). When the table resize fails, -1 is
2024 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002025
2026 After a similar function by Just van Rossum. */
2027
2028int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002029PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 static struct _inittab *our_copy = NULL;
2032 struct _inittab *p;
2033 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* Count the number of entries in both tables */
2036 for (n = 0; newtab[n].name != NULL; n++)
2037 ;
2038 if (n == 0)
2039 return 0; /* Nothing to do */
2040 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2041 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 /* Allocate new memory for the combined table */
2044 p = our_copy;
2045 PyMem_RESIZE(p, struct _inittab, i+n+1);
2046 if (p == NULL)
2047 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* Copy the tables into the new memory */
2050 if (our_copy != PyImport_Inittab)
2051 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2052 PyImport_Inittab = our_copy = p;
2053 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002056}
2057
2058/* Shorthand to add a single entry given a name and a function */
2059
2060int
Brett Cannona826f322009-04-02 03:41:46 +00002061PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002066
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002067 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002071}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002072
2073#ifdef __cplusplus
2074}
2075#endif