blob: 54654afd14368e088e2614610ebd5da1fcae985b [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 if (import_lock != NULL)
213 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000214 if (import_lock_level > 1) {
215 /* Forked as a side effect of import */
216 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500217 /* The following could fail if the lock is already held, but forking as
218 a side-effect of an import is a) rare, b) nuts, and c) difficult to
219 do thanks to the lock only being held when doing individual module
220 locks per import. */
221 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000222 import_lock_thread = me;
223 import_lock_level--;
224 } else {
225 import_lock_thread = -1;
226 import_lock_level = 0;
227 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000228}
229
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000230#endif
231
Brett Cannon4caa61d2014-01-09 19:03:32 -0500232/*[clinic input]
233_imp.lock_held
234
235Return True if the import lock is currently held, else False.
236
237On platforms without threads, return False.
238[clinic start generated code]*/
239
Brett Cannon4caa61d2014-01-09 19:03:32 -0500240static PyObject *
241_imp_lock_held_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400242/*[clinic end generated code: output=d7a8cc3a5169081a input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000243{
Tim Peters69232342001-08-30 05:16:13 +0000244#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000246#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000248#endif
249}
250
Brett Cannon4caa61d2014-01-09 19:03:32 -0500251/*[clinic input]
252_imp.acquire_lock
253
254Acquires the interpreter's import lock for the current thread.
255
256This lock should be used by import hooks to ensure thread-safety when importing
257modules. On platforms without threads, this function does nothing.
258[clinic start generated code]*/
259
Brett Cannon4caa61d2014-01-09 19:03:32 -0500260static PyObject *
261_imp_acquire_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400262/*[clinic end generated code: output=cc143b1d16422cae input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000263{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000264#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000266#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_INCREF(Py_None);
268 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000269}
270
Brett Cannon4caa61d2014-01-09 19:03:32 -0500271/*[clinic input]
272_imp.release_lock
273
274Release the interpreter's import lock.
275
276On platforms without threads, this function does nothing.
277[clinic start generated code]*/
278
Brett Cannon4caa61d2014-01-09 19:03:32 -0500279static PyObject *
280_imp_release_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400281/*[clinic end generated code: output=74d28e38ebe2b224 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000282{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000283#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 if (_PyImport_ReleaseLock() < 0) {
285 PyErr_SetString(PyExc_RuntimeError,
286 "not holding the import lock");
287 return NULL;
288 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000289#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 Py_INCREF(Py_None);
291 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000292}
293
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100294void
295_PyImport_Fini(void)
296{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200297 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100298#ifdef WITH_THREAD
299 if (import_lock != NULL) {
300 PyThread_free_lock(import_lock);
301 import_lock = NULL;
302 }
303#endif
304}
305
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306/* Helper for sys */
307
308PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000309PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 PyInterpreterState *interp = PyThreadState_GET()->interp;
312 if (interp->modules == NULL)
313 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
314 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315}
316
Guido van Rossum3f5da241990-12-20 15:06:42 +0000317
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000318/* List of names to clear in sys */
319static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 "path", "argv", "ps1", "ps2",
321 "last_type", "last_value", "last_traceback",
322 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200323 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 /* misc stuff */
325 "flags", "float_info",
326 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000327};
328
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000329static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 "stdin", "__stdin__",
331 "stdout", "__stdout__",
332 "stderr", "__stderr__",
333 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000334};
335
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000336/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000337
Guido van Rossum3f5da241990-12-20 15:06:42 +0000338void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000339PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000340{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200341 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PyObject *key, *value, *dict;
343 PyInterpreterState *interp = PyThreadState_GET()->interp;
344 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200345 PyObject *weaklist = NULL;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200346 char **p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (modules == NULL)
349 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* Delete some special variables first. These are common
352 places where user values hide and people complain when their
353 destructors fail. Since the modules containing them are
354 deleted *last* of all, they would come too late in the normal
355 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000356
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200357 /* XXX Perhaps these precautions are obsolete. Who knows? */
358
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200359 if (Py_VerboseFlag)
360 PySys_WriteStderr("# clear builtins._\n");
361 PyDict_SetItemString(interp->builtins, "_", Py_None);
362
363 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200365 PySys_WriteStderr("# clear sys.%s\n", *p);
366 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200368 for (p = sys_files; *p != NULL; p+=2) {
369 if (Py_VerboseFlag)
370 PySys_WriteStderr("# restore sys.%s\n", *p);
371 value = PyDict_GetItemString(interp->sysdict, *(p+1));
372 if (value == NULL)
373 value = Py_None;
374 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000376
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200377 /* We prepare a list which will receive (name, weakref) tuples of
378 modules when they are removed from sys.modules. The name is used
379 for diagnosis messages (in verbose mode), while the weakref helps
380 detect those modules which have been held alive. */
381 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200382 if (weaklist == NULL)
383 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200384
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200385#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200386 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200387 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
388 if (name && wr) { \
389 PyObject *tup = PyTuple_Pack(2, name, wr); \
390 PyList_Append(weaklist, tup); \
391 Py_XDECREF(tup); \
392 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200393 Py_XDECREF(wr); \
394 if (PyErr_Occurred()) \
395 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000397
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200398 /* Remove all modules from sys.modules, hoping that garbage collection
399 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 pos = 0;
401 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200402 if (PyModule_Check(value)) {
403 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200404 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200405 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 PyDict_SetItem(modules, key, Py_None);
407 }
408 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000409
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200410 /* Clear the modules dict. */
411 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200412 /* Restore the original builtins dict, to ensure that any
413 user data gets cleared. */
414 dict = PyDict_Copy(interp->builtins);
415 if (dict == NULL)
416 PyErr_Clear();
417 PyDict_Clear(interp->builtins);
418 if (PyDict_Update(interp->builtins, interp->builtins_copy))
419 PyErr_Clear();
420 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200421 /* Clear module dict copies stored in the interpreter state */
422 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200423 /* Collect references */
424 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200425 /* Dump GC stats before it's too late, since it uses the warnings
426 machinery. */
427 _PyGC_DumpShutdownStats();
428
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200429 /* Now, if there are any modules left alive, clear their globals to
430 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200431 up here, since they are kept alive in the interpreter state.
432
433 The special treatment of "builtins" here is because even
434 when it's not referenced as a module, its dictionary is
435 referenced by almost every module's __builtins__. Since
436 deleting a module clears its dictionary (even if there are
437 references left to it), we need to delete the "builtins"
438 module last. Likewise, we don't delete sys until the very
439 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200440 if (weaklist != NULL) {
441 Py_ssize_t i, n;
442 n = PyList_GET_SIZE(weaklist);
443 for (i = 0; i < n; i++) {
444 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200445 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200446 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
447 if (mod == Py_None)
448 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200449 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200450 dict = PyModule_GetDict(mod);
451 if (dict == interp->builtins || dict == interp->sysdict)
452 continue;
453 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200454 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200455 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200456 _PyModule_Clear(mod);
457 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200458 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200459 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000461
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200462 /* Next, delete sys and builtins (in that order) */
463 if (Py_VerboseFlag)
464 PySys_FormatStderr("# cleanup[3] wiping sys\n");
465 _PyModule_ClearDict(interp->sysdict);
466 if (Py_VerboseFlag)
467 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
468 _PyModule_ClearDict(interp->builtins);
469
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200470 /* Clear and delete the modules directory. Actual modules will
471 still be there only if imported during the execution of some
472 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 interp->modules = NULL;
474 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200475
476 /* Once more */
477 _PyGC_CollectNoFail();
478
479#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000480}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000481
482
Barry Warsaw28a691b2010-04-17 00:19:56 +0000483/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000484
485long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000486PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000487{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200488 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400489 PyInterpreterState *interp = PyThreadState_Get()->interp;
490 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
491 "_RAW_MAGIC_NUMBER");
492 if (pyc_magic == NULL)
493 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200494 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700495 Py_DECREF(pyc_magic);
496 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000497}
498
499
Brett Cannon3adc7b72012-07-09 14:22:12 -0400500extern const char * _PySys_ImplCacheTag;
501
Barry Warsaw28a691b2010-04-17 00:19:56 +0000502const char *
503PyImport_GetMagicTag(void)
504{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400505 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000506}
507
Brett Cannon98979b82012-07-02 15:13:11 -0400508
Guido van Rossum25ce5661997-08-02 03:10:38 +0000509/* Magic for extension modules (built-in as well as dynamically
510 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200511 once, we keep a static dictionary 'extensions' keyed by the tuple
512 (module name, module name) (for built-in modules) or by
513 (filename, module name) (for dynamically loaded modules), containing these
514 modules. A copy of the module's dictionary is stored by calling
515 _PyImport_FixupExtensionObject() immediately after the module initialization
516 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100517 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000518
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000519 Modules which do support multiple initialization set their m_size
520 field to a non-negative number (indicating the size of the
521 module-specific state). They are still recorded in the extensions
522 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000523*/
524
525int
Victor Stinner95872862011-03-07 18:20:56 +0100526_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
527 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000528{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500529 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500531 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (extensions == NULL) {
533 extensions = PyDict_New();
534 if (extensions == NULL)
535 return -1;
536 }
537 if (mod == NULL || !PyModule_Check(mod)) {
538 PyErr_BadInternalCall();
539 return -1;
540 }
541 def = PyModule_GetDef(mod);
542 if (!def) {
543 PyErr_BadInternalCall();
544 return -1;
545 }
546 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100547 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return -1;
549 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100550 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return -1;
552 }
553 if (def->m_size == -1) {
554 if (def->m_base.m_copy) {
555 /* Somebody already imported the module,
556 likely under a different name.
557 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200558 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 }
560 dict = PyModule_GetDict(mod);
561 if (dict == NULL)
562 return -1;
563 def->m_base.m_copy = PyDict_Copy(dict);
564 if (def->m_base.m_copy == NULL)
565 return -1;
566 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500567 key = PyTuple_Pack(2, filename, name);
568 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200569 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500570 res = PyDict_SetItem(extensions, key, (PyObject *)def);
571 Py_DECREF(key);
572 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200573 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575}
576
Victor Stinner49d3f252010-10-17 01:24:53 +0000577int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300578_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000579{
580 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100581 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100582 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100583 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000584 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100585 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
586 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000587 return res;
588}
589
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100591_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500593 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 PyModuleDef* def;
595 if (extensions == NULL)
596 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500597 key = PyTuple_Pack(2, filename, name);
598 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200599 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500600 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
601 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (def == NULL)
603 return NULL;
604 if (def->m_size == -1) {
605 /* Module does not support repeated initialization */
606 if (def->m_base.m_copy == NULL)
607 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100608 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (mod == NULL)
610 return NULL;
611 mdict = PyModule_GetDict(mod);
612 if (mdict == NULL)
613 return NULL;
614 if (PyDict_Update(mdict, def->m_base.m_copy))
615 return NULL;
616 }
617 else {
618 if (def->m_base.m_init == NULL)
619 return NULL;
620 mod = def->m_base.m_init();
621 if (mod == NULL)
622 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200623 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
624 Py_DECREF(mod);
625 return NULL;
626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 Py_DECREF(mod);
628 }
629 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100630 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 Py_DECREF(mod);
632 return NULL;
633 }
634 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100635 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 name, filename);
637 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000638
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000639}
640
Victor Stinner49d3f252010-10-17 01:24:53 +0000641PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000642_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000643{
Victor Stinner95872862011-03-07 18:20:56 +0100644 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100645 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100646 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000647 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100648 res = _PyImport_FindExtensionObject(nameobj, nameobj);
649 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000650 return res;
651}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000652
653/* Get the module object corresponding to a module name.
654 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000655 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000656 Because the former action is most common, THIS DOES NOT RETURN A
657 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658
Guido van Rossum79f25d91997-04-29 20:08:16 +0000659PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000660PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *modules = PyImport_GetModuleDict();
663 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000664
Victor Stinner27ee0892011-03-04 12:57:09 +0000665 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyModule_Check(m))
667 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000668 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (m == NULL)
670 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000671 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 Py_DECREF(m);
673 return NULL;
674 }
675 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000678}
679
Victor Stinner27ee0892011-03-04 12:57:09 +0000680PyObject *
681PyImport_AddModule(const char *name)
682{
683 PyObject *nameobj, *module;
684 nameobj = PyUnicode_FromString(name);
685 if (nameobj == NULL)
686 return NULL;
687 module = PyImport_AddModuleObject(nameobj);
688 Py_DECREF(nameobj);
689 return module;
690}
691
692
Tim Peters1cd70172004-08-02 03:52:12 +0000693/* Remove name from sys.modules, if it's there. */
694static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000695remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000698 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000700 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 Py_FatalError("import: deleting existing key in"
702 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000703}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000704
Christian Heimes3b06e532008-01-07 20:12:44 +0000705
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000706/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000707 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
708 * removed from sys.modules, to avoid leaving damaged module objects
709 * in sys.modules. The caller may wish to restore the original
710 * module object (if any) in this case; PyImport_ReloadModule is an
711 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000712 *
713 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
714 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000715 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000716PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300717PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return PyImport_ExecCodeModuleWithPathnames(
720 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000721}
722
723PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300724PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 return PyImport_ExecCodeModuleWithPathnames(
727 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000728}
729
730PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300731PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
732 const char *pathname,
733 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000734{
Victor Stinner27ee0892011-03-04 12:57:09 +0000735 PyObject *m = NULL;
736 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
737
738 nameobj = PyUnicode_FromString(name);
739 if (nameobj == NULL)
740 return NULL;
741
Victor Stinner27ee0892011-03-04 12:57:09 +0000742 if (cpathname != NULL) {
743 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
744 if (cpathobj == NULL)
745 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400746 }
747 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000748 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400749
750 if (pathname != NULL) {
751 pathobj = PyUnicode_DecodeFSDefault(pathname);
752 if (pathobj == NULL)
753 goto error;
754 }
755 else if (cpathobj != NULL) {
756 PyInterpreterState *interp = PyThreadState_GET()->interp;
757 _Py_IDENTIFIER(_get_sourcefile);
758
759 if (interp == NULL) {
760 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
761 "no interpreter!");
762 }
763
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -0700764 pathobj = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannona6473f92012-07-13 13:57:03 -0400765 &PyId__get_sourcefile, cpathobj,
766 NULL);
767 if (pathobj == NULL)
768 PyErr_Clear();
769 }
770 else
771 pathobj = NULL;
772
Victor Stinner27ee0892011-03-04 12:57:09 +0000773 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
774error:
775 Py_DECREF(nameobj);
776 Py_XDECREF(pathobj);
777 Py_XDECREF(cpathobj);
778 return m;
779}
780
Brett Cannon18fc4e72014-04-04 10:01:46 -0400781static PyObject *
782module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000783{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400784 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785
Victor Stinner27ee0892011-03-04 12:57:09 +0000786 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (m == NULL)
788 return NULL;
789 /* If the module is being reloaded, we get the old module back
790 and re-use its dict to exec the new code. */
791 d = PyModule_GetDict(m);
792 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
793 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400794 PyEval_GetBuiltins()) != 0) {
795 remove_module(name);
796 return NULL;
797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400799
Eric Snow08197a42014-05-12 17:54:55 -0600800 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400801}
802
803static PyObject *
804exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
805{
806 PyObject *modules = PyImport_GetModuleDict();
807 PyObject *v, *m;
808
809 v = PyEval_EvalCode(code_object, module_dict, module_dict);
810 if (v == NULL) {
811 remove_module(name);
812 return NULL;
813 }
814 Py_DECREF(v);
815
816 if ((m = PyDict_GetItem(modules, name)) == NULL) {
817 PyErr_Format(PyExc_ImportError,
818 "Loaded module %R not found in sys.modules",
819 name);
820 return NULL;
821 }
822
823 Py_INCREF(m);
824
825 return m;
826}
827
828PyObject*
829PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
830 PyObject *cpathname)
831{
Eric Snow08197a42014-05-12 17:54:55 -0600832 PyObject *d, *res;
833 PyInterpreterState *interp = PyThreadState_GET()->interp;
834 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400835
836 d = module_dict_for_exec(name);
837 if (d == NULL) {
838 return NULL;
839 }
840
Eric Snow08197a42014-05-12 17:54:55 -0600841 if (pathname == NULL) {
842 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 }
Eric Snow08197a42014-05-12 17:54:55 -0600844 res = _PyObject_CallMethodIdObjArgs(interp->importlib,
845 &PyId__fix_up_module,
846 d, name, pathname, cpathname, NULL);
847 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600848 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600849 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 }
Eric Snow08197a42014-05-12 17:54:55 -0600851 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000852}
853
854
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000855static void
856update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyObject *constants, *tmp;
859 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (PyUnicode_Compare(co->co_filename, oldname))
862 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 tmp = co->co_filename;
865 co->co_filename = newname;
866 Py_INCREF(co->co_filename);
867 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 constants = co->co_consts;
870 n = PyTuple_GET_SIZE(constants);
871 for (i = 0; i < n; i++) {
872 tmp = PyTuple_GET_ITEM(constants, i);
873 if (PyCode_Check(tmp))
874 update_code_filenames((PyCodeObject *)tmp,
875 oldname, newname);
876 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000877}
878
Victor Stinner2f42ae52011-03-20 00:41:24 +0100879static void
880update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000881{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100882 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000883
Victor Stinner2f42ae52011-03-20 00:41:24 +0100884 if (PyUnicode_Compare(co->co_filename, newname) == 0)
885 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 oldname = co->co_filename;
888 Py_INCREF(oldname);
889 update_code_filenames(co, oldname, newname);
890 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000891}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000892
Brett Cannon4caa61d2014-01-09 19:03:32 -0500893/*[clinic input]
894_imp._fix_co_filename
895
896 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
897 Code object to change.
898
899 path: unicode
900 File path to use.
901 /
902
903Changes code.co_filename to specify the passed-in file path.
904[clinic start generated code]*/
905
Brett Cannon4caa61d2014-01-09 19:03:32 -0500906static PyObject *
907_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400908/*[clinic end generated code: output=7afe5ba6b9d383e4 input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700909
Brett Cannon4caa61d2014-01-09 19:03:32 -0500910{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500911 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700912
913 Py_RETURN_NONE;
914}
915
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000916
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000917/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700918static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000919
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000920
921/* Helper to test for built-in module */
922
923static int
Victor Stinner95872862011-03-07 18:20:56 +0100924is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000925{
Victor Stinner95872862011-03-07 18:20:56 +0100926 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +0100928 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
929 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 if (PyImport_Inittab[i].initfunc == NULL)
931 return -1;
932 else
933 return 1;
934 }
935 }
936 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000937}
938
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000939
Just van Rossum52e14d62002-12-30 22:08:05 +0000940/* Return an importer object for a sys.path/pkg.__path__ item 'p',
941 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000942 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000943 that can handle the path item. Return None if no hook could;
944 this tells our caller it should fall back to the builtin
945 import mechanism. Cache the result in path_importer_cache.
946 Returns a borrowed reference. */
947
948static PyObject *
949get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyObject *importer;
953 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* These conditions are the caller's responsibility: */
956 assert(PyList_Check(path_hooks));
957 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 nhooks = PyList_Size(path_hooks);
960 if (nhooks < 0)
961 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 importer = PyDict_GetItem(path_importer_cache, p);
964 if (importer != NULL)
965 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 /* set path_importer_cache[p] to None to avoid recursion */
968 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
969 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 for (j = 0; j < nhooks; j++) {
972 PyObject *hook = PyList_GetItem(path_hooks, j);
973 if (hook == NULL)
974 return NULL;
975 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
976 if (importer != NULL)
977 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
980 return NULL;
981 }
982 PyErr_Clear();
983 }
984 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400985 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 }
987 if (importer != NULL) {
988 int err = PyDict_SetItem(path_importer_cache, p, importer);
989 Py_DECREF(importer);
990 if (err != 0)
991 return NULL;
992 }
993 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000994}
995
Christian Heimes9cd17752007-11-18 19:35:23 +0000996PyAPI_FUNC(PyObject *)
997PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +0000999
Victor Stinner1e53bba2013-07-16 22:26:05 +02001000 path_importer_cache = PySys_GetObject("path_importer_cache");
1001 path_hooks = PySys_GetObject("path_hooks");
1002 if (path_importer_cache != NULL && path_hooks != NULL) {
1003 importer = get_path_importer(path_importer_cache,
1004 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 }
1006 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1007 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001008}
1009
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001010
Victor Stinner95872862011-03-07 18:20:56 +01001011static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001012
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001013/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001014 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001015 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001016
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001017static int
Victor Stinner95872862011-03-07 18:20:56 +01001018init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001021 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001022
Victor Stinner5eb4f592013-11-14 22:38:52 +01001023 mod = _PyImport_FindExtensionObject(name, name);
1024 if (PyErr_Occurred())
1025 return -1;
1026 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 for (p = PyImport_Inittab; p->name != NULL; p++) {
1030 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001031 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001032 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (p->initfunc == NULL) {
1034 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001035 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 name);
1037 return -1;
1038 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 mod = (*p->initfunc)();
1040 if (mod == 0)
1041 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001042 /* Remember pointer to module init function. */
1043 def = PyModule_GetDef(mod);
1044 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001045 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return -1;
1047 /* FixupExtension has put the module into sys.modules,
1048 so we can release our own reference. */
1049 Py_DECREF(mod);
1050 return 1;
1051 }
1052 }
1053 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001054}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001055
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001056
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001057/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001058
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001059static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001060find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001061{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001062 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001063
Victor Stinner53dc7352011-03-20 01:50:21 +01001064 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 for (p = PyImport_FrozenModules; ; p++) {
1068 if (p->name == NULL)
1069 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001070 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 break;
1072 }
1073 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001074}
1075
Guido van Rossum79f25d91997-04-29 20:08:16 +00001076static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001077get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001078{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001079 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (p == NULL) {
1083 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001084 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 name);
1086 return NULL;
1087 }
1088 if (p->code == NULL) {
1089 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001090 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 name);
1092 return NULL;
1093 }
1094 size = p->size;
1095 if (size < 0)
1096 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001097 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001098}
1099
Brett Cannon8d110132009-03-15 02:20:16 +00001100static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001101is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001102{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001103 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (p == NULL) {
1107 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001108 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 name);
1110 return NULL;
1111 }
Brett Cannon8d110132009-03-15 02:20:16 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (size < 0)
1116 Py_RETURN_TRUE;
1117 else
1118 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001119}
1120
1121
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001122/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001123 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001124 an exception set if the initialization failed.
1125 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001126
1127int
Victor Stinner53dc7352011-03-20 01:50:21 +01001128PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001129{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001130 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001131 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 int ispackage;
1133 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001134
Victor Stinner53dc7352011-03-20 01:50:21 +01001135 p = find_frozen(name);
1136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (p == NULL)
1138 return 0;
1139 if (p->code == NULL) {
1140 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001141 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 name);
1143 return -1;
1144 }
1145 size = p->size;
1146 ispackage = (size < 0);
1147 if (ispackage)
1148 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001149 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (co == NULL)
1151 return -1;
1152 if (!PyCode_Check(co)) {
1153 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001154 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 name);
1156 goto err_return;
1157 }
1158 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001159 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001160 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001162 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (m == NULL)
1164 goto err_return;
1165 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001166 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 goto err_return;
1169 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 err = PyDict_SetItemString(d, "__path__", l);
1171 Py_DECREF(l);
1172 if (err != 0)
1173 goto err_return;
1174 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001175 d = module_dict_for_exec(name);
1176 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001177 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001178 }
1179 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (m == NULL)
1181 goto err_return;
1182 Py_DECREF(co);
1183 Py_DECREF(m);
1184 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001185err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 Py_DECREF(co);
1187 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001188}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001189
Victor Stinner53dc7352011-03-20 01:50:21 +01001190int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001191PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001192{
1193 PyObject *nameobj;
1194 int ret;
1195 nameobj = PyUnicode_InternFromString(name);
1196 if (nameobj == NULL)
1197 return -1;
1198 ret = PyImport_ImportFrozenModuleObject(nameobj);
1199 Py_DECREF(nameobj);
1200 return ret;
1201}
1202
Guido van Rossum74e6a111994-08-29 12:54:38 +00001203
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001204/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001205 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001206
Guido van Rossum79f25d91997-04-29 20:08:16 +00001207PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001208PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyObject *pname;
1211 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 pname = PyUnicode_FromString(name);
1214 if (pname == NULL)
1215 return NULL;
1216 result = PyImport_Import(pname);
1217 Py_DECREF(pname);
1218 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001219}
1220
Christian Heimes072c0f12008-01-03 23:01:04 +00001221/* Import a module without blocking
1222 *
1223 * At first it tries to fetch the module from sys.modules. If the module was
1224 * never loaded before it loads it with PyImport_ImportModule() unless another
1225 * thread holds the import lock. In the latter case the function raises an
1226 * ImportError instead of blocking.
1227 *
1228 * Returns the module object with incremented ref count.
1229 */
1230PyObject *
1231PyImport_ImportModuleNoBlock(const char *name)
1232{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001233 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001234}
1235
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001236
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001237/* Remove importlib frames from the traceback,
1238 * except in Verbose mode. */
1239static void
1240remove_importlib_frames(void)
1241{
1242 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001243 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001244 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001245 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001246 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001247 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001248
1249 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001250 from the traceback. We always trim chunks
1251 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001252
1253 PyErr_Fetch(&exception, &value, &base_tb);
1254 if (!exception || Py_VerboseFlag)
1255 goto done;
1256 if (PyType_IsSubtype((PyTypeObject *) exception,
1257 (PyTypeObject *) PyExc_ImportError))
1258 always_trim = 1;
1259
1260 prev_link = &base_tb;
1261 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001262 while (tb != NULL) {
1263 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1264 PyObject *next = (PyObject *) traceback->tb_next;
1265 PyFrameObject *frame = traceback->tb_frame;
1266 PyCodeObject *code = frame->f_code;
1267 int now_in_importlib;
1268
1269 assert(PyTraceBack_Check(tb));
1270 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1271 code->co_filename,
1272 importlib_filename) == 0);
1273 if (now_in_importlib && !in_importlib) {
1274 /* This is the link to this chunk of importlib tracebacks */
1275 outer_link = prev_link;
1276 }
1277 in_importlib = now_in_importlib;
1278
1279 if (in_importlib &&
1280 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001281 PyUnicode_CompareWithASCIIString(code->co_name,
1282 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001283 PyObject *tmp = *outer_link;
1284 *outer_link = next;
1285 Py_XINCREF(next);
1286 Py_DECREF(tmp);
1287 prev_link = outer_link;
1288 }
1289 else {
1290 prev_link = (PyObject **) &traceback->tb_next;
1291 }
1292 tb = next;
1293 }
1294done:
1295 PyErr_Restore(exception, value, base_tb);
1296}
1297
1298
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001299PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001300PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1301 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001302 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001303{
Brett Cannonfd074152012-04-14 14:10:13 -04001304 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001305 _Py_IDENTIFIER(__spec__);
1306 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001307 _Py_IDENTIFIER(__package__);
1308 _Py_IDENTIFIER(__path__);
1309 _Py_IDENTIFIER(__name__);
1310 _Py_IDENTIFIER(_find_and_load);
1311 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001312 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001313 _Py_static_string(single_dot, ".");
1314 PyObject *abs_name = NULL;
1315 PyObject *builtins_import = NULL;
1316 PyObject *final_mod = NULL;
1317 PyObject *mod = NULL;
1318 PyObject *package = NULL;
1319 PyObject *globals = NULL;
1320 PyObject *fromlist = NULL;
1321 PyInterpreterState *interp = PyThreadState_GET()->interp;
1322
1323 /* Make sure to use default values so as to not have
1324 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1325 NULL argument. */
1326 if (given_globals == NULL) {
1327 globals = PyDict_New();
1328 if (globals == NULL) {
1329 goto error;
1330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 }
Brett Cannonfd074152012-04-14 14:10:13 -04001332 else {
1333 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001334 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001335 if (level > 0 && !PyDict_Check(given_globals)) {
1336 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1337 goto error;
1338 }
1339 globals = given_globals;
1340 Py_INCREF(globals);
1341 }
1342
1343 if (given_fromlist == NULL) {
1344 fromlist = PyList_New(0);
1345 if (fromlist == NULL) {
1346 goto error;
1347 }
1348 }
1349 else {
1350 fromlist = given_fromlist;
1351 Py_INCREF(fromlist);
1352 }
1353 if (name == NULL) {
1354 PyErr_SetString(PyExc_ValueError, "Empty module name");
1355 goto error;
1356 }
1357
1358 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1359 for added performance. */
1360
1361 if (!PyUnicode_Check(name)) {
1362 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1363 goto error;
1364 }
1365 else if (PyUnicode_READY(name) < 0) {
1366 goto error;
1367 }
1368 if (level < 0) {
1369 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1370 goto error;
1371 }
1372 else if (level > 0) {
1373 package = _PyDict_GetItemId(globals, &PyId___package__);
1374 if (package != NULL && package != Py_None) {
1375 Py_INCREF(package);
1376 if (!PyUnicode_Check(package)) {
1377 PyErr_SetString(PyExc_TypeError, "package must be a string");
1378 goto error;
1379 }
1380 }
1381 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001382 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001383 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001384 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001385 goto error;
1386 }
1387 else if (!PyUnicode_Check(package)) {
1388 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1389 }
1390 Py_INCREF(package);
1391
1392 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001393 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001394 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1395 if (borrowed_dot == NULL) {
1396 goto error;
1397 }
Brett Cannon740fce02012-04-14 14:23:49 -04001398 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001399 Py_DECREF(package);
1400 if (partition == NULL) {
1401 goto error;
1402 }
1403 package = PyTuple_GET_ITEM(partition, 0);
1404 Py_INCREF(package);
1405 Py_DECREF(partition);
1406 }
1407 }
1408
1409 if (PyDict_GetItem(interp->modules, package) == NULL) {
1410 PyErr_Format(PyExc_SystemError,
1411 "Parent module %R not loaded, cannot perform relative "
1412 "import", package);
1413 goto error;
1414 }
1415 }
1416 else { /* level == 0 */
1417 if (PyUnicode_GET_LENGTH(name) == 0) {
1418 PyErr_SetString(PyExc_ValueError, "Empty module name");
1419 goto error;
1420 }
1421 package = Py_None;
1422 Py_INCREF(package);
1423 }
1424
1425 if (level > 0) {
1426 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1427 PyObject *base = NULL;
1428 int level_up = 1;
1429
1430 for (level_up = 1; level_up < level; level_up += 1) {
1431 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1432 if (last_dot == -2) {
1433 goto error;
1434 }
1435 else if (last_dot == -1) {
1436 PyErr_SetString(PyExc_ValueError,
1437 "attempted relative import beyond top-level "
1438 "package");
1439 goto error;
1440 }
1441 }
Victor Stinner22af2592013-11-13 12:11:36 +01001442
Brett Cannonfd074152012-04-14 14:10:13 -04001443 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001444 if (base == NULL)
1445 goto error;
1446
Brett Cannonfd074152012-04-14 14:10:13 -04001447 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001448 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001449
1450 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001451 seq = PyTuple_Pack(2, base, name);
1452 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001453 if (borrowed_dot == NULL || seq == NULL) {
1454 goto error;
1455 }
1456
1457 abs_name = PyUnicode_Join(borrowed_dot, seq);
1458 Py_DECREF(seq);
1459 if (abs_name == NULL) {
1460 goto error;
1461 }
1462 }
1463 else {
1464 abs_name = base;
1465 }
1466 }
1467 else {
1468 abs_name = name;
1469 Py_INCREF(abs_name);
1470 }
1471
Brian Curtine6b299f2012-04-14 14:19:33 -05001472#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001473 _PyImport_AcquireLock();
1474#endif
1475 /* From this point forward, goto error_with_unlock! */
1476 if (PyDict_Check(globals)) {
1477 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1478 }
1479 if (builtins_import == NULL) {
1480 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1481 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001482 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1483 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001484 }
1485 }
1486 Py_INCREF(builtins_import);
1487
1488 mod = PyDict_GetItem(interp->modules, abs_name);
1489 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001490 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1491 "None in sys.modules", abs_name);
1492 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001493 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001494 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001495 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001496 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001497 goto error_with_unlock;
1498 }
1499 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001500 PyObject *value = NULL;
1501 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001502 int initializing = 0;
1503
Brett Cannonfd074152012-04-14 14:10:13 -04001504 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001505 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001506 __spec__._initializing is true.
1507 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001508 stuffing the new module in sys.modules.
1509 */
Eric Snowb523f842013-11-22 09:05:39 -07001510 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1511 if (spec != NULL) {
1512 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1513 Py_DECREF(spec);
1514 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001515 if (value == NULL)
1516 PyErr_Clear();
1517 else {
1518 initializing = PyObject_IsTrue(value);
1519 Py_DECREF(value);
1520 if (initializing == -1)
1521 PyErr_Clear();
1522 }
1523 if (initializing > 0) {
1524 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001525 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001526 &PyId__lock_unlock_module, abs_name,
1527 NULL);
1528 if (value == NULL)
1529 goto error;
1530 Py_DECREF(value);
1531 }
1532 else {
1533#ifdef WITH_THREAD
1534 if (_PyImport_ReleaseLock() < 0) {
1535 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1536 goto error;
1537 }
1538#endif
1539 }
Brett Cannonfd074152012-04-14 14:10:13 -04001540 }
1541 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001542 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001543 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001544 &PyId__find_and_load, abs_name,
1545 builtins_import, NULL);
1546 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001547 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001548 }
1549 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001550 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001551
1552 if (PyObject_Not(fromlist)) {
1553 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1554 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001555 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001556 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1557
1558 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001559 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001560 }
1561
Brian Curtine6b299f2012-04-14 14:19:33 -05001562 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001563 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001564 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001565 }
1566
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001567 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1568 /* No dot in module name, simple exit */
1569 Py_DECREF(partition);
1570 final_mod = mod;
1571 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001572 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001573 }
1574
Brett Cannonfd074152012-04-14 14:10:13 -04001575 front = PyTuple_GET_ITEM(partition, 0);
1576 Py_INCREF(front);
1577 Py_DECREF(partition);
1578
1579 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001580 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001581 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001582 }
1583 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001584 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1585 PyUnicode_GET_LENGTH(front);
1586 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001587 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001588 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001589 Py_DECREF(front);
1590 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001591 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001592 }
Brett Cannonfd074152012-04-14 14:10:13 -04001593
1594 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001595 if (final_mod == NULL) {
1596 PyErr_Format(PyExc_KeyError,
1597 "%R not in sys.modules as expected",
1598 to_return);
1599 }
1600 else {
1601 Py_INCREF(final_mod);
1602 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001603 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001604 }
1605 }
1606 else {
1607 final_mod = mod;
1608 Py_INCREF(mod);
1609 }
1610 }
1611 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001612 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001613 &PyId__handle_fromlist, mod,
1614 fromlist, builtins_import,
1615 NULL);
1616 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001617 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001618
Brett Cannonfd074152012-04-14 14:10:13 -04001619 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001620#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001621 if (_PyImport_ReleaseLock() < 0) {
1622 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1623 }
1624#endif
1625 error:
1626 Py_XDECREF(abs_name);
1627 Py_XDECREF(builtins_import);
1628 Py_XDECREF(mod);
1629 Py_XDECREF(package);
1630 Py_XDECREF(globals);
1631 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001632 if (final_mod == NULL)
1633 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001634 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001635}
1636
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001637PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001638PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001639 PyObject *fromlist, int level)
1640{
1641 PyObject *nameobj, *mod;
1642 nameobj = PyUnicode_FromString(name);
1643 if (nameobj == NULL)
1644 return NULL;
1645 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1646 fromlist, level);
1647 Py_DECREF(nameobj);
1648 return mod;
1649}
1650
1651
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001652/* Re-import a module of any kind and return its module object, WITH
1653 INCREMENTED REFERENCE COUNT */
1654
Guido van Rossum79f25d91997-04-29 20:08:16 +00001655PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001656PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001657{
Brett Cannon62228db2012-04-29 14:38:11 -04001658 _Py_IDENTIFIER(reload);
1659 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001661 PyObject *imp = PyDict_GetItemString(modules, "imp");
1662 if (imp == NULL) {
1663 imp = PyImport_ImportModule("imp");
1664 if (imp == NULL) {
1665 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 }
Brett Cannon62228db2012-04-29 14:38:11 -04001668 else {
1669 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001671
Brett Cannon62228db2012-04-29 14:38:11 -04001672 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1673 Py_DECREF(imp);
1674 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001675}
1676
1677
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001678/* Higher-level import emulator which emulates the "import" statement
1679 more accurately -- it invokes the __import__() function from the
1680 builtins of the current globals. This means that the import is
1681 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001682 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001683 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001684 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001685 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001686
1687PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001688PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 static PyObject *silly_list = NULL;
1691 static PyObject *builtins_str = NULL;
1692 static PyObject *import_str = NULL;
1693 PyObject *globals = NULL;
1694 PyObject *import = NULL;
1695 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001696 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 /* Initialize constant string objects */
1700 if (silly_list == NULL) {
1701 import_str = PyUnicode_InternFromString("__import__");
1702 if (import_str == NULL)
1703 return NULL;
1704 builtins_str = PyUnicode_InternFromString("__builtins__");
1705 if (builtins_str == NULL)
1706 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001707 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (silly_list == NULL)
1709 return NULL;
1710 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 /* Get the builtins from current globals */
1713 globals = PyEval_GetGlobals();
1714 if (globals != NULL) {
1715 Py_INCREF(globals);
1716 builtins = PyObject_GetItem(globals, builtins_str);
1717 if (builtins == NULL)
1718 goto err;
1719 }
1720 else {
1721 /* No globals -- use standard builtins, and fake globals */
1722 builtins = PyImport_ImportModuleLevel("builtins",
1723 NULL, NULL, NULL, 0);
1724 if (builtins == NULL)
1725 return NULL;
1726 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1727 if (globals == NULL)
1728 goto err;
1729 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 /* Get the __import__ function from the builtins */
1732 if (PyDict_Check(builtins)) {
1733 import = PyObject_GetItem(builtins, import_str);
1734 if (import == NULL)
1735 PyErr_SetObject(PyExc_KeyError, import_str);
1736 }
1737 else
1738 import = PyObject_GetAttr(builtins, import_str);
1739 if (import == NULL)
1740 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001743 Always use absolute import here.
1744 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1746 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001747 if (r == NULL)
1748 goto err;
1749 Py_DECREF(r);
1750
1751 modules = PyImport_GetModuleDict();
1752 r = PyDict_GetItem(modules, module_name);
1753 if (r != NULL)
1754 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001755
1756 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_XDECREF(globals);
1758 Py_XDECREF(builtins);
1759 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001762}
1763
Brett Cannon4caa61d2014-01-09 19:03:32 -05001764/*[clinic input]
1765_imp.extension_suffixes
1766
1767Returns the list of file suffixes used to identify extension modules.
1768[clinic start generated code]*/
1769
Brett Cannon4caa61d2014-01-09 19:03:32 -05001770static PyObject *
1771_imp_extension_suffixes_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001772/*[clinic end generated code: output=d44c1566ef362229 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001775 const char *suffix;
1776 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 list = PyList_New(0);
1779 if (list == NULL)
1780 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001781#ifdef HAVE_DYNAMIC_LOADING
1782 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1783 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (item == NULL) {
1785 Py_DECREF(list);
1786 return NULL;
1787 }
1788 if (PyList_Append(list, item) < 0) {
1789 Py_DECREF(list);
1790 Py_DECREF(item);
1791 return NULL;
1792 }
1793 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001794 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 }
Brett Cannon2657df42012-05-04 15:20:40 -04001796#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001798}
1799
Brett Cannon4caa61d2014-01-09 19:03:32 -05001800/*[clinic input]
1801_imp.init_builtin
1802
1803 name: unicode
1804 /
1805
1806Initializes a built-in module.
1807[clinic start generated code]*/
1808
Brett Cannon4caa61d2014-01-09 19:03:32 -05001809static PyObject *
1810_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001811/*[clinic end generated code: output=1868f473685f6d67 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 int ret;
1814 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 ret = init_builtin(name);
1817 if (ret < 0)
1818 return NULL;
1819 if (ret == 0) {
1820 Py_INCREF(Py_None);
1821 return Py_None;
1822 }
Victor Stinner95872862011-03-07 18:20:56 +01001823 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 Py_XINCREF(m);
1825 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001826}
1827
Brett Cannon4caa61d2014-01-09 19:03:32 -05001828/*[clinic input]
1829_imp.init_frozen
1830
1831 name: unicode
1832 /
1833
1834Initializes a frozen module.
1835[clinic start generated code]*/
1836
Brett Cannon4caa61d2014-01-09 19:03:32 -05001837static PyObject *
1838_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001839/*[clinic end generated code: output=a9de493bdd711878 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 int ret;
1842 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001843
Victor Stinner53dc7352011-03-20 01:50:21 +01001844 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 if (ret < 0)
1846 return NULL;
1847 if (ret == 0) {
1848 Py_INCREF(Py_None);
1849 return Py_None;
1850 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001851 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 Py_XINCREF(m);
1853 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001854}
1855
Brett Cannon4caa61d2014-01-09 19:03:32 -05001856/*[clinic input]
1857_imp.get_frozen_object
1858
1859 name: unicode
1860 /
1861
1862Create a code object for a frozen module.
1863[clinic start generated code]*/
1864
Brett Cannon4caa61d2014-01-09 19:03:32 -05001865static PyObject *
1866_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001867/*[clinic end generated code: output=3114c970a47f2e3c input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001870}
1871
Brett Cannon4caa61d2014-01-09 19:03:32 -05001872/*[clinic input]
1873_imp.is_frozen_package
1874
1875 name: unicode
1876 /
1877
1878Returns True if the module name is of a frozen package.
1879[clinic start generated code]*/
1880
Brett Cannon4caa61d2014-01-09 19:03:32 -05001881static PyObject *
1882_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001883/*[clinic end generated code: output=3e4cab802b56d649 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001886}
1887
Brett Cannon4caa61d2014-01-09 19:03:32 -05001888/*[clinic input]
1889_imp.is_builtin
1890
1891 name: unicode
1892 /
1893
1894Returns True if the module name corresponds to a built-in module.
1895[clinic start generated code]*/
1896
Guido van Rossum79f25d91997-04-29 20:08:16 +00001897static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001898_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001899/*[clinic end generated code: output=2deec9cac6fb9a7e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001900{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001901 return PyLong_FromLong(is_builtin(name));
1902}
1903
1904/*[clinic input]
1905_imp.is_frozen
1906
1907 name: unicode
1908 /
1909
1910Returns True if the module name corresponds to a frozen module.
1911[clinic start generated code]*/
1912
Brett Cannon4caa61d2014-01-09 19:03:32 -05001913static PyObject *
1914_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001915/*[clinic end generated code: output=7de8e260c8e36aed input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001916{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001917 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 p = find_frozen(name);
1920 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001921}
1922
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001923#ifdef HAVE_DYNAMIC_LOADING
1924
Brett Cannon4caa61d2014-01-09 19:03:32 -05001925/*[clinic input]
1926_imp.load_dynamic
1927
1928 name: unicode
1929 path: fs_unicode
1930 file: object = NULL
1931 /
1932
1933Loads an extension module.
1934[clinic start generated code]*/
1935
Brett Cannon4caa61d2014-01-09 19:03:32 -05001936static PyObject *
1937_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001938/*[clinic end generated code: output=8b7ae431d795e1ba input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001939{
1940 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001941 FILE *fp;
1942
Brett Cannon4caa61d2014-01-09 19:03:32 -05001943 if (file != NULL) {
1944 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001945 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05001946 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001948 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001950 else
1951 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001952 mod = _PyImport_LoadDynamicModule(name, path, fp);
1953 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (fp)
1955 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001956 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001957}
1958
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001959#endif /* HAVE_DYNAMIC_LOADING */
1960
Larry Hastings7726ac92014-01-31 22:03:12 -08001961/*[clinic input]
1962dump buffer
1963[clinic start generated code]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -04001964/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
Larry Hastings7726ac92014-01-31 22:03:12 -08001965
Barry Warsaw28a691b2010-04-17 00:19:56 +00001966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04001968"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001969
Guido van Rossum79f25d91997-04-29 20:08:16 +00001970static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05001971 _IMP_EXTENSION_SUFFIXES_METHODDEF
1972 _IMP_LOCK_HELD_METHODDEF
1973 _IMP_ACQUIRE_LOCK_METHODDEF
1974 _IMP_RELEASE_LOCK_METHODDEF
1975 _IMP_GET_FROZEN_OBJECT_METHODDEF
1976 _IMP_IS_FROZEN_PACKAGE_METHODDEF
1977 _IMP_INIT_BUILTIN_METHODDEF
1978 _IMP_INIT_FROZEN_METHODDEF
1979 _IMP_IS_BUILTIN_METHODDEF
1980 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05001981 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05001982 _IMP__FIX_CO_FILENAME_METHODDEF
1983 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001984};
1985
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001986
Martin v. Löwis1a214512008-06-11 05:26:20 +00001987static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04001989 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 doc_imp,
1991 0,
1992 imp_methods,
1993 NULL,
1994 NULL,
1995 NULL,
1996 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001997};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001998
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001999PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002000PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 m = PyModule_Create(&impmodule);
2005 if (m == NULL)
2006 goto failure;
2007 d = PyModule_GetDict(m);
2008 if (d == NULL)
2009 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002012 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 Py_XDECREF(m);
2014 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002015}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002016
2017
Guido van Rossumb18618d2000-05-03 23:44:39 +00002018/* API for embedding applications that want to add their own entries
2019 to the table of built-in modules. This should normally be called
2020 *before* Py_Initialize(). When the table resize fails, -1 is
2021 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002022
2023 After a similar function by Just van Rossum. */
2024
2025int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002026PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 static struct _inittab *our_copy = NULL;
2029 struct _inittab *p;
2030 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 /* Count the number of entries in both tables */
2033 for (n = 0; newtab[n].name != NULL; n++)
2034 ;
2035 if (n == 0)
2036 return 0; /* Nothing to do */
2037 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2038 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 /* Allocate new memory for the combined table */
2041 p = our_copy;
2042 PyMem_RESIZE(p, struct _inittab, i+n+1);
2043 if (p == NULL)
2044 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* Copy the tables into the new memory */
2047 if (our_copy != PyImport_Inittab)
2048 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2049 PyImport_Inittab = our_copy = p;
2050 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002053}
2054
2055/* Shorthand to add a single entry given a name and a function */
2056
2057int
Brett Cannona826f322009-04-02 03:41:46 +00002058PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002063
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002064 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002068}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002069
2070#ifdef __cplusplus
2071}
2072#endif