blob: 0608924e4333238200fcc7c3342d720d1d14d346 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020011#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000014
Guido van Rossum55a83382000-09-20 20:31:38 +000015#ifdef HAVE_FCNTL_H
16#include <fcntl.h>
17#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000019extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000021
Barry Warsaw28a691b2010-04-17 00:19:56 +000022#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000023
Victor Stinner95872862011-03-07 18:20:56 +010024/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000025static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Guido van Rossum771c6c81997-10-31 18:37:24 +000027/* This table is defined in config.c: */
28extern struct _inittab _PyImport_Inittab[];
29
30struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000031
Victor Stinnerd0296212011-03-14 14:04:10 -040032static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033
Brett Cannon4caa61d2014-01-09 19:03:32 -050034/*[clinic input]
35module _imp
36[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030037/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040038
39#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050040
41/*[python input]
42class fs_unicode_converter(CConverter):
43 type = 'PyObject *'
44 converter = 'PyUnicode_FSDecoder'
45
46[python start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080047/*[python end generated code: output=da39a3ee5e6b4b0d input=9d6786230166006e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050048
Guido van Rossum1ae940a1995-01-02 19:04:15 +000049/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000050
51void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000052_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020054 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040055 initstr = PyUnicode_InternFromString("__init__");
56 if (initstr == NULL)
57 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020058 interp->builtins_copy = PyDict_Copy(interp->builtins);
59 if (interp->builtins_copy == NULL)
60 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061}
62
Guido van Rossum25ce5661997-08-02 03:10:38 +000063void
Just van Rossum52e14d62002-12-30 22:08:05 +000064_PyImportHooks_Init(void)
65{
Brett Cannonfd074152012-04-14 14:10:13 -040066 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000068
Brett Cannonfd074152012-04-14 14:10:13 -040069 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 v = PyList_New(0);
71 if (v == NULL)
72 goto error;
73 err = PySys_SetObject("meta_path", v);
74 Py_DECREF(v);
75 if (err)
76 goto error;
77 v = PyDict_New();
78 if (v == NULL)
79 goto error;
80 err = PySys_SetObject("path_importer_cache", v);
81 Py_DECREF(v);
82 if (err)
83 goto error;
84 path_hooks = PyList_New(0);
85 if (path_hooks == NULL)
86 goto error;
87 err = PySys_SetObject("path_hooks", path_hooks);
88 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000089 error:
Brett Cannonfd074152012-04-14 14:10:13 -040090 PyErr_Print();
91 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020092 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 }
Brett Cannonfd074152012-04-14 14:10:13 -040094 Py_DECREF(path_hooks);
95}
96
97void
98_PyImportZip_Init(void)
99{
100 PyObject *path_hooks, *zimpimport;
101 int err = 0;
102
103 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200104 if (path_hooks == NULL) {
105 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400106 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200107 }
Brett Cannonfd074152012-04-14 14:10:13 -0400108
109 if (Py_VerboseFlag)
110 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 zimpimport = PyImport_ImportModule("zipimport");
113 if (zimpimport == NULL) {
114 PyErr_Clear(); /* No zip import module -- okay */
115 if (Py_VerboseFlag)
116 PySys_WriteStderr("# can't import zipimport\n");
117 }
118 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200119 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200120 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
121 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 Py_DECREF(zimpimport);
123 if (zipimporter == NULL) {
124 PyErr_Clear(); /* No zipimporter object -- okay */
125 if (Py_VerboseFlag)
126 PySys_WriteStderr(
127 "# can't import zipimport.zipimporter\n");
128 }
129 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400130 /* sys.path_hooks.insert(0, zipimporter) */
131 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400133 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 if (Py_VerboseFlag)
137 PySys_WriteStderr(
138 "# installed zipimport hook\n");
139 }
140 }
Brett Cannonfd074152012-04-14 14:10:13 -0400141
142 return;
143
144 error:
145 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400146 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000147}
148
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000149/* Locking primitives to prevent parallel imports of the same module
150 in different threads to return with a partially loaded module.
151 These calls are serialized by the global interpreter lock. */
152
153#ifdef WITH_THREAD
154
Guido van Rossum49b56061998-10-01 20:42:43 +0000155#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156
Guido van Rossum65d5b571998-12-21 19:32:43 +0000157static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000158static long import_lock_thread = -1;
159static int import_lock_level = 0;
160
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000161void
162_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 long me = PyThread_get_thread_ident();
165 if (me == -1)
166 return; /* Too bad */
167 if (import_lock == NULL) {
168 import_lock = PyThread_allocate_lock();
169 if (import_lock == NULL)
170 return; /* Nothing much we can do. */
171 }
172 if (import_lock_thread == me) {
173 import_lock_level++;
174 return;
175 }
176 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
177 {
178 PyThreadState *tstate = PyEval_SaveThread();
179 PyThread_acquire_lock(import_lock, 1);
180 PyEval_RestoreThread(tstate);
181 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100182 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 import_lock_thread = me;
184 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000185}
186
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000187int
188_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 long me = PyThread_get_thread_ident();
191 if (me == -1 || import_lock == NULL)
192 return 0; /* Too bad */
193 if (import_lock_thread != me)
194 return -1;
195 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100196 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 if (import_lock_level == 0) {
198 import_lock_thread = -1;
199 PyThread_release_lock(import_lock);
200 }
201 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000202}
203
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000204/* This function is called from PyOS_AfterFork to ensure that newly
205 created child processes do not share locks with the parent.
206 We now acquire the import lock around fork() calls but on some platforms
207 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000208
209void
210_PyImport_ReInitLock(void)
211{
Christian Heimes418fd742015-04-19 21:08:42 +0200212 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200214 if (import_lock == NULL) {
215 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
216 }
217 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000218 if (import_lock_level > 1) {
219 /* Forked as a side effect of import */
220 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500221 /* The following could fail if the lock is already held, but forking as
222 a side-effect of an import is a) rare, b) nuts, and c) difficult to
223 do thanks to the lock only being held when doing individual module
224 locks per import. */
225 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000226 import_lock_thread = me;
227 import_lock_level--;
228 } else {
229 import_lock_thread = -1;
230 import_lock_level = 0;
231 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000232}
233
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000234#endif
235
Brett Cannon4caa61d2014-01-09 19:03:32 -0500236/*[clinic input]
237_imp.lock_held
238
239Return True if the import lock is currently held, else False.
240
241On platforms without threads, return False.
242[clinic start generated code]*/
243
Brett Cannon4caa61d2014-01-09 19:03:32 -0500244static PyObject *
245_imp_lock_held_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400246/*[clinic end generated code: output=d7a8cc3a5169081a input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000247{
Tim Peters69232342001-08-30 05:16:13 +0000248#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000250#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000252#endif
253}
254
Brett Cannon4caa61d2014-01-09 19:03:32 -0500255/*[clinic input]
256_imp.acquire_lock
257
258Acquires the interpreter's import lock for the current thread.
259
260This lock should be used by import hooks to ensure thread-safety when importing
261modules. On platforms without threads, this function does nothing.
262[clinic start generated code]*/
263
Brett Cannon4caa61d2014-01-09 19:03:32 -0500264static PyObject *
265_imp_acquire_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400266/*[clinic end generated code: output=cc143b1d16422cae input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000267{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000268#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 Py_INCREF(Py_None);
272 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000273}
274
Brett Cannon4caa61d2014-01-09 19:03:32 -0500275/*[clinic input]
276_imp.release_lock
277
278Release the interpreter's import lock.
279
280On platforms without threads, this function does nothing.
281[clinic start generated code]*/
282
Brett Cannon4caa61d2014-01-09 19:03:32 -0500283static PyObject *
284_imp_release_lock_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -0400285/*[clinic end generated code: output=74d28e38ebe2b224 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000286{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000287#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 if (_PyImport_ReleaseLock() < 0) {
289 PyErr_SetString(PyExc_RuntimeError,
290 "not holding the import lock");
291 return NULL;
292 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000293#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_INCREF(Py_None);
295 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000296}
297
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100298void
299_PyImport_Fini(void)
300{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200301 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100302#ifdef WITH_THREAD
303 if (import_lock != NULL) {
304 PyThread_free_lock(import_lock);
305 import_lock = NULL;
306 }
307#endif
308}
309
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310/* Helper for sys */
311
312PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000313PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyInterpreterState *interp = PyThreadState_GET()->interp;
316 if (interp->modules == NULL)
317 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
318 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319}
320
Guido van Rossum3f5da241990-12-20 15:06:42 +0000321
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000322/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200323static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 "path", "argv", "ps1", "ps2",
325 "last_type", "last_value", "last_traceback",
326 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200327 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 /* misc stuff */
329 "flags", "float_info",
330 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000331};
332
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200333static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 "stdin", "__stdin__",
335 "stdout", "__stdout__",
336 "stderr", "__stderr__",
337 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000338};
339
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000340/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000341
Guido van Rossum3f5da241990-12-20 15:06:42 +0000342void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000343PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000344{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200345 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 PyObject *key, *value, *dict;
347 PyInterpreterState *interp = PyThreadState_GET()->interp;
348 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200349 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200350 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (modules == NULL)
353 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* Delete some special variables first. These are common
356 places where user values hide and people complain when their
357 destructors fail. Since the modules containing them are
358 deleted *last* of all, they would come too late in the normal
359 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000360
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200361 /* XXX Perhaps these precautions are obsolete. Who knows? */
362
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200363 if (Py_VerboseFlag)
364 PySys_WriteStderr("# clear builtins._\n");
365 PyDict_SetItemString(interp->builtins, "_", Py_None);
366
367 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200369 PySys_WriteStderr("# clear sys.%s\n", *p);
370 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200372 for (p = sys_files; *p != NULL; p+=2) {
373 if (Py_VerboseFlag)
374 PySys_WriteStderr("# restore sys.%s\n", *p);
375 value = PyDict_GetItemString(interp->sysdict, *(p+1));
376 if (value == NULL)
377 value = Py_None;
378 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000380
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200381 /* We prepare a list which will receive (name, weakref) tuples of
382 modules when they are removed from sys.modules. The name is used
383 for diagnosis messages (in verbose mode), while the weakref helps
384 detect those modules which have been held alive. */
385 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200386 if (weaklist == NULL)
387 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200388
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200389#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200390 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200391 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
392 if (name && wr) { \
393 PyObject *tup = PyTuple_Pack(2, name, wr); \
394 PyList_Append(weaklist, tup); \
395 Py_XDECREF(tup); \
396 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200397 Py_XDECREF(wr); \
398 if (PyErr_Occurred()) \
399 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000401
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200402 /* Remove all modules from sys.modules, hoping that garbage collection
403 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 pos = 0;
405 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200406 if (PyModule_Check(value)) {
407 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200408 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200409 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyDict_SetItem(modules, key, Py_None);
411 }
412 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000413
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200414 /* Clear the modules dict. */
415 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200416 /* Restore the original builtins dict, to ensure that any
417 user data gets cleared. */
418 dict = PyDict_Copy(interp->builtins);
419 if (dict == NULL)
420 PyErr_Clear();
421 PyDict_Clear(interp->builtins);
422 if (PyDict_Update(interp->builtins, interp->builtins_copy))
423 PyErr_Clear();
424 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200425 /* Clear module dict copies stored in the interpreter state */
426 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200427 /* Collect references */
428 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200429 /* Dump GC stats before it's too late, since it uses the warnings
430 machinery. */
431 _PyGC_DumpShutdownStats();
432
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200433 /* Now, if there are any modules left alive, clear their globals to
434 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200435 up here, since they are kept alive in the interpreter state.
436
437 The special treatment of "builtins" here is because even
438 when it's not referenced as a module, its dictionary is
439 referenced by almost every module's __builtins__. Since
440 deleting a module clears its dictionary (even if there are
441 references left to it), we need to delete the "builtins"
442 module last. Likewise, we don't delete sys until the very
443 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200444 if (weaklist != NULL) {
445 Py_ssize_t i, n;
446 n = PyList_GET_SIZE(weaklist);
447 for (i = 0; i < n; i++) {
448 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200449 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
451 if (mod == Py_None)
452 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200453 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200454 dict = PyModule_GetDict(mod);
455 if (dict == interp->builtins || dict == interp->sysdict)
456 continue;
457 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200458 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200459 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200460 _PyModule_Clear(mod);
461 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200462 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200463 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000465
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200466 /* Next, delete sys and builtins (in that order) */
467 if (Py_VerboseFlag)
468 PySys_FormatStderr("# cleanup[3] wiping sys\n");
469 _PyModule_ClearDict(interp->sysdict);
470 if (Py_VerboseFlag)
471 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
472 _PyModule_ClearDict(interp->builtins);
473
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200474 /* Clear and delete the modules directory. Actual modules will
475 still be there only if imported during the execution of some
476 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 interp->modules = NULL;
478 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200479
480 /* Once more */
481 _PyGC_CollectNoFail();
482
483#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000484}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000485
486
Barry Warsaw28a691b2010-04-17 00:19:56 +0000487/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000488
489long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000490PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000491{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200492 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400493 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600494 PyObject *external, *pyc_magic;
495
496 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
497 if (external == NULL)
498 return -1;
499 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
500 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400501 if (pyc_magic == NULL)
502 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200503 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700504 Py_DECREF(pyc_magic);
505 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000506}
507
508
Brett Cannon3adc7b72012-07-09 14:22:12 -0400509extern const char * _PySys_ImplCacheTag;
510
Barry Warsaw28a691b2010-04-17 00:19:56 +0000511const char *
512PyImport_GetMagicTag(void)
513{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400514 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000515}
516
Brett Cannon98979b82012-07-02 15:13:11 -0400517
Guido van Rossum25ce5661997-08-02 03:10:38 +0000518/* Magic for extension modules (built-in as well as dynamically
519 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200520 once, we keep a static dictionary 'extensions' keyed by the tuple
521 (module name, module name) (for built-in modules) or by
522 (filename, module name) (for dynamically loaded modules), containing these
523 modules. A copy of the module's dictionary is stored by calling
524 _PyImport_FixupExtensionObject() immediately after the module initialization
525 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100526 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000527
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000528 Modules which do support multiple initialization set their m_size
529 field to a non-negative number (indicating the size of the
530 module-specific state). They are still recorded in the extensions
531 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000532*/
533
534int
Victor Stinner95872862011-03-07 18:20:56 +0100535_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
536 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000537{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500538 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500540 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (extensions == NULL) {
542 extensions = PyDict_New();
543 if (extensions == NULL)
544 return -1;
545 }
546 if (mod == NULL || !PyModule_Check(mod)) {
547 PyErr_BadInternalCall();
548 return -1;
549 }
550 def = PyModule_GetDef(mod);
551 if (!def) {
552 PyErr_BadInternalCall();
553 return -1;
554 }
555 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100556 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 return -1;
558 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100559 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return -1;
561 }
562 if (def->m_size == -1) {
563 if (def->m_base.m_copy) {
564 /* Somebody already imported the module,
565 likely under a different name.
566 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200567 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 }
569 dict = PyModule_GetDict(mod);
570 if (dict == NULL)
571 return -1;
572 def->m_base.m_copy = PyDict_Copy(dict);
573 if (def->m_base.m_copy == NULL)
574 return -1;
575 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500576 key = PyTuple_Pack(2, filename, name);
577 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200578 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500579 res = PyDict_SetItem(extensions, key, (PyObject *)def);
580 Py_DECREF(key);
581 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200582 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584}
585
Victor Stinner49d3f252010-10-17 01:24:53 +0000586int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300587_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000588{
589 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100590 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100591 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100592 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000593 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100594 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
595 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000596 return res;
597}
598
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100600_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500602 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyModuleDef* def;
604 if (extensions == NULL)
605 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500606 key = PyTuple_Pack(2, filename, name);
607 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200608 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500609 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
610 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (def == NULL)
612 return NULL;
613 if (def->m_size == -1) {
614 /* Module does not support repeated initialization */
615 if (def->m_base.m_copy == NULL)
616 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100617 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (mod == NULL)
619 return NULL;
620 mdict = PyModule_GetDict(mod);
621 if (mdict == NULL)
622 return NULL;
623 if (PyDict_Update(mdict, def->m_base.m_copy))
624 return NULL;
625 }
626 else {
627 if (def->m_base.m_init == NULL)
628 return NULL;
629 mod = def->m_base.m_init();
630 if (mod == NULL)
631 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200632 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
633 Py_DECREF(mod);
634 return NULL;
635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_DECREF(mod);
637 }
638 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100639 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 Py_DECREF(mod);
641 return NULL;
642 }
643 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100644 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 name, filename);
646 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000647
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000648}
649
Victor Stinner49d3f252010-10-17 01:24:53 +0000650PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000651_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000652{
Victor Stinner95872862011-03-07 18:20:56 +0100653 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100654 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100655 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000656 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100657 res = _PyImport_FindExtensionObject(nameobj, nameobj);
658 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000659 return res;
660}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000661
662/* Get the module object corresponding to a module name.
663 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000664 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000665 Because the former action is most common, THIS DOES NOT RETURN A
666 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000667
Guido van Rossum79f25d91997-04-29 20:08:16 +0000668PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000669PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyObject *modules = PyImport_GetModuleDict();
672 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000673
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200674 if ((m = PyDict_GetItemWithError(modules, name)) != NULL &&
675 PyModule_Check(m)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return m;
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200677 }
678 if (PyErr_Occurred()) {
679 return NULL;
680 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000681 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (m == NULL)
683 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000684 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 Py_DECREF(m);
686 return NULL;
687 }
688 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000691}
692
Victor Stinner27ee0892011-03-04 12:57:09 +0000693PyObject *
694PyImport_AddModule(const char *name)
695{
696 PyObject *nameobj, *module;
697 nameobj = PyUnicode_FromString(name);
698 if (nameobj == NULL)
699 return NULL;
700 module = PyImport_AddModuleObject(nameobj);
701 Py_DECREF(nameobj);
702 return module;
703}
704
705
Tim Peters1cd70172004-08-02 03:52:12 +0000706/* Remove name from sys.modules, if it's there. */
707static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000708remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000711 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000713 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 Py_FatalError("import: deleting existing key in"
715 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000716}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717
Christian Heimes3b06e532008-01-07 20:12:44 +0000718
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000719/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000720 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
721 * removed from sys.modules, to avoid leaving damaged module objects
722 * in sys.modules. The caller may wish to restore the original
723 * module object (if any) in this case; PyImport_ReloadModule is an
724 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000725 *
726 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
727 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000728 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000729PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300730PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 return PyImport_ExecCodeModuleWithPathnames(
733 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000734}
735
736PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300737PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return PyImport_ExecCodeModuleWithPathnames(
740 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000741}
742
743PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300744PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
745 const char *pathname,
746 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000747{
Victor Stinner27ee0892011-03-04 12:57:09 +0000748 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600749 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000750
751 nameobj = PyUnicode_FromString(name);
752 if (nameobj == NULL)
753 return NULL;
754
Victor Stinner27ee0892011-03-04 12:57:09 +0000755 if (cpathname != NULL) {
756 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
757 if (cpathobj == NULL)
758 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400759 }
760 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000761 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400762
763 if (pathname != NULL) {
764 pathobj = PyUnicode_DecodeFSDefault(pathname);
765 if (pathobj == NULL)
766 goto error;
767 }
768 else if (cpathobj != NULL) {
769 PyInterpreterState *interp = PyThreadState_GET()->interp;
770 _Py_IDENTIFIER(_get_sourcefile);
771
772 if (interp == NULL) {
773 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
774 "no interpreter!");
775 }
776
Eric Snow32439d62015-05-02 19:15:18 -0600777 external= PyObject_GetAttrString(interp->importlib,
778 "_bootstrap_external");
779 if (external != NULL) {
780 pathobj = _PyObject_CallMethodIdObjArgs(external,
781 &PyId__get_sourcefile, cpathobj,
782 NULL);
783 Py_DECREF(external);
784 }
Brett Cannona6473f92012-07-13 13:57:03 -0400785 if (pathobj == NULL)
786 PyErr_Clear();
787 }
788 else
789 pathobj = NULL;
790
Victor Stinner27ee0892011-03-04 12:57:09 +0000791 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
792error:
793 Py_DECREF(nameobj);
794 Py_XDECREF(pathobj);
795 Py_XDECREF(cpathobj);
796 return m;
797}
798
Brett Cannon18fc4e72014-04-04 10:01:46 -0400799static PyObject *
800module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000801{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400802 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000803
Victor Stinner27ee0892011-03-04 12:57:09 +0000804 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (m == NULL)
806 return NULL;
807 /* If the module is being reloaded, we get the old module back
808 and re-use its dict to exec the new code. */
809 d = PyModule_GetDict(m);
810 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
811 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400812 PyEval_GetBuiltins()) != 0) {
813 remove_module(name);
814 return NULL;
815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400817
Eric Snow08197a42014-05-12 17:54:55 -0600818 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400819}
820
821static PyObject *
822exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
823{
824 PyObject *modules = PyImport_GetModuleDict();
825 PyObject *v, *m;
826
827 v = PyEval_EvalCode(code_object, module_dict, module_dict);
828 if (v == NULL) {
829 remove_module(name);
830 return NULL;
831 }
832 Py_DECREF(v);
833
834 if ((m = PyDict_GetItem(modules, name)) == NULL) {
835 PyErr_Format(PyExc_ImportError,
836 "Loaded module %R not found in sys.modules",
837 name);
838 return NULL;
839 }
840
841 Py_INCREF(m);
842
843 return m;
844}
845
846PyObject*
847PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
848 PyObject *cpathname)
849{
Eric Snow32439d62015-05-02 19:15:18 -0600850 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600851 PyInterpreterState *interp = PyThreadState_GET()->interp;
852 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400853
854 d = module_dict_for_exec(name);
855 if (d == NULL) {
856 return NULL;
857 }
858
Eric Snow08197a42014-05-12 17:54:55 -0600859 if (pathname == NULL) {
860 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 }
Eric Snow32439d62015-05-02 19:15:18 -0600862 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
863 if (external == NULL)
864 return NULL;
865 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600866 &PyId__fix_up_module,
867 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600868 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600869 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600870 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600871 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 }
Eric Snow08197a42014-05-12 17:54:55 -0600873 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874}
875
876
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000877static void
878update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyObject *constants, *tmp;
881 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (PyUnicode_Compare(co->co_filename, oldname))
884 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000885
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200886 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300887 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 constants = co->co_consts;
890 n = PyTuple_GET_SIZE(constants);
891 for (i = 0; i < n; i++) {
892 tmp = PyTuple_GET_ITEM(constants, i);
893 if (PyCode_Check(tmp))
894 update_code_filenames((PyCodeObject *)tmp,
895 oldname, newname);
896 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000897}
898
Victor Stinner2f42ae52011-03-20 00:41:24 +0100899static void
900update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000901{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100902 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000903
Victor Stinner2f42ae52011-03-20 00:41:24 +0100904 if (PyUnicode_Compare(co->co_filename, newname) == 0)
905 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 oldname = co->co_filename;
908 Py_INCREF(oldname);
909 update_code_filenames(co, oldname, newname);
910 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000911}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912
Brett Cannon4caa61d2014-01-09 19:03:32 -0500913/*[clinic input]
914_imp._fix_co_filename
915
916 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
917 Code object to change.
918
919 path: unicode
920 File path to use.
921 /
922
923Changes code.co_filename to specify the passed-in file path.
924[clinic start generated code]*/
925
Brett Cannon4caa61d2014-01-09 19:03:32 -0500926static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -0400927_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code,
928 PyObject *path)
929/*[clinic end generated code: output=f4db56aac0a1327f input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700930
Brett Cannon4caa61d2014-01-09 19:03:32 -0500931{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500932 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700933
934 Py_RETURN_NONE;
935}
936
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000937
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000938/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700939static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000940
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000941
942/* Helper to test for built-in module */
943
944static int
Victor Stinner95872862011-03-07 18:20:56 +0100945is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000946{
Victor Stinner95872862011-03-07 18:20:56 +0100947 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +0100949 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
950 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (PyImport_Inittab[i].initfunc == NULL)
952 return -1;
953 else
954 return 1;
955 }
956 }
957 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000958}
959
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000960
Just van Rossum52e14d62002-12-30 22:08:05 +0000961/* Return an importer object for a sys.path/pkg.__path__ item 'p',
962 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000963 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000964 that can handle the path item. Return None if no hook could;
965 this tells our caller it should fall back to the builtin
966 import mechanism. Cache the result in path_importer_cache.
967 Returns a borrowed reference. */
968
969static PyObject *
970get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 PyObject *importer;
974 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 /* These conditions are the caller's responsibility: */
977 assert(PyList_Check(path_hooks));
978 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 nhooks = PyList_Size(path_hooks);
981 if (nhooks < 0)
982 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 importer = PyDict_GetItem(path_importer_cache, p);
985 if (importer != NULL)
986 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* set path_importer_cache[p] to None to avoid recursion */
989 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
990 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 for (j = 0; j < nhooks; j++) {
993 PyObject *hook = PyList_GetItem(path_hooks, j);
994 if (hook == NULL)
995 return NULL;
996 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
997 if (importer != NULL)
998 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1001 return NULL;
1002 }
1003 PyErr_Clear();
1004 }
1005 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001006 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 }
1008 if (importer != NULL) {
1009 int err = PyDict_SetItem(path_importer_cache, p, importer);
1010 Py_DECREF(importer);
1011 if (err != 0)
1012 return NULL;
1013 }
1014 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001015}
1016
Christian Heimes9cd17752007-11-18 19:35:23 +00001017PyAPI_FUNC(PyObject *)
1018PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001020
Victor Stinner1e53bba2013-07-16 22:26:05 +02001021 path_importer_cache = PySys_GetObject("path_importer_cache");
1022 path_hooks = PySys_GetObject("path_hooks");
1023 if (path_importer_cache != NULL && path_hooks != NULL) {
1024 importer = get_path_importer(path_importer_cache,
1025 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 }
1027 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1028 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001029}
1030
Nick Coghland5cacbb2015-05-23 22:24:10 +10001031/*[clinic input]
1032_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001033
Nick Coghland5cacbb2015-05-23 22:24:10 +10001034 spec: object
1035 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001036
Nick Coghland5cacbb2015-05-23 22:24:10 +10001037Create an extension module.
1038[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001039
Nick Coghland5cacbb2015-05-23 22:24:10 +10001040static PyObject *
1041_imp_create_builtin(PyModuleDef *module, PyObject *spec)
1042/*[clinic end generated code: output=5038f467617226bd input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001045 PyObject *name;
1046 char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001047 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001048
Nick Coghland5cacbb2015-05-23 22:24:10 +10001049 name = PyObject_GetAttrString(spec, "name");
1050 if (name == NULL) {
1051 return NULL;
1052 }
1053
Victor Stinner5eb4f592013-11-14 22:38:52 +01001054 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001055 if (mod || PyErr_Occurred()) {
1056 Py_DECREF(name);
1057 Py_INCREF(mod);
1058 return mod;
1059 }
1060
1061 namestr = PyUnicode_AsUTF8(name);
1062 if (namestr == NULL) {
1063 Py_DECREF(name);
1064 return NULL;
1065 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001068 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001069 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001071 /* Cannot re-init internal module ("sys" or "builtins") */
1072 mod = PyImport_AddModule(namestr);
1073 Py_DECREF(name);
1074 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001077 if (mod == NULL) {
1078 Py_DECREF(name);
1079 return NULL;
1080 }
1081 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1082 Py_DECREF(name);
1083 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1084 } else {
1085 /* Remember pointer to module init function. */
1086 def = PyModule_GetDef(mod);
1087 def->m_base.m_init = p->initfunc;
1088 if (_PyImport_FixupExtensionObject(mod, name, name) < 0) {
1089 Py_DECREF(name);
1090 return NULL;
1091 }
1092 Py_DECREF(name);
1093 return mod;
1094 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 }
1096 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001097 Py_DECREF(name);
1098 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001099}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001100
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001101
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001102/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001103
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001104static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001105find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001106{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001107 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001108
Victor Stinner53dc7352011-03-20 01:50:21 +01001109 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 for (p = PyImport_FrozenModules; ; p++) {
1113 if (p->name == NULL)
1114 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001115 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 break;
1117 }
1118 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001119}
1120
Guido van Rossum79f25d91997-04-29 20:08:16 +00001121static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001122get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001123{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001124 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 if (p == NULL) {
1128 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001129 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 name);
1131 return NULL;
1132 }
1133 if (p->code == NULL) {
1134 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001135 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 name);
1137 return NULL;
1138 }
1139 size = p->size;
1140 if (size < 0)
1141 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001142 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001143}
1144
Brett Cannon8d110132009-03-15 02:20:16 +00001145static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001146is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001147{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001148 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (p == NULL) {
1152 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001153 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 name);
1155 return NULL;
1156 }
Brett Cannon8d110132009-03-15 02:20:16 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (size < 0)
1161 Py_RETURN_TRUE;
1162 else
1163 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001164}
1165
1166
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001167/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001168 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001169 an exception set if the initialization failed.
1170 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001171
1172int
Victor Stinner53dc7352011-03-20 01:50:21 +01001173PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001174{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001175 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001176 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 int ispackage;
1178 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001179
Victor Stinner53dc7352011-03-20 01:50:21 +01001180 p = find_frozen(name);
1181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (p == NULL)
1183 return 0;
1184 if (p->code == NULL) {
1185 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001186 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 name);
1188 return -1;
1189 }
1190 size = p->size;
1191 ispackage = (size < 0);
1192 if (ispackage)
1193 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001194 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (co == NULL)
1196 return -1;
1197 if (!PyCode_Check(co)) {
1198 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001199 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 name);
1201 goto err_return;
1202 }
1203 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001204 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001205 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001207 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (m == NULL)
1209 goto err_return;
1210 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001211 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 goto err_return;
1214 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 err = PyDict_SetItemString(d, "__path__", l);
1216 Py_DECREF(l);
1217 if (err != 0)
1218 goto err_return;
1219 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001220 d = module_dict_for_exec(name);
1221 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001222 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001223 }
1224 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (m == NULL)
1226 goto err_return;
1227 Py_DECREF(co);
1228 Py_DECREF(m);
1229 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001230err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 Py_DECREF(co);
1232 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001233}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001234
Victor Stinner53dc7352011-03-20 01:50:21 +01001235int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001236PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001237{
1238 PyObject *nameobj;
1239 int ret;
1240 nameobj = PyUnicode_InternFromString(name);
1241 if (nameobj == NULL)
1242 return -1;
1243 ret = PyImport_ImportFrozenModuleObject(nameobj);
1244 Py_DECREF(nameobj);
1245 return ret;
1246}
1247
Guido van Rossum74e6a111994-08-29 12:54:38 +00001248
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001249/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001250 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001251
Guido van Rossum79f25d91997-04-29 20:08:16 +00001252PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001253PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 PyObject *pname;
1256 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 pname = PyUnicode_FromString(name);
1259 if (pname == NULL)
1260 return NULL;
1261 result = PyImport_Import(pname);
1262 Py_DECREF(pname);
1263 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001264}
1265
Christian Heimes072c0f12008-01-03 23:01:04 +00001266/* Import a module without blocking
1267 *
1268 * At first it tries to fetch the module from sys.modules. If the module was
1269 * never loaded before it loads it with PyImport_ImportModule() unless another
1270 * thread holds the import lock. In the latter case the function raises an
1271 * ImportError instead of blocking.
1272 *
1273 * Returns the module object with incremented ref count.
1274 */
1275PyObject *
1276PyImport_ImportModuleNoBlock(const char *name)
1277{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001278 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001279}
1280
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001281
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001282/* Remove importlib frames from the traceback,
1283 * except in Verbose mode. */
1284static void
1285remove_importlib_frames(void)
1286{
1287 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001288 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001289 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001290 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001291 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001292 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001293 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001294
1295 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001296 from the traceback. We always trim chunks
1297 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001298
1299 PyErr_Fetch(&exception, &value, &base_tb);
1300 if (!exception || Py_VerboseFlag)
1301 goto done;
1302 if (PyType_IsSubtype((PyTypeObject *) exception,
1303 (PyTypeObject *) PyExc_ImportError))
1304 always_trim = 1;
1305
1306 prev_link = &base_tb;
1307 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001308 while (tb != NULL) {
1309 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1310 PyObject *next = (PyObject *) traceback->tb_next;
1311 PyFrameObject *frame = traceback->tb_frame;
1312 PyCodeObject *code = frame->f_code;
1313 int now_in_importlib;
1314
1315 assert(PyTraceBack_Check(tb));
1316 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1317 code->co_filename,
Eric Snow32439d62015-05-02 19:15:18 -06001318 importlib_filename) == 0) ||
1319 (PyUnicode_CompareWithASCIIString(
1320 code->co_filename,
1321 external_filename) == 0);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001322 if (now_in_importlib && !in_importlib) {
1323 /* This is the link to this chunk of importlib tracebacks */
1324 outer_link = prev_link;
1325 }
1326 in_importlib = now_in_importlib;
1327
1328 if (in_importlib &&
1329 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001330 PyUnicode_CompareWithASCIIString(code->co_name,
1331 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001332 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001333 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001334 prev_link = outer_link;
1335 }
1336 else {
1337 prev_link = (PyObject **) &traceback->tb_next;
1338 }
1339 tb = next;
1340 }
1341done:
1342 PyErr_Restore(exception, value, base_tb);
1343}
1344
1345
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001346PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001347PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1348 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001349 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001350{
Brett Cannonfd074152012-04-14 14:10:13 -04001351 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001352 _Py_IDENTIFIER(__spec__);
1353 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001354 _Py_IDENTIFIER(__package__);
1355 _Py_IDENTIFIER(__path__);
1356 _Py_IDENTIFIER(__name__);
1357 _Py_IDENTIFIER(_find_and_load);
1358 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001359 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001360 _Py_static_string(single_dot, ".");
1361 PyObject *abs_name = NULL;
1362 PyObject *builtins_import = NULL;
1363 PyObject *final_mod = NULL;
1364 PyObject *mod = NULL;
1365 PyObject *package = NULL;
Brett Cannon63b85052016-01-15 13:33:03 -08001366 PyObject *spec = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001367 PyObject *globals = NULL;
1368 PyObject *fromlist = NULL;
1369 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001370 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001371
1372 /* Make sure to use default values so as to not have
1373 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1374 NULL argument. */
1375 if (given_globals == NULL) {
1376 globals = PyDict_New();
1377 if (globals == NULL) {
1378 goto error;
1379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 }
Brett Cannonfd074152012-04-14 14:10:13 -04001381 else {
1382 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001383 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001384 if (level > 0 && !PyDict_Check(given_globals)) {
1385 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1386 goto error;
1387 }
1388 globals = given_globals;
1389 Py_INCREF(globals);
1390 }
1391
1392 if (given_fromlist == NULL) {
1393 fromlist = PyList_New(0);
1394 if (fromlist == NULL) {
1395 goto error;
1396 }
1397 }
1398 else {
1399 fromlist = given_fromlist;
1400 Py_INCREF(fromlist);
1401 }
1402 if (name == NULL) {
1403 PyErr_SetString(PyExc_ValueError, "Empty module name");
1404 goto error;
1405 }
1406
1407 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1408 for added performance. */
1409
1410 if (!PyUnicode_Check(name)) {
1411 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1412 goto error;
1413 }
1414 else if (PyUnicode_READY(name) < 0) {
1415 goto error;
1416 }
1417 if (level < 0) {
1418 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1419 goto error;
1420 }
1421 else if (level > 0) {
Brett Cannon849113a2016-01-22 15:25:50 -08001422 package = _PyDict_GetItemId(globals, &PyId___package__);
Brett Cannon63b85052016-01-15 13:33:03 -08001423 spec = _PyDict_GetItemId(globals, &PyId___spec__);
Brett Cannon849113a2016-01-22 15:25:50 -08001424
Brett Cannonfd074152012-04-14 14:10:13 -04001425 if (package != NULL && package != Py_None) {
Brett Cannon849113a2016-01-22 15:25:50 -08001426 Py_INCREF(package);
Brett Cannonfd074152012-04-14 14:10:13 -04001427 if (!PyUnicode_Check(package)) {
Brett Cannon849113a2016-01-22 15:25:50 -08001428 PyErr_SetString(PyExc_TypeError, "package must be a string");
1429 goto error;
1430 }
Brett Cannon9fa81262016-01-22 16:39:02 -08001431 else if (spec != NULL && spec != Py_None) {
Brett Cannon849113a2016-01-22 15:25:50 -08001432 int equal;
1433 PyObject *parent = PyObject_GetAttrString(spec, "parent");
1434 if (parent == NULL) {
1435 goto error;
1436 }
1437
1438 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1439 Py_DECREF(parent);
1440 if (equal < 0) {
1441 goto error;
1442 }
1443 else if (equal == 0) {
1444 if (PyErr_WarnEx(PyExc_ImportWarning,
1445 "__package__ != __spec__.parent", 1) < 0) {
1446 goto error;
1447 }
1448 }
1449 }
1450 }
Brett Cannon9fa81262016-01-22 16:39:02 -08001451 else if (spec != NULL && spec != Py_None) {
Brett Cannon849113a2016-01-22 15:25:50 -08001452 package = PyObject_GetAttrString(spec, "parent");
1453 if (package == NULL) {
1454 goto error;
1455 }
1456 else if (!PyUnicode_Check(package)) {
Brett Cannon63b85052016-01-15 13:33:03 -08001457 PyErr_SetString(PyExc_TypeError,
1458 "__spec__.parent must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001459 goto error;
1460 }
1461 }
1462 else {
Brett Cannon849113a2016-01-22 15:25:50 -08001463 if (PyErr_WarnEx(PyExc_ImportWarning,
1464 "can't resolve package from __spec__ or __package__, "
1465 "falling back on __name__ and __path__", 1) < 0) {
1466 goto error;
Brett Cannon63b85052016-01-15 13:33:03 -08001467 }
Brett Cannon849113a2016-01-22 15:25:50 -08001468
1469 package = _PyDict_GetItemId(globals, &PyId___name__);
1470 if (package == NULL) {
1471 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1472 goto error;
1473 }
1474
1475 Py_INCREF(package);
1476 if (!PyUnicode_Check(package)) {
1477 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1478 goto error;
1479 }
1480
1481 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1482 PyObject *partition = NULL;
1483 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1484 if (borrowed_dot == NULL) {
Brett Cannon63b85052016-01-15 13:33:03 -08001485 goto error;
1486 }
Brett Cannon849113a2016-01-22 15:25:50 -08001487 partition = PyUnicode_RPartition(package, borrowed_dot);
1488 Py_DECREF(package);
1489 if (partition == NULL) {
Brett Cannon63b85052016-01-15 13:33:03 -08001490 goto error;
1491 }
Brett Cannon849113a2016-01-22 15:25:50 -08001492 package = PyTuple_GET_ITEM(partition, 0);
Brett Cannon63b85052016-01-15 13:33:03 -08001493 Py_INCREF(package);
Brett Cannon849113a2016-01-22 15:25:50 -08001494 Py_DECREF(partition);
Brett Cannonfd074152012-04-14 14:10:13 -04001495 }
1496 }
1497
Brett Cannon9fa81262016-01-22 16:39:02 -08001498 if (PyUnicode_CompareWithASCIIString(package, "") == 0) {
1499 PyErr_SetString(PyExc_ImportError,
1500 "attempted relative import with no known parent package");
1501 goto error;
1502 }
1503 else if (PyDict_GetItem(interp->modules, package) == NULL) {
Brett Cannonfd074152012-04-14 14:10:13 -04001504 PyErr_Format(PyExc_SystemError,
1505 "Parent module %R not loaded, cannot perform relative "
1506 "import", package);
1507 goto error;
1508 }
1509 }
1510 else { /* level == 0 */
1511 if (PyUnicode_GET_LENGTH(name) == 0) {
1512 PyErr_SetString(PyExc_ValueError, "Empty module name");
1513 goto error;
1514 }
1515 package = Py_None;
1516 Py_INCREF(package);
1517 }
1518
1519 if (level > 0) {
1520 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1521 PyObject *base = NULL;
1522 int level_up = 1;
1523
1524 for (level_up = 1; level_up < level; level_up += 1) {
1525 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1526 if (last_dot == -2) {
1527 goto error;
1528 }
1529 else if (last_dot == -1) {
1530 PyErr_SetString(PyExc_ValueError,
1531 "attempted relative import beyond top-level "
1532 "package");
1533 goto error;
1534 }
1535 }
Victor Stinner22af2592013-11-13 12:11:36 +01001536
Brett Cannonfd074152012-04-14 14:10:13 -04001537 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001538 if (base == NULL)
1539 goto error;
1540
Brett Cannonfd074152012-04-14 14:10:13 -04001541 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001542 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001543
1544 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001545 seq = PyTuple_Pack(2, base, name);
1546 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001547 if (borrowed_dot == NULL || seq == NULL) {
1548 goto error;
1549 }
1550
1551 abs_name = PyUnicode_Join(borrowed_dot, seq);
1552 Py_DECREF(seq);
1553 if (abs_name == NULL) {
1554 goto error;
1555 }
1556 }
1557 else {
1558 abs_name = base;
1559 }
1560 }
1561 else {
1562 abs_name = name;
1563 Py_INCREF(abs_name);
1564 }
1565
Brian Curtine6b299f2012-04-14 14:19:33 -05001566#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001567 _PyImport_AcquireLock();
1568#endif
1569 /* From this point forward, goto error_with_unlock! */
1570 if (PyDict_Check(globals)) {
1571 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1572 }
1573 if (builtins_import == NULL) {
1574 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1575 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001576 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1577 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001578 }
1579 }
1580 Py_INCREF(builtins_import);
1581
1582 mod = PyDict_GetItem(interp->modules, abs_name);
1583 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001584 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1585 "None in sys.modules", abs_name);
1586 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001587 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001588 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001589 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001590 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001591 goto error_with_unlock;
1592 }
1593 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001594 PyObject *value = NULL;
1595 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001596 int initializing = 0;
1597
Brett Cannonfd074152012-04-14 14:10:13 -04001598 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001599 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001600 __spec__._initializing is true.
1601 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001602 stuffing the new module in sys.modules.
1603 */
Eric Snowb523f842013-11-22 09:05:39 -07001604 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1605 if (spec != NULL) {
1606 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1607 Py_DECREF(spec);
1608 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001609 if (value == NULL)
1610 PyErr_Clear();
1611 else {
1612 initializing = PyObject_IsTrue(value);
1613 Py_DECREF(value);
1614 if (initializing == -1)
1615 PyErr_Clear();
1616 }
1617 if (initializing > 0) {
1618 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001619 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001620 &PyId__lock_unlock_module, abs_name,
1621 NULL);
1622 if (value == NULL)
1623 goto error;
1624 Py_DECREF(value);
1625 }
1626 else {
1627#ifdef WITH_THREAD
1628 if (_PyImport_ReleaseLock() < 0) {
1629 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1630 goto error;
1631 }
1632#endif
1633 }
Brett Cannonfd074152012-04-14 14:10:13 -04001634 }
1635 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001636 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001637 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001638 &PyId__find_and_load, abs_name,
1639 builtins_import, NULL);
1640 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001641 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001642 }
1643 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001644 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001645
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001646 has_from = PyObject_IsTrue(fromlist);
1647 if (has_from < 0)
1648 goto error;
1649 if (!has_from) {
Brett Cannonfd074152012-04-14 14:10:13 -04001650 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1651 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001652 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001653 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1654
1655 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001656 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001657 }
1658
Brian Curtine6b299f2012-04-14 14:19:33 -05001659 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001660 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001661 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001662 }
1663
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001664 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1665 /* No dot in module name, simple exit */
1666 Py_DECREF(partition);
1667 final_mod = mod;
1668 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001669 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001670 }
1671
Brett Cannonfd074152012-04-14 14:10:13 -04001672 front = PyTuple_GET_ITEM(partition, 0);
1673 Py_INCREF(front);
1674 Py_DECREF(partition);
1675
1676 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001677 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001678 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001679 }
1680 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001681 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1682 PyUnicode_GET_LENGTH(front);
1683 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001684 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001685 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001686 Py_DECREF(front);
1687 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001688 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001689 }
Brett Cannonfd074152012-04-14 14:10:13 -04001690
1691 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001692 if (final_mod == NULL) {
1693 PyErr_Format(PyExc_KeyError,
1694 "%R not in sys.modules as expected",
1695 to_return);
1696 }
1697 else {
1698 Py_INCREF(final_mod);
1699 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001700 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001701 }
1702 }
1703 else {
1704 final_mod = mod;
1705 Py_INCREF(mod);
1706 }
1707 }
1708 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001709 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001710 &PyId__handle_fromlist, mod,
1711 fromlist, builtins_import,
1712 NULL);
1713 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001714 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001715
Brett Cannonfd074152012-04-14 14:10:13 -04001716 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001717#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001718 if (_PyImport_ReleaseLock() < 0) {
1719 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1720 }
1721#endif
1722 error:
1723 Py_XDECREF(abs_name);
1724 Py_XDECREF(builtins_import);
1725 Py_XDECREF(mod);
1726 Py_XDECREF(package);
1727 Py_XDECREF(globals);
1728 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001729 if (final_mod == NULL)
1730 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001731 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001732}
1733
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001734PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001735PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001736 PyObject *fromlist, int level)
1737{
1738 PyObject *nameobj, *mod;
1739 nameobj = PyUnicode_FromString(name);
1740 if (nameobj == NULL)
1741 return NULL;
1742 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1743 fromlist, level);
1744 Py_DECREF(nameobj);
1745 return mod;
1746}
1747
1748
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001749/* Re-import a module of any kind and return its module object, WITH
1750 INCREMENTED REFERENCE COUNT */
1751
Guido van Rossum79f25d91997-04-29 20:08:16 +00001752PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001753PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001754{
Brett Cannon62228db2012-04-29 14:38:11 -04001755 _Py_IDENTIFIER(reload);
1756 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001758 PyObject *imp = PyDict_GetItemString(modules, "imp");
1759 if (imp == NULL) {
1760 imp = PyImport_ImportModule("imp");
1761 if (imp == NULL) {
1762 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 }
Brett Cannon62228db2012-04-29 14:38:11 -04001765 else {
1766 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001768
Brett Cannon62228db2012-04-29 14:38:11 -04001769 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1770 Py_DECREF(imp);
1771 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001772}
1773
1774
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001775/* Higher-level import emulator which emulates the "import" statement
1776 more accurately -- it invokes the __import__() function from the
1777 builtins of the current globals. This means that the import is
1778 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001779 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001780 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001781 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001782 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001783
1784PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001785PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 static PyObject *silly_list = NULL;
1788 static PyObject *builtins_str = NULL;
1789 static PyObject *import_str = NULL;
1790 PyObject *globals = NULL;
1791 PyObject *import = NULL;
1792 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001793 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Initialize constant string objects */
1797 if (silly_list == NULL) {
1798 import_str = PyUnicode_InternFromString("__import__");
1799 if (import_str == NULL)
1800 return NULL;
1801 builtins_str = PyUnicode_InternFromString("__builtins__");
1802 if (builtins_str == NULL)
1803 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001804 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (silly_list == NULL)
1806 return NULL;
1807 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* Get the builtins from current globals */
1810 globals = PyEval_GetGlobals();
1811 if (globals != NULL) {
1812 Py_INCREF(globals);
1813 builtins = PyObject_GetItem(globals, builtins_str);
1814 if (builtins == NULL)
1815 goto err;
1816 }
1817 else {
1818 /* No globals -- use standard builtins, and fake globals */
1819 builtins = PyImport_ImportModuleLevel("builtins",
1820 NULL, NULL, NULL, 0);
1821 if (builtins == NULL)
1822 return NULL;
1823 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1824 if (globals == NULL)
1825 goto err;
1826 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 /* Get the __import__ function from the builtins */
1829 if (PyDict_Check(builtins)) {
1830 import = PyObject_GetItem(builtins, import_str);
1831 if (import == NULL)
1832 PyErr_SetObject(PyExc_KeyError, import_str);
1833 }
1834 else
1835 import = PyObject_GetAttr(builtins, import_str);
1836 if (import == NULL)
1837 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001840 Always use absolute import here.
1841 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1843 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001844 if (r == NULL)
1845 goto err;
1846 Py_DECREF(r);
1847
1848 modules = PyImport_GetModuleDict();
1849 r = PyDict_GetItem(modules, module_name);
1850 if (r != NULL)
1851 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001852
1853 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 Py_XDECREF(globals);
1855 Py_XDECREF(builtins);
1856 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001859}
1860
Brett Cannon4caa61d2014-01-09 19:03:32 -05001861/*[clinic input]
1862_imp.extension_suffixes
1863
1864Returns the list of file suffixes used to identify extension modules.
1865[clinic start generated code]*/
1866
Brett Cannon4caa61d2014-01-09 19:03:32 -05001867static PyObject *
1868_imp_extension_suffixes_impl(PyModuleDef *module)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001869/*[clinic end generated code: output=d44c1566ef362229 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001872 const char *suffix;
1873 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 list = PyList_New(0);
1876 if (list == NULL)
1877 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001878#ifdef HAVE_DYNAMIC_LOADING
1879 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1880 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (item == NULL) {
1882 Py_DECREF(list);
1883 return NULL;
1884 }
1885 if (PyList_Append(list, item) < 0) {
1886 Py_DECREF(list);
1887 Py_DECREF(item);
1888 return NULL;
1889 }
1890 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001891 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 }
Brett Cannon2657df42012-05-04 15:20:40 -04001893#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001895}
1896
Brett Cannon4caa61d2014-01-09 19:03:32 -05001897/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001898_imp.init_frozen
1899
1900 name: unicode
1901 /
1902
1903Initializes a frozen module.
1904[clinic start generated code]*/
1905
Brett Cannon4caa61d2014-01-09 19:03:32 -05001906static PyObject *
1907_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001908/*[clinic end generated code: output=a9de493bdd711878 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 int ret;
1911 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001912
Victor Stinner53dc7352011-03-20 01:50:21 +01001913 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 if (ret < 0)
1915 return NULL;
1916 if (ret == 0) {
1917 Py_INCREF(Py_None);
1918 return Py_None;
1919 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001920 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 Py_XINCREF(m);
1922 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001923}
1924
Brett Cannon4caa61d2014-01-09 19:03:32 -05001925/*[clinic input]
1926_imp.get_frozen_object
1927
1928 name: unicode
1929 /
1930
1931Create a code object for a frozen module.
1932[clinic start generated code]*/
1933
Brett Cannon4caa61d2014-01-09 19:03:32 -05001934static PyObject *
1935_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001936/*[clinic end generated code: output=3114c970a47f2e3c input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001939}
1940
Brett Cannon4caa61d2014-01-09 19:03:32 -05001941/*[clinic input]
1942_imp.is_frozen_package
1943
1944 name: unicode
1945 /
1946
1947Returns True if the module name is of a frozen package.
1948[clinic start generated code]*/
1949
Brett Cannon4caa61d2014-01-09 19:03:32 -05001950static PyObject *
1951_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001952/*[clinic end generated code: output=3e4cab802b56d649 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001955}
1956
Brett Cannon4caa61d2014-01-09 19:03:32 -05001957/*[clinic input]
1958_imp.is_builtin
1959
1960 name: unicode
1961 /
1962
1963Returns True if the module name corresponds to a built-in module.
1964[clinic start generated code]*/
1965
Guido van Rossum79f25d91997-04-29 20:08:16 +00001966static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001967_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001968/*[clinic end generated code: output=2deec9cac6fb9a7e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001969{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001970 return PyLong_FromLong(is_builtin(name));
1971}
1972
1973/*[clinic input]
1974_imp.is_frozen
1975
1976 name: unicode
1977 /
1978
1979Returns True if the module name corresponds to a frozen module.
1980[clinic start generated code]*/
1981
Brett Cannon4caa61d2014-01-09 19:03:32 -05001982static PyObject *
1983_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Brett Cannonfd4d0502014-05-30 11:21:14 -04001984/*[clinic end generated code: output=7de8e260c8e36aed input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001985{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001986 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 p = find_frozen(name);
1989 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001990}
1991
Larry Hastings1df0b352015-08-24 19:53:56 -07001992/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1993static int
1994exec_builtin_or_dynamic(PyObject *mod) {
1995 PyModuleDef *def;
1996 void *state;
1997
1998 if (!PyModule_Check(mod)) {
1999 return 0;
2000 }
2001
2002 def = PyModule_GetDef(mod);
2003 if (def == NULL) {
2004 if (PyErr_Occurred()) {
2005 return -1;
2006 }
2007 return 0;
2008 }
2009 state = PyModule_GetState(mod);
2010 if (PyErr_Occurred()) {
2011 return -1;
2012 }
2013 if (state) {
2014 /* Already initialized; skip reload */
2015 return 0;
2016 }
2017 return PyModule_ExecDef(mod, def);
2018}
2019
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002020#ifdef HAVE_DYNAMIC_LOADING
2021
Brett Cannon4caa61d2014-01-09 19:03:32 -05002022/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002023_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002024
Nick Coghland5cacbb2015-05-23 22:24:10 +10002025 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002026 file: object = NULL
2027 /
2028
Nick Coghland5cacbb2015-05-23 22:24:10 +10002029Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002030[clinic start generated code]*/
2031
Brett Cannon4caa61d2014-01-09 19:03:32 -05002032static PyObject *
Nick Coghland5cacbb2015-05-23 22:24:10 +10002033_imp_create_dynamic_impl(PyModuleDef *module, PyObject *spec, PyObject *file)
2034/*[clinic end generated code: output=935cde5b3872d56d input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002035{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002036 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002037 FILE *fp;
2038
Nick Coghland5cacbb2015-05-23 22:24:10 +10002039 name = PyObject_GetAttrString(spec, "name");
2040 if (name == NULL) {
2041 return NULL;
2042 }
2043
2044 path = PyObject_GetAttrString(spec, "origin");
2045 if (path == NULL) {
2046 Py_DECREF(name);
2047 return NULL;
2048 }
2049
2050 mod = _PyImport_FindExtensionObject(name, path);
2051 if (mod != NULL) {
2052 Py_DECREF(name);
2053 Py_DECREF(path);
2054 Py_INCREF(mod);
2055 return mod;
2056 }
2057
Brett Cannon4caa61d2014-01-09 19:03:32 -05002058 if (file != NULL) {
2059 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002060 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002061 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002062 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002064 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002066 else
2067 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002068
2069 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2070
2071 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002072 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (fp)
2074 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002075 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002076}
2077
Nick Coghland5cacbb2015-05-23 22:24:10 +10002078/*[clinic input]
2079_imp.exec_dynamic -> int
2080
2081 mod: object
2082 /
2083
2084Initialize an extension module.
2085[clinic start generated code]*/
2086
2087static int
2088_imp_exec_dynamic_impl(PyModuleDef *module, PyObject *mod)
2089/*[clinic end generated code: output=4b84f1301b22d4bd input=9fdbfcb250280d3a]*/
2090{
Larry Hastings1df0b352015-08-24 19:53:56 -07002091 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002092}
2093
2094
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002095#endif /* HAVE_DYNAMIC_LOADING */
2096
Larry Hastings7726ac92014-01-31 22:03:12 -08002097/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002098_imp.exec_builtin -> int
2099
2100 mod: object
2101 /
2102
2103Initialize a built-in module.
2104[clinic start generated code]*/
2105
2106static int
2107_imp_exec_builtin_impl(PyModuleDef *module, PyObject *mod)
Larry Hastings01b1ff62015-08-24 20:23:27 -07002108/*[clinic end generated code: output=215e99876a27e284 input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002109{
2110 return exec_builtin_or_dynamic(mod);
2111}
2112
2113/*[clinic input]
Larry Hastings7726ac92014-01-31 22:03:12 -08002114dump buffer
2115[clinic start generated code]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -04002116/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
Larry Hastings7726ac92014-01-31 22:03:12 -08002117
Barry Warsaw28a691b2010-04-17 00:19:56 +00002118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002119PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002120"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002121
Guido van Rossum79f25d91997-04-29 20:08:16 +00002122static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002123 _IMP_EXTENSION_SUFFIXES_METHODDEF
2124 _IMP_LOCK_HELD_METHODDEF
2125 _IMP_ACQUIRE_LOCK_METHODDEF
2126 _IMP_RELEASE_LOCK_METHODDEF
2127 _IMP_GET_FROZEN_OBJECT_METHODDEF
2128 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002129 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002130 _IMP_INIT_FROZEN_METHODDEF
2131 _IMP_IS_BUILTIN_METHODDEF
2132 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002133 _IMP_CREATE_DYNAMIC_METHODDEF
2134 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002135 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002136 _IMP__FIX_CO_FILENAME_METHODDEF
2137 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002138};
2139
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002140
Martin v. Löwis1a214512008-06-11 05:26:20 +00002141static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002143 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 doc_imp,
2145 0,
2146 imp_methods,
2147 NULL,
2148 NULL,
2149 NULL,
2150 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002151};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002152
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002153PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002154PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 m = PyModule_Create(&impmodule);
2159 if (m == NULL)
2160 goto failure;
2161 d = PyModule_GetDict(m);
2162 if (d == NULL)
2163 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002166 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Py_XDECREF(m);
2168 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002169}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002170
2171
Guido van Rossumb18618d2000-05-03 23:44:39 +00002172/* API for embedding applications that want to add their own entries
2173 to the table of built-in modules. This should normally be called
2174 *before* Py_Initialize(). When the table resize fails, -1 is
2175 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002176
2177 After a similar function by Just van Rossum. */
2178
2179int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002180PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 static struct _inittab *our_copy = NULL;
2183 struct _inittab *p;
2184 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* Count the number of entries in both tables */
2187 for (n = 0; newtab[n].name != NULL; n++)
2188 ;
2189 if (n == 0)
2190 return 0; /* Nothing to do */
2191 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2192 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 /* Allocate new memory for the combined table */
2195 p = our_copy;
2196 PyMem_RESIZE(p, struct _inittab, i+n+1);
2197 if (p == NULL)
2198 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* Copy the tables into the new memory */
2201 if (our_copy != PyImport_Inittab)
2202 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2203 PyImport_Inittab = our_copy = p;
2204 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002207}
2208
2209/* Shorthand to add a single entry given a name and a function */
2210
2211int
Brett Cannona826f322009-04-02 03:41:46 +00002212PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002217
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002218 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002222}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002223
2224#ifdef __cplusplus
2225}
2226#endif