blob: 999da3759c0f6e691957ee2d1694f38f5c61766d [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]
35module _imp
36[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030037/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040038
39#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050040
41/*[python input]
42class fs_unicode_converter(CConverter):
43 type = 'PyObject *'
44 converter = 'PyUnicode_FSDecoder'
45
46[python start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080047/*[python end generated code: output=da39a3ee5e6b4b0d input=9d6786230166006e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050048
Guido van Rossum1ae940a1995-01-02 19:04:15 +000049/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000050
51void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000052_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020054 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040055 initstr = PyUnicode_InternFromString("__init__");
56 if (initstr == NULL)
57 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020058 interp->builtins_copy = PyDict_Copy(interp->builtins);
59 if (interp->builtins_copy == NULL)
60 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061}
62
Guido van Rossum25ce5661997-08-02 03:10:38 +000063void
Just van Rossum52e14d62002-12-30 22:08:05 +000064_PyImportHooks_Init(void)
65{
Brett Cannonfd074152012-04-14 14:10:13 -040066 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000068
Brett Cannonfd074152012-04-14 14:10:13 -040069 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 v = PyList_New(0);
71 if (v == NULL)
72 goto error;
73 err = PySys_SetObject("meta_path", v);
74 Py_DECREF(v);
75 if (err)
76 goto error;
77 v = PyDict_New();
78 if (v == NULL)
79 goto error;
80 err = PySys_SetObject("path_importer_cache", v);
81 Py_DECREF(v);
82 if (err)
83 goto error;
84 path_hooks = PyList_New(0);
85 if (path_hooks == NULL)
86 goto error;
87 err = PySys_SetObject("path_hooks", path_hooks);
88 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000089 error:
Brett Cannonfd074152012-04-14 14:10:13 -040090 PyErr_Print();
91 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020092 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 }
Brett Cannonfd074152012-04-14 14:10:13 -040094 Py_DECREF(path_hooks);
95}
96
97void
98_PyImportZip_Init(void)
99{
100 PyObject *path_hooks, *zimpimport;
101 int err = 0;
102
103 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200104 if (path_hooks == NULL) {
105 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400106 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200107 }
Brett Cannonfd074152012-04-14 14:10:13 -0400108
109 if (Py_VerboseFlag)
110 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 zimpimport = PyImport_ImportModule("zipimport");
113 if (zimpimport == NULL) {
114 PyErr_Clear(); /* No zip import module -- okay */
115 if (Py_VerboseFlag)
116 PySys_WriteStderr("# can't import zipimport\n");
117 }
118 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200119 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200120 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
121 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 Py_DECREF(zimpimport);
123 if (zipimporter == NULL) {
124 PyErr_Clear(); /* No zipimporter object -- okay */
125 if (Py_VerboseFlag)
126 PySys_WriteStderr(
127 "# can't import zipimport.zipimporter\n");
128 }
129 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400130 /* sys.path_hooks.insert(0, zipimporter) */
131 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400133 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 if (Py_VerboseFlag)
137 PySys_WriteStderr(
138 "# installed zipimport hook\n");
139 }
140 }
Brett Cannonfd074152012-04-14 14:10:13 -0400141
142 return;
143
144 error:
145 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400146 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000147}
148
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000149/* Locking primitives to prevent parallel imports of the same module
150 in different threads to return with a partially loaded module.
151 These calls are serialized by the global interpreter lock. */
152
153#ifdef WITH_THREAD
154
Guido van Rossum49b56061998-10-01 20:42:43 +0000155#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156
Guido van Rossum65d5b571998-12-21 19:32:43 +0000157static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000158static long import_lock_thread = -1;
159static int import_lock_level = 0;
160
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000161void
162_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 long me = PyThread_get_thread_ident();
165 if (me == -1)
166 return; /* Too bad */
167 if (import_lock == NULL) {
168 import_lock = PyThread_allocate_lock();
169 if (import_lock == NULL)
170 return; /* Nothing much we can do. */
171 }
172 if (import_lock_thread == me) {
173 import_lock_level++;
174 return;
175 }
176 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
177 {
178 PyThreadState *tstate = PyEval_SaveThread();
179 PyThread_acquire_lock(import_lock, 1);
180 PyEval_RestoreThread(tstate);
181 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100182 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 import_lock_thread = me;
184 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000185}
186
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000187int
188_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 long me = PyThread_get_thread_ident();
191 if (me == -1 || import_lock == NULL)
192 return 0; /* Too bad */
193 if (import_lock_thread != me)
194 return -1;
195 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100196 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 if (import_lock_level == 0) {
198 import_lock_thread = -1;
199 PyThread_release_lock(import_lock);
200 }
201 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000202}
203
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000204/* This function is called from PyOS_AfterFork to ensure that newly
205 created child processes do not share locks with the parent.
206 We now acquire the import lock around fork() calls but on some platforms
207 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000208
209void
210_PyImport_ReInitLock(void)
211{
Christian Heimes418fd742015-04-19 21:08:42 +0200212 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200214 if (import_lock == NULL) {
215 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
216 }
217 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000218 if (import_lock_level > 1) {
219 /* Forked as a side effect of import */
220 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500221 /* The following could fail if the lock is already held, but forking as
222 a side-effect of an import is a) rare, b) nuts, and c) difficult to
223 do thanks to the lock only being held when doing individual module
224 locks per import. */
225 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000226 import_lock_thread = me;
227 import_lock_level--;
228 } else {
229 import_lock_thread = -1;
230 import_lock_level = 0;
231 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000232}
233
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000234#endif
235
Brett Cannon4caa61d2014-01-09 19:03:32 -0500236/*[clinic input]
237_imp.lock_held
238
239Return True if the import lock is currently held, else False.
240
241On platforms without threads, return False.
242[clinic start generated code]*/
243
Brett Cannon4caa61d2014-01-09 19:03:32 -0500244static PyObject *
245_imp_lock_held_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400246/*[clinic end generated code: output=d7a8cc3a5169081a input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000247{
Tim Peters69232342001-08-30 05:16:13 +0000248#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000250#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000252#endif
253}
254
Brett Cannon4caa61d2014-01-09 19:03:32 -0500255/*[clinic input]
256_imp.acquire_lock
257
258Acquires the interpreter's import lock for the current thread.
259
260This lock should be used by import hooks to ensure thread-safety when importing
261modules. On platforms without threads, this function does nothing.
262[clinic start generated code]*/
263
Brett Cannon4caa61d2014-01-09 19:03:32 -0500264static PyObject *
265_imp_acquire_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400266/*[clinic end generated code: output=cc143b1d16422cae input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000267{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000268#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 Py_INCREF(Py_None);
272 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000273}
274
Brett Cannon4caa61d2014-01-09 19:03:32 -0500275/*[clinic input]
276_imp.release_lock
277
278Release the interpreter's import lock.
279
280On platforms without threads, this function does nothing.
281[clinic start generated code]*/
282
Brett Cannon4caa61d2014-01-09 19:03:32 -0500283static PyObject *
284_imp_release_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400285/*[clinic end generated code: output=74d28e38ebe2b224 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000286{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000287#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 if (_PyImport_ReleaseLock() < 0) {
289 PyErr_SetString(PyExc_RuntimeError,
290 "not holding the import lock");
291 return NULL;
292 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000293#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_INCREF(Py_None);
295 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000296}
297
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100298void
299_PyImport_Fini(void)
300{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200301 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100302#ifdef WITH_THREAD
303 if (import_lock != NULL) {
304 PyThread_free_lock(import_lock);
305 import_lock = NULL;
306 }
307#endif
308}
309
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310/* Helper for sys */
311
312PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000313PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyInterpreterState *interp = PyThreadState_GET()->interp;
316 if (interp->modules == NULL)
317 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
318 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319}
320
Guido van Rossum3f5da241990-12-20 15:06:42 +0000321
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000322/* List of names to clear in sys */
323static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 "path", "argv", "ps1", "ps2",
325 "last_type", "last_value", "last_traceback",
326 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200327 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 /* misc stuff */
329 "flags", "float_info",
330 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000331};
332
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000333static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 "stdin", "__stdin__",
335 "stdout", "__stdout__",
336 "stderr", "__stderr__",
337 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000338};
339
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000340/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000341
Guido van Rossum3f5da241990-12-20 15:06:42 +0000342void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000343PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000344{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200345 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 PyObject *key, *value, *dict;
347 PyInterpreterState *interp = PyThreadState_GET()->interp;
348 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200349 PyObject *weaklist = NULL;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200350 char **p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (modules == NULL)
353 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* Delete some special variables first. These are common
356 places where user values hide and people complain when their
357 destructors fail. Since the modules containing them are
358 deleted *last* of all, they would come too late in the normal
359 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000360
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200361 /* XXX Perhaps these precautions are obsolete. Who knows? */
362
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200363 if (Py_VerboseFlag)
364 PySys_WriteStderr("# clear builtins._\n");
365 PyDict_SetItemString(interp->builtins, "_", Py_None);
366
367 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200369 PySys_WriteStderr("# clear sys.%s\n", *p);
370 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200372 for (p = sys_files; *p != NULL; p+=2) {
373 if (Py_VerboseFlag)
374 PySys_WriteStderr("# restore sys.%s\n", *p);
375 value = PyDict_GetItemString(interp->sysdict, *(p+1));
376 if (value == NULL)
377 value = Py_None;
378 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000380
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200381 /* We prepare a list which will receive (name, weakref) tuples of
382 modules when they are removed from sys.modules. The name is used
383 for diagnosis messages (in verbose mode), while the weakref helps
384 detect those modules which have been held alive. */
385 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200386 if (weaklist == NULL)
387 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200388
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200389#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200390 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200391 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
392 if (name && wr) { \
393 PyObject *tup = PyTuple_Pack(2, name, wr); \
394 PyList_Append(weaklist, tup); \
395 Py_XDECREF(tup); \
396 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200397 Py_XDECREF(wr); \
398 if (PyErr_Occurred()) \
399 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000401
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200402 /* Remove all modules from sys.modules, hoping that garbage collection
403 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 pos = 0;
405 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200406 if (PyModule_Check(value)) {
407 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200408 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200409 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyDict_SetItem(modules, key, Py_None);
411 }
412 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000413
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200414 /* Clear the modules dict. */
415 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200416 /* Restore the original builtins dict, to ensure that any
417 user data gets cleared. */
418 dict = PyDict_Copy(interp->builtins);
419 if (dict == NULL)
420 PyErr_Clear();
421 PyDict_Clear(interp->builtins);
422 if (PyDict_Update(interp->builtins, interp->builtins_copy))
423 PyErr_Clear();
424 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200425 /* Clear module dict copies stored in the interpreter state */
426 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200427 /* Collect references */
428 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200429 /* Dump GC stats before it's too late, since it uses the warnings
430 machinery. */
431 _PyGC_DumpShutdownStats();
432
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200433 /* Now, if there are any modules left alive, clear their globals to
434 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200435 up here, since they are kept alive in the interpreter state.
436
437 The special treatment of "builtins" here is because even
438 when it's not referenced as a module, its dictionary is
439 referenced by almost every module's __builtins__. Since
440 deleting a module clears its dictionary (even if there are
441 references left to it), we need to delete the "builtins"
442 module last. Likewise, we don't delete sys until the very
443 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200444 if (weaklist != NULL) {
445 Py_ssize_t i, n;
446 n = PyList_GET_SIZE(weaklist);
447 for (i = 0; i < n; i++) {
448 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200449 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
451 if (mod == Py_None)
452 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200453 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200454 dict = PyModule_GetDict(mod);
455 if (dict == interp->builtins || dict == interp->sysdict)
456 continue;
457 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200458 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200459 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200460 _PyModule_Clear(mod);
461 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200462 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200463 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000465
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200466 /* Next, delete sys and builtins (in that order) */
467 if (Py_VerboseFlag)
468 PySys_FormatStderr("# cleanup[3] wiping sys\n");
469 _PyModule_ClearDict(interp->sysdict);
470 if (Py_VerboseFlag)
471 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
472 _PyModule_ClearDict(interp->builtins);
473
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200474 /* Clear and delete the modules directory. Actual modules will
475 still be there only if imported during the execution of some
476 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 interp->modules = NULL;
478 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200479
480 /* Once more */
481 _PyGC_CollectNoFail();
482
483#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000484}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000485
486
Barry Warsaw28a691b2010-04-17 00:19:56 +0000487/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000488
489long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000490PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000491{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200492 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400493 PyInterpreterState *interp = PyThreadState_Get()->interp;
494 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
495 "_RAW_MAGIC_NUMBER");
496 if (pyc_magic == NULL)
497 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200498 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700499 Py_DECREF(pyc_magic);
500 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000501}
502
503
Brett Cannon3adc7b72012-07-09 14:22:12 -0400504extern const char * _PySys_ImplCacheTag;
505
Barry Warsaw28a691b2010-04-17 00:19:56 +0000506const char *
507PyImport_GetMagicTag(void)
508{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400509 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000510}
511
Brett Cannon98979b82012-07-02 15:13:11 -0400512
Guido van Rossum25ce5661997-08-02 03:10:38 +0000513/* Magic for extension modules (built-in as well as dynamically
514 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200515 once, we keep a static dictionary 'extensions' keyed by the tuple
516 (module name, module name) (for built-in modules) or by
517 (filename, module name) (for dynamically loaded modules), containing these
518 modules. A copy of the module's dictionary is stored by calling
519 _PyImport_FixupExtensionObject() immediately after the module initialization
520 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100521 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000522
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000523 Modules which do support multiple initialization set their m_size
524 field to a non-negative number (indicating the size of the
525 module-specific state). They are still recorded in the extensions
526 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000527*/
528
529int
Victor Stinner95872862011-03-07 18:20:56 +0100530_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
531 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000532{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500533 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500535 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (extensions == NULL) {
537 extensions = PyDict_New();
538 if (extensions == NULL)
539 return -1;
540 }
541 if (mod == NULL || !PyModule_Check(mod)) {
542 PyErr_BadInternalCall();
543 return -1;
544 }
545 def = PyModule_GetDef(mod);
546 if (!def) {
547 PyErr_BadInternalCall();
548 return -1;
549 }
550 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100551 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return -1;
553 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100554 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return -1;
556 }
557 if (def->m_size == -1) {
558 if (def->m_base.m_copy) {
559 /* Somebody already imported the module,
560 likely under a different name.
561 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200562 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 }
564 dict = PyModule_GetDict(mod);
565 if (dict == NULL)
566 return -1;
567 def->m_base.m_copy = PyDict_Copy(dict);
568 if (def->m_base.m_copy == NULL)
569 return -1;
570 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500571 key = PyTuple_Pack(2, filename, name);
572 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200573 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500574 res = PyDict_SetItem(extensions, key, (PyObject *)def);
575 Py_DECREF(key);
576 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200577 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579}
580
Victor Stinner49d3f252010-10-17 01:24:53 +0000581int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300582_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000583{
584 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100585 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100586 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100587 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000588 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100589 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
590 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000591 return res;
592}
593
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100595_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500597 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 PyModuleDef* def;
599 if (extensions == NULL)
600 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500601 key = PyTuple_Pack(2, filename, name);
602 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200603 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500604 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
605 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (def == NULL)
607 return NULL;
608 if (def->m_size == -1) {
609 /* Module does not support repeated initialization */
610 if (def->m_base.m_copy == NULL)
611 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100612 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (mod == NULL)
614 return NULL;
615 mdict = PyModule_GetDict(mod);
616 if (mdict == NULL)
617 return NULL;
618 if (PyDict_Update(mdict, def->m_base.m_copy))
619 return NULL;
620 }
621 else {
622 if (def->m_base.m_init == NULL)
623 return NULL;
624 mod = def->m_base.m_init();
625 if (mod == NULL)
626 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200627 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
628 Py_DECREF(mod);
629 return NULL;
630 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 Py_DECREF(mod);
632 }
633 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100634 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 Py_DECREF(mod);
636 return NULL;
637 }
638 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100639 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 name, filename);
641 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000642
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000643}
644
Victor Stinner49d3f252010-10-17 01:24:53 +0000645PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000646_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000647{
Victor Stinner95872862011-03-07 18:20:56 +0100648 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100649 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100650 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000651 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100652 res = _PyImport_FindExtensionObject(nameobj, nameobj);
653 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000654 return res;
655}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656
657/* Get the module object corresponding to a module name.
658 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000659 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000660 Because the former action is most common, THIS DOES NOT RETURN A
661 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662
Guido van Rossum79f25d91997-04-29 20:08:16 +0000663PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000664PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyObject *modules = PyImport_GetModuleDict();
667 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000668
Victor Stinner27ee0892011-03-04 12:57:09 +0000669 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyModule_Check(m))
671 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000672 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (m == NULL)
674 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000675 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 Py_DECREF(m);
677 return NULL;
678 }
679 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000682}
683
Victor Stinner27ee0892011-03-04 12:57:09 +0000684PyObject *
685PyImport_AddModule(const char *name)
686{
687 PyObject *nameobj, *module;
688 nameobj = PyUnicode_FromString(name);
689 if (nameobj == NULL)
690 return NULL;
691 module = PyImport_AddModuleObject(nameobj);
692 Py_DECREF(nameobj);
693 return module;
694}
695
696
Tim Peters1cd70172004-08-02 03:52:12 +0000697/* Remove name from sys.modules, if it's there. */
698static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000699remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000702 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000704 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 Py_FatalError("import: deleting existing key in"
706 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000707}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000708
Christian Heimes3b06e532008-01-07 20:12:44 +0000709
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000710/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000711 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
712 * removed from sys.modules, to avoid leaving damaged module objects
713 * in sys.modules. The caller may wish to restore the original
714 * module object (if any) in this case; PyImport_ReloadModule is an
715 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000716 *
717 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
718 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000719 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000720PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300721PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return PyImport_ExecCodeModuleWithPathnames(
724 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000725}
726
727PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300728PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 return PyImport_ExecCodeModuleWithPathnames(
731 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000732}
733
734PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300735PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
736 const char *pathname,
737 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000738{
Victor Stinner27ee0892011-03-04 12:57:09 +0000739 PyObject *m = NULL;
740 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
741
742 nameobj = PyUnicode_FromString(name);
743 if (nameobj == NULL)
744 return NULL;
745
Victor Stinner27ee0892011-03-04 12:57:09 +0000746 if (cpathname != NULL) {
747 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
748 if (cpathobj == NULL)
749 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400750 }
751 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000752 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400753
754 if (pathname != NULL) {
755 pathobj = PyUnicode_DecodeFSDefault(pathname);
756 if (pathobj == NULL)
757 goto error;
758 }
759 else if (cpathobj != NULL) {
760 PyInterpreterState *interp = PyThreadState_GET()->interp;
761 _Py_IDENTIFIER(_get_sourcefile);
762
763 if (interp == NULL) {
764 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
765 "no interpreter!");
766 }
767
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -0700768 pathobj = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannona6473f92012-07-13 13:57:03 -0400769 &PyId__get_sourcefile, cpathobj,
770 NULL);
771 if (pathobj == NULL)
772 PyErr_Clear();
773 }
774 else
775 pathobj = NULL;
776
Victor Stinner27ee0892011-03-04 12:57:09 +0000777 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
778error:
779 Py_DECREF(nameobj);
780 Py_XDECREF(pathobj);
781 Py_XDECREF(cpathobj);
782 return m;
783}
784
Brett Cannon18fc4e72014-04-04 10:01:46 -0400785static PyObject *
786module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000787{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400788 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000789
Victor Stinner27ee0892011-03-04 12:57:09 +0000790 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (m == NULL)
792 return NULL;
793 /* If the module is being reloaded, we get the old module back
794 and re-use its dict to exec the new code. */
795 d = PyModule_GetDict(m);
796 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
797 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400798 PyEval_GetBuiltins()) != 0) {
799 remove_module(name);
800 return NULL;
801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400803
Eric Snow08197a42014-05-12 17:54:55 -0600804 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400805}
806
807static PyObject *
808exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
809{
810 PyObject *modules = PyImport_GetModuleDict();
811 PyObject *v, *m;
812
813 v = PyEval_EvalCode(code_object, module_dict, module_dict);
814 if (v == NULL) {
815 remove_module(name);
816 return NULL;
817 }
818 Py_DECREF(v);
819
820 if ((m = PyDict_GetItem(modules, name)) == NULL) {
821 PyErr_Format(PyExc_ImportError,
822 "Loaded module %R not found in sys.modules",
823 name);
824 return NULL;
825 }
826
827 Py_INCREF(m);
828
829 return m;
830}
831
832PyObject*
833PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
834 PyObject *cpathname)
835{
Eric Snow08197a42014-05-12 17:54:55 -0600836 PyObject *d, *res;
837 PyInterpreterState *interp = PyThreadState_GET()->interp;
838 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400839
840 d = module_dict_for_exec(name);
841 if (d == NULL) {
842 return NULL;
843 }
844
Eric Snow08197a42014-05-12 17:54:55 -0600845 if (pathname == NULL) {
846 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 }
Eric Snow08197a42014-05-12 17:54:55 -0600848 res = _PyObject_CallMethodIdObjArgs(interp->importlib,
849 &PyId__fix_up_module,
850 d, name, pathname, cpathname, NULL);
851 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600852 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600853 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 }
Eric Snow08197a42014-05-12 17:54:55 -0600855 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000856}
857
858
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000859static void
860update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyObject *constants, *tmp;
863 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (PyUnicode_Compare(co->co_filename, oldname))
866 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 tmp = co->co_filename;
869 co->co_filename = newname;
870 Py_INCREF(co->co_filename);
871 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 constants = co->co_consts;
874 n = PyTuple_GET_SIZE(constants);
875 for (i = 0; i < n; i++) {
876 tmp = PyTuple_GET_ITEM(constants, i);
877 if (PyCode_Check(tmp))
878 update_code_filenames((PyCodeObject *)tmp,
879 oldname, newname);
880 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000881}
882
Victor Stinner2f42ae52011-03-20 00:41:24 +0100883static void
884update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000885{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100886 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000887
Victor Stinner2f42ae52011-03-20 00:41:24 +0100888 if (PyUnicode_Compare(co->co_filename, newname) == 0)
889 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 oldname = co->co_filename;
892 Py_INCREF(oldname);
893 update_code_filenames(co, oldname, newname);
894 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000895}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000896
Brett Cannon4caa61d2014-01-09 19:03:32 -0500897/*[clinic input]
898_imp._fix_co_filename
899
900 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
901 Code object to change.
902
903 path: unicode
904 File path to use.
905 /
906
907Changes code.co_filename to specify the passed-in file path.
908[clinic start generated code]*/
909
Brett Cannon4caa61d2014-01-09 19:03:32 -0500910static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -0400911_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code,
912 PyObject *path)
913/*[clinic end generated code: output=f4db56aac0a1327f input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700914
Brett Cannon4caa61d2014-01-09 19:03:32 -0500915{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500916 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700917
918 Py_RETURN_NONE;
919}
920
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000921
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000922/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700923static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000924
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000925
926/* Helper to test for built-in module */
927
928static int
Victor Stinner95872862011-03-07 18:20:56 +0100929is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000930{
Victor Stinner95872862011-03-07 18:20:56 +0100931 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +0100933 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
934 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (PyImport_Inittab[i].initfunc == NULL)
936 return -1;
937 else
938 return 1;
939 }
940 }
941 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000942}
943
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000944
Just van Rossum52e14d62002-12-30 22:08:05 +0000945/* Return an importer object for a sys.path/pkg.__path__ item 'p',
946 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000947 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000948 that can handle the path item. Return None if no hook could;
949 this tells our caller it should fall back to the builtin
950 import mechanism. Cache the result in path_importer_cache.
951 Returns a borrowed reference. */
952
953static PyObject *
954get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 PyObject *importer;
958 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* These conditions are the caller's responsibility: */
961 assert(PyList_Check(path_hooks));
962 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 nhooks = PyList_Size(path_hooks);
965 if (nhooks < 0)
966 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 importer = PyDict_GetItem(path_importer_cache, p);
969 if (importer != NULL)
970 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* set path_importer_cache[p] to None to avoid recursion */
973 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
974 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 for (j = 0; j < nhooks; j++) {
977 PyObject *hook = PyList_GetItem(path_hooks, j);
978 if (hook == NULL)
979 return NULL;
980 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
981 if (importer != NULL)
982 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
985 return NULL;
986 }
987 PyErr_Clear();
988 }
989 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400990 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 }
992 if (importer != NULL) {
993 int err = PyDict_SetItem(path_importer_cache, p, importer);
994 Py_DECREF(importer);
995 if (err != 0)
996 return NULL;
997 }
998 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000999}
1000
Christian Heimes9cd17752007-11-18 19:35:23 +00001001PyAPI_FUNC(PyObject *)
1002PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001004
Victor Stinner1e53bba2013-07-16 22:26:05 +02001005 path_importer_cache = PySys_GetObject("path_importer_cache");
1006 path_hooks = PySys_GetObject("path_hooks");
1007 if (path_importer_cache != NULL && path_hooks != NULL) {
1008 importer = get_path_importer(path_importer_cache,
1009 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 }
1011 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1012 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001013}
1014
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001015
Victor Stinner95872862011-03-07 18:20:56 +01001016static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001018/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001019 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001020 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001021
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001022static int
Victor Stinner95872862011-03-07 18:20:56 +01001023init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001026 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001027
Victor Stinner5eb4f592013-11-14 22:38:52 +01001028 mod = _PyImport_FindExtensionObject(name, name);
1029 if (PyErr_Occurred())
1030 return -1;
1031 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 for (p = PyImport_Inittab; p->name != NULL; p++) {
1035 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001036 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001037 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (p->initfunc == NULL) {
1039 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001040 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 name);
1042 return -1;
1043 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 mod = (*p->initfunc)();
1045 if (mod == 0)
1046 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001047 /* Remember pointer to module init function. */
1048 def = PyModule_GetDef(mod);
1049 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001050 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 return -1;
1052 /* FixupExtension has put the module into sys.modules,
1053 so we can release our own reference. */
1054 Py_DECREF(mod);
1055 return 1;
1056 }
1057 }
1058 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001059}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001060
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001061
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001062/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001063
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001064static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001065find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001066{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001067 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001068
Victor Stinner53dc7352011-03-20 01:50:21 +01001069 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 for (p = PyImport_FrozenModules; ; p++) {
1073 if (p->name == NULL)
1074 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001075 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 break;
1077 }
1078 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001079}
1080
Guido van Rossum79f25d91997-04-29 20:08:16 +00001081static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001082get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001083{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001084 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (p == NULL) {
1088 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001089 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 name);
1091 return NULL;
1092 }
1093 if (p->code == NULL) {
1094 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001095 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 name);
1097 return NULL;
1098 }
1099 size = p->size;
1100 if (size < 0)
1101 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001102 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001103}
1104
Brett Cannon8d110132009-03-15 02:20:16 +00001105static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001106is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001107{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001108 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (p == NULL) {
1112 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001113 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 name);
1115 return NULL;
1116 }
Brett Cannon8d110132009-03-15 02:20:16 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 if (size < 0)
1121 Py_RETURN_TRUE;
1122 else
1123 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001124}
1125
1126
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001127/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001128 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001129 an exception set if the initialization failed.
1130 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001131
1132int
Victor Stinner53dc7352011-03-20 01:50:21 +01001133PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001134{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001135 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001136 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 int ispackage;
1138 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001139
Victor Stinner53dc7352011-03-20 01:50:21 +01001140 p = find_frozen(name);
1141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (p == NULL)
1143 return 0;
1144 if (p->code == NULL) {
1145 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001146 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 name);
1148 return -1;
1149 }
1150 size = p->size;
1151 ispackage = (size < 0);
1152 if (ispackage)
1153 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001154 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (co == NULL)
1156 return -1;
1157 if (!PyCode_Check(co)) {
1158 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001159 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 name);
1161 goto err_return;
1162 }
1163 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001164 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001165 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001167 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (m == NULL)
1169 goto err_return;
1170 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001171 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 goto err_return;
1174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 err = PyDict_SetItemString(d, "__path__", l);
1176 Py_DECREF(l);
1177 if (err != 0)
1178 goto err_return;
1179 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001180 d = module_dict_for_exec(name);
1181 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001182 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001183 }
1184 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (m == NULL)
1186 goto err_return;
1187 Py_DECREF(co);
1188 Py_DECREF(m);
1189 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001190err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 Py_DECREF(co);
1192 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001193}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001194
Victor Stinner53dc7352011-03-20 01:50:21 +01001195int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001196PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001197{
1198 PyObject *nameobj;
1199 int ret;
1200 nameobj = PyUnicode_InternFromString(name);
1201 if (nameobj == NULL)
1202 return -1;
1203 ret = PyImport_ImportFrozenModuleObject(nameobj);
1204 Py_DECREF(nameobj);
1205 return ret;
1206}
1207
Guido van Rossum74e6a111994-08-29 12:54:38 +00001208
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001209/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001210 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001211
Guido van Rossum79f25d91997-04-29 20:08:16 +00001212PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001213PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyObject *pname;
1216 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 pname = PyUnicode_FromString(name);
1219 if (pname == NULL)
1220 return NULL;
1221 result = PyImport_Import(pname);
1222 Py_DECREF(pname);
1223 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001224}
1225
Christian Heimes072c0f12008-01-03 23:01:04 +00001226/* Import a module without blocking
1227 *
1228 * At first it tries to fetch the module from sys.modules. If the module was
1229 * never loaded before it loads it with PyImport_ImportModule() unless another
1230 * thread holds the import lock. In the latter case the function raises an
1231 * ImportError instead of blocking.
1232 *
1233 * Returns the module object with incremented ref count.
1234 */
1235PyObject *
1236PyImport_ImportModuleNoBlock(const char *name)
1237{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001238 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001239}
1240
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001241
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001242/* Remove importlib frames from the traceback,
1243 * except in Verbose mode. */
1244static void
1245remove_importlib_frames(void)
1246{
1247 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001248 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001249 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001250 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001251 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001252 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001253
1254 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001255 from the traceback. We always trim chunks
1256 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001257
1258 PyErr_Fetch(&exception, &value, &base_tb);
1259 if (!exception || Py_VerboseFlag)
1260 goto done;
1261 if (PyType_IsSubtype((PyTypeObject *) exception,
1262 (PyTypeObject *) PyExc_ImportError))
1263 always_trim = 1;
1264
1265 prev_link = &base_tb;
1266 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001267 while (tb != NULL) {
1268 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1269 PyObject *next = (PyObject *) traceback->tb_next;
1270 PyFrameObject *frame = traceback->tb_frame;
1271 PyCodeObject *code = frame->f_code;
1272 int now_in_importlib;
1273
1274 assert(PyTraceBack_Check(tb));
1275 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1276 code->co_filename,
1277 importlib_filename) == 0);
1278 if (now_in_importlib && !in_importlib) {
1279 /* This is the link to this chunk of importlib tracebacks */
1280 outer_link = prev_link;
1281 }
1282 in_importlib = now_in_importlib;
1283
1284 if (in_importlib &&
1285 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001286 PyUnicode_CompareWithASCIIString(code->co_name,
1287 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001288 PyObject *tmp = *outer_link;
1289 *outer_link = next;
1290 Py_XINCREF(next);
1291 Py_DECREF(tmp);
1292 prev_link = outer_link;
1293 }
1294 else {
1295 prev_link = (PyObject **) &traceback->tb_next;
1296 }
1297 tb = next;
1298 }
1299done:
1300 PyErr_Restore(exception, value, base_tb);
1301}
1302
1303
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001304PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001305PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1306 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001307 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001308{
Brett Cannonfd074152012-04-14 14:10:13 -04001309 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001310 _Py_IDENTIFIER(__spec__);
1311 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001312 _Py_IDENTIFIER(__package__);
1313 _Py_IDENTIFIER(__path__);
1314 _Py_IDENTIFIER(__name__);
1315 _Py_IDENTIFIER(_find_and_load);
1316 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001317 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001318 _Py_static_string(single_dot, ".");
1319 PyObject *abs_name = NULL;
1320 PyObject *builtins_import = NULL;
1321 PyObject *final_mod = NULL;
1322 PyObject *mod = NULL;
1323 PyObject *package = NULL;
1324 PyObject *globals = NULL;
1325 PyObject *fromlist = NULL;
1326 PyInterpreterState *interp = PyThreadState_GET()->interp;
1327
1328 /* Make sure to use default values so as to not have
1329 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1330 NULL argument. */
1331 if (given_globals == NULL) {
1332 globals = PyDict_New();
1333 if (globals == NULL) {
1334 goto error;
1335 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 }
Brett Cannonfd074152012-04-14 14:10:13 -04001337 else {
1338 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001339 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001340 if (level > 0 && !PyDict_Check(given_globals)) {
1341 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1342 goto error;
1343 }
1344 globals = given_globals;
1345 Py_INCREF(globals);
1346 }
1347
1348 if (given_fromlist == NULL) {
1349 fromlist = PyList_New(0);
1350 if (fromlist == NULL) {
1351 goto error;
1352 }
1353 }
1354 else {
1355 fromlist = given_fromlist;
1356 Py_INCREF(fromlist);
1357 }
1358 if (name == NULL) {
1359 PyErr_SetString(PyExc_ValueError, "Empty module name");
1360 goto error;
1361 }
1362
1363 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1364 for added performance. */
1365
1366 if (!PyUnicode_Check(name)) {
1367 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1368 goto error;
1369 }
1370 else if (PyUnicode_READY(name) < 0) {
1371 goto error;
1372 }
1373 if (level < 0) {
1374 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1375 goto error;
1376 }
1377 else if (level > 0) {
1378 package = _PyDict_GetItemId(globals, &PyId___package__);
1379 if (package != NULL && package != Py_None) {
1380 Py_INCREF(package);
1381 if (!PyUnicode_Check(package)) {
1382 PyErr_SetString(PyExc_TypeError, "package must be a string");
1383 goto error;
1384 }
1385 }
1386 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001387 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001388 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001389 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001390 goto error;
1391 }
1392 else if (!PyUnicode_Check(package)) {
1393 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1394 }
1395 Py_INCREF(package);
1396
1397 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001398 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001399 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1400 if (borrowed_dot == NULL) {
1401 goto error;
1402 }
Brett Cannon740fce02012-04-14 14:23:49 -04001403 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001404 Py_DECREF(package);
1405 if (partition == NULL) {
1406 goto error;
1407 }
1408 package = PyTuple_GET_ITEM(partition, 0);
1409 Py_INCREF(package);
1410 Py_DECREF(partition);
1411 }
1412 }
1413
1414 if (PyDict_GetItem(interp->modules, package) == NULL) {
1415 PyErr_Format(PyExc_SystemError,
1416 "Parent module %R not loaded, cannot perform relative "
1417 "import", package);
1418 goto error;
1419 }
1420 }
1421 else { /* level == 0 */
1422 if (PyUnicode_GET_LENGTH(name) == 0) {
1423 PyErr_SetString(PyExc_ValueError, "Empty module name");
1424 goto error;
1425 }
1426 package = Py_None;
1427 Py_INCREF(package);
1428 }
1429
1430 if (level > 0) {
1431 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1432 PyObject *base = NULL;
1433 int level_up = 1;
1434
1435 for (level_up = 1; level_up < level; level_up += 1) {
1436 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1437 if (last_dot == -2) {
1438 goto error;
1439 }
1440 else if (last_dot == -1) {
1441 PyErr_SetString(PyExc_ValueError,
1442 "attempted relative import beyond top-level "
1443 "package");
1444 goto error;
1445 }
1446 }
Victor Stinner22af2592013-11-13 12:11:36 +01001447
Brett Cannonfd074152012-04-14 14:10:13 -04001448 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001449 if (base == NULL)
1450 goto error;
1451
Brett Cannonfd074152012-04-14 14:10:13 -04001452 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001453 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001454
1455 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001456 seq = PyTuple_Pack(2, base, name);
1457 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001458 if (borrowed_dot == NULL || seq == NULL) {
1459 goto error;
1460 }
1461
1462 abs_name = PyUnicode_Join(borrowed_dot, seq);
1463 Py_DECREF(seq);
1464 if (abs_name == NULL) {
1465 goto error;
1466 }
1467 }
1468 else {
1469 abs_name = base;
1470 }
1471 }
1472 else {
1473 abs_name = name;
1474 Py_INCREF(abs_name);
1475 }
1476
Brian Curtine6b299f2012-04-14 14:19:33 -05001477#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001478 _PyImport_AcquireLock();
1479#endif
1480 /* From this point forward, goto error_with_unlock! */
1481 if (PyDict_Check(globals)) {
1482 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1483 }
1484 if (builtins_import == NULL) {
1485 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1486 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001487 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1488 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001489 }
1490 }
1491 Py_INCREF(builtins_import);
1492
1493 mod = PyDict_GetItem(interp->modules, abs_name);
1494 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001495 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1496 "None in sys.modules", abs_name);
1497 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001498 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001499 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001500 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001501 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001502 goto error_with_unlock;
1503 }
1504 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001505 PyObject *value = NULL;
1506 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001507 int initializing = 0;
1508
Brett Cannonfd074152012-04-14 14:10:13 -04001509 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001510 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001511 __spec__._initializing is true.
1512 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001513 stuffing the new module in sys.modules.
1514 */
Eric Snowb523f842013-11-22 09:05:39 -07001515 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1516 if (spec != NULL) {
1517 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1518 Py_DECREF(spec);
1519 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001520 if (value == NULL)
1521 PyErr_Clear();
1522 else {
1523 initializing = PyObject_IsTrue(value);
1524 Py_DECREF(value);
1525 if (initializing == -1)
1526 PyErr_Clear();
1527 }
1528 if (initializing > 0) {
1529 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001530 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001531 &PyId__lock_unlock_module, abs_name,
1532 NULL);
1533 if (value == NULL)
1534 goto error;
1535 Py_DECREF(value);
1536 }
1537 else {
1538#ifdef WITH_THREAD
1539 if (_PyImport_ReleaseLock() < 0) {
1540 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1541 goto error;
1542 }
1543#endif
1544 }
Brett Cannonfd074152012-04-14 14:10:13 -04001545 }
1546 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001547 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001548 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001549 &PyId__find_and_load, abs_name,
1550 builtins_import, NULL);
1551 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001552 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001553 }
1554 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001555 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001556
1557 if (PyObject_Not(fromlist)) {
1558 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1559 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001560 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001561 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1562
1563 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001564 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001565 }
1566
Brian Curtine6b299f2012-04-14 14:19:33 -05001567 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001568 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001569 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001570 }
1571
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001572 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1573 /* No dot in module name, simple exit */
1574 Py_DECREF(partition);
1575 final_mod = mod;
1576 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001577 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001578 }
1579
Brett Cannonfd074152012-04-14 14:10:13 -04001580 front = PyTuple_GET_ITEM(partition, 0);
1581 Py_INCREF(front);
1582 Py_DECREF(partition);
1583
1584 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001585 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001586 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001587 }
1588 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001589 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1590 PyUnicode_GET_LENGTH(front);
1591 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001592 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001593 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001594 Py_DECREF(front);
1595 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001596 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001597 }
Brett Cannonfd074152012-04-14 14:10:13 -04001598
1599 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001600 if (final_mod == NULL) {
1601 PyErr_Format(PyExc_KeyError,
1602 "%R not in sys.modules as expected",
1603 to_return);
1604 }
1605 else {
1606 Py_INCREF(final_mod);
1607 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001608 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001609 }
1610 }
1611 else {
1612 final_mod = mod;
1613 Py_INCREF(mod);
1614 }
1615 }
1616 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001617 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001618 &PyId__handle_fromlist, mod,
1619 fromlist, builtins_import,
1620 NULL);
1621 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001622 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001623
Brett Cannonfd074152012-04-14 14:10:13 -04001624 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001625#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001626 if (_PyImport_ReleaseLock() < 0) {
1627 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1628 }
1629#endif
1630 error:
1631 Py_XDECREF(abs_name);
1632 Py_XDECREF(builtins_import);
1633 Py_XDECREF(mod);
1634 Py_XDECREF(package);
1635 Py_XDECREF(globals);
1636 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001637 if (final_mod == NULL)
1638 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001639 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001640}
1641
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001642PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001643PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001644 PyObject *fromlist, int level)
1645{
1646 PyObject *nameobj, *mod;
1647 nameobj = PyUnicode_FromString(name);
1648 if (nameobj == NULL)
1649 return NULL;
1650 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1651 fromlist, level);
1652 Py_DECREF(nameobj);
1653 return mod;
1654}
1655
1656
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001657/* Re-import a module of any kind and return its module object, WITH
1658 INCREMENTED REFERENCE COUNT */
1659
Guido van Rossum79f25d91997-04-29 20:08:16 +00001660PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001661PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001662{
Brett Cannon62228db2012-04-29 14:38:11 -04001663 _Py_IDENTIFIER(reload);
1664 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001666 PyObject *imp = PyDict_GetItemString(modules, "imp");
1667 if (imp == NULL) {
1668 imp = PyImport_ImportModule("imp");
1669 if (imp == NULL) {
1670 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 }
Brett Cannon62228db2012-04-29 14:38:11 -04001673 else {
1674 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001676
Brett Cannon62228db2012-04-29 14:38:11 -04001677 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1678 Py_DECREF(imp);
1679 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001680}
1681
1682
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001683/* Higher-level import emulator which emulates the "import" statement
1684 more accurately -- it invokes the __import__() function from the
1685 builtins of the current globals. This means that the import is
1686 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001687 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001688 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001689 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001690 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001691
1692PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001693PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 static PyObject *silly_list = NULL;
1696 static PyObject *builtins_str = NULL;
1697 static PyObject *import_str = NULL;
1698 PyObject *globals = NULL;
1699 PyObject *import = NULL;
1700 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001701 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 /* Initialize constant string objects */
1705 if (silly_list == NULL) {
1706 import_str = PyUnicode_InternFromString("__import__");
1707 if (import_str == NULL)
1708 return NULL;
1709 builtins_str = PyUnicode_InternFromString("__builtins__");
1710 if (builtins_str == NULL)
1711 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001712 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 if (silly_list == NULL)
1714 return NULL;
1715 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 /* Get the builtins from current globals */
1718 globals = PyEval_GetGlobals();
1719 if (globals != NULL) {
1720 Py_INCREF(globals);
1721 builtins = PyObject_GetItem(globals, builtins_str);
1722 if (builtins == NULL)
1723 goto err;
1724 }
1725 else {
1726 /* No globals -- use standard builtins, and fake globals */
1727 builtins = PyImport_ImportModuleLevel("builtins",
1728 NULL, NULL, NULL, 0);
1729 if (builtins == NULL)
1730 return NULL;
1731 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1732 if (globals == NULL)
1733 goto err;
1734 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* Get the __import__ function from the builtins */
1737 if (PyDict_Check(builtins)) {
1738 import = PyObject_GetItem(builtins, import_str);
1739 if (import == NULL)
1740 PyErr_SetObject(PyExc_KeyError, import_str);
1741 }
1742 else
1743 import = PyObject_GetAttr(builtins, import_str);
1744 if (import == NULL)
1745 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001748 Always use absolute import here.
1749 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1751 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001752 if (r == NULL)
1753 goto err;
1754 Py_DECREF(r);
1755
1756 modules = PyImport_GetModuleDict();
1757 r = PyDict_GetItem(modules, module_name);
1758 if (r != NULL)
1759 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001760
1761 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 Py_XDECREF(globals);
1763 Py_XDECREF(builtins);
1764 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001767}
1768
Brett Cannon4caa61d2014-01-09 19:03:32 -05001769/*[clinic input]
1770_imp.extension_suffixes
1771
1772Returns the list of file suffixes used to identify extension modules.
1773[clinic start generated code]*/
1774
Brett Cannon4caa61d2014-01-09 19:03:32 -05001775static PyObject *
1776_imp_extension_suffixes_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001777/*[clinic end generated code: output=d44c1566ef362229 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001780 const char *suffix;
1781 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 list = PyList_New(0);
1784 if (list == NULL)
1785 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001786#ifdef HAVE_DYNAMIC_LOADING
1787 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1788 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (item == NULL) {
1790 Py_DECREF(list);
1791 return NULL;
1792 }
1793 if (PyList_Append(list, item) < 0) {
1794 Py_DECREF(list);
1795 Py_DECREF(item);
1796 return NULL;
1797 }
1798 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001799 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 }
Brett Cannon2657df42012-05-04 15:20:40 -04001801#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001803}
1804
Brett Cannon4caa61d2014-01-09 19:03:32 -05001805/*[clinic input]
1806_imp.init_builtin
1807
1808 name: unicode
1809 /
1810
1811Initializes a built-in module.
1812[clinic start generated code]*/
1813
Brett Cannon4caa61d2014-01-09 19:03:32 -05001814static PyObject *
1815_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001816/*[clinic end generated code: output=1868f473685f6d67 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 int ret;
1819 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 ret = init_builtin(name);
1822 if (ret < 0)
1823 return NULL;
1824 if (ret == 0) {
1825 Py_INCREF(Py_None);
1826 return Py_None;
1827 }
Victor Stinner95872862011-03-07 18:20:56 +01001828 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 Py_XINCREF(m);
1830 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001831}
1832
Brett Cannon4caa61d2014-01-09 19:03:32 -05001833/*[clinic input]
1834_imp.init_frozen
1835
1836 name: unicode
1837 /
1838
1839Initializes a frozen module.
1840[clinic start generated code]*/
1841
Brett Cannon4caa61d2014-01-09 19:03:32 -05001842static PyObject *
1843_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001844/*[clinic end generated code: output=a9de493bdd711878 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 int ret;
1847 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001848
Victor Stinner53dc7352011-03-20 01:50:21 +01001849 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (ret < 0)
1851 return NULL;
1852 if (ret == 0) {
1853 Py_INCREF(Py_None);
1854 return Py_None;
1855 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001856 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 Py_XINCREF(m);
1858 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001859}
1860
Brett Cannon4caa61d2014-01-09 19:03:32 -05001861/*[clinic input]
1862_imp.get_frozen_object
1863
1864 name: unicode
1865 /
1866
1867Create a code object for a frozen module.
1868[clinic start generated code]*/
1869
Brett Cannon4caa61d2014-01-09 19:03:32 -05001870static PyObject *
1871_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001872/*[clinic end generated code: output=3114c970a47f2e3c input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001875}
1876
Brett Cannon4caa61d2014-01-09 19:03:32 -05001877/*[clinic input]
1878_imp.is_frozen_package
1879
1880 name: unicode
1881 /
1882
1883Returns True if the module name is of a frozen package.
1884[clinic start generated code]*/
1885
Brett Cannon4caa61d2014-01-09 19:03:32 -05001886static PyObject *
1887_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001888/*[clinic end generated code: output=3e4cab802b56d649 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001891}
1892
Brett Cannon4caa61d2014-01-09 19:03:32 -05001893/*[clinic input]
1894_imp.is_builtin
1895
1896 name: unicode
1897 /
1898
1899Returns True if the module name corresponds to a built-in module.
1900[clinic start generated code]*/
1901
Guido van Rossum79f25d91997-04-29 20:08:16 +00001902static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001903_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001904/*[clinic end generated code: output=2deec9cac6fb9a7e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001905{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001906 return PyLong_FromLong(is_builtin(name));
1907}
1908
1909/*[clinic input]
1910_imp.is_frozen
1911
1912 name: unicode
1913 /
1914
1915Returns True if the module name corresponds to a frozen module.
1916[clinic start generated code]*/
1917
Brett Cannon4caa61d2014-01-09 19:03:32 -05001918static PyObject *
1919_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001920/*[clinic end generated code: output=7de8e260c8e36aed input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001921{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001922 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 p = find_frozen(name);
1925 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001926}
1927
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001928#ifdef HAVE_DYNAMIC_LOADING
1929
Brett Cannon4caa61d2014-01-09 19:03:32 -05001930/*[clinic input]
1931_imp.load_dynamic
1932
1933 name: unicode
1934 path: fs_unicode
1935 file: object = NULL
1936 /
1937
1938Loads an extension module.
1939[clinic start generated code]*/
1940
Brett Cannon4caa61d2014-01-09 19:03:32 -05001941static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001942_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path,
1943 PyObject *file)
1944/*[clinic end generated code: output=e84e5f7f0f39bc54 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001945{
1946 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001947 FILE *fp;
1948
Brett Cannon4caa61d2014-01-09 19:03:32 -05001949 if (file != NULL) {
1950 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001951 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05001952 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001954 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001956 else
1957 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001958 mod = _PyImport_LoadDynamicModule(name, path, fp);
1959 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (fp)
1961 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001962 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001963}
1964
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001965#endif /* HAVE_DYNAMIC_LOADING */
1966
Larry Hastings7726ac92014-01-31 22:03:12 -08001967/*[clinic input]
1968dump buffer
1969[clinic start generated code]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -04001970/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
Larry Hastings7726ac92014-01-31 22:03:12 -08001971
Barry Warsaw28a691b2010-04-17 00:19:56 +00001972
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001973PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04001974"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001975
Guido van Rossum79f25d91997-04-29 20:08:16 +00001976static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05001977 _IMP_EXTENSION_SUFFIXES_METHODDEF
1978 _IMP_LOCK_HELD_METHODDEF
1979 _IMP_ACQUIRE_LOCK_METHODDEF
1980 _IMP_RELEASE_LOCK_METHODDEF
1981 _IMP_GET_FROZEN_OBJECT_METHODDEF
1982 _IMP_IS_FROZEN_PACKAGE_METHODDEF
1983 _IMP_INIT_BUILTIN_METHODDEF
1984 _IMP_INIT_FROZEN_METHODDEF
1985 _IMP_IS_BUILTIN_METHODDEF
1986 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05001987 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988 _IMP__FIX_CO_FILENAME_METHODDEF
1989 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001990};
1991
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001992
Martin v. Löwis1a214512008-06-11 05:26:20 +00001993static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04001995 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 doc_imp,
1997 0,
1998 imp_methods,
1999 NULL,
2000 NULL,
2001 NULL,
2002 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002003};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002004
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002005PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002006PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 m = PyModule_Create(&impmodule);
2011 if (m == NULL)
2012 goto failure;
2013 d = PyModule_GetDict(m);
2014 if (d == NULL)
2015 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002018 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_XDECREF(m);
2020 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002021}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002022
2023
Guido van Rossumb18618d2000-05-03 23:44:39 +00002024/* API for embedding applications that want to add their own entries
2025 to the table of built-in modules. This should normally be called
2026 *before* Py_Initialize(). When the table resize fails, -1 is
2027 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002028
2029 After a similar function by Just van Rossum. */
2030
2031int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002032PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 static struct _inittab *our_copy = NULL;
2035 struct _inittab *p;
2036 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* Count the number of entries in both tables */
2039 for (n = 0; newtab[n].name != NULL; n++)
2040 ;
2041 if (n == 0)
2042 return 0; /* Nothing to do */
2043 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2044 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* Allocate new memory for the combined table */
2047 p = our_copy;
2048 PyMem_RESIZE(p, struct _inittab, i+n+1);
2049 if (p == NULL)
2050 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* Copy the tables into the new memory */
2053 if (our_copy != PyImport_Inittab)
2054 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2055 PyImport_Inittab = our_copy = p;
2056 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002059}
2060
2061/* Shorthand to add a single entry given a name and a function */
2062
2063int
Brett Cannona826f322009-04-02 03:41:46 +00002064PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002069
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002070 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002074}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002075
2076#ifdef __cplusplus
2077}
2078#endif