blob: f27b7cb010ce0bfb9c1a742c6e12ba3c05d6cc73 [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
Guido van Rossum1ae940a1995-01-02 19:04:15 +000041/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000042
43void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000044_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000045{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020046 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040047 initstr = PyUnicode_InternFromString("__init__");
48 if (initstr == NULL)
49 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020050 interp->builtins_copy = PyDict_Copy(interp->builtins);
51 if (interp->builtins_copy == NULL)
52 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053}
54
Guido van Rossum25ce5661997-08-02 03:10:38 +000055void
Just van Rossum52e14d62002-12-30 22:08:05 +000056_PyImportHooks_Init(void)
57{
Brett Cannonfd074152012-04-14 14:10:13 -040058 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000060
Brett Cannonfd074152012-04-14 14:10:13 -040061 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 v = PyList_New(0);
63 if (v == NULL)
64 goto error;
65 err = PySys_SetObject("meta_path", v);
66 Py_DECREF(v);
67 if (err)
68 goto error;
69 v = PyDict_New();
70 if (v == NULL)
71 goto error;
72 err = PySys_SetObject("path_importer_cache", v);
73 Py_DECREF(v);
74 if (err)
75 goto error;
76 path_hooks = PyList_New(0);
77 if (path_hooks == NULL)
78 goto error;
79 err = PySys_SetObject("path_hooks", path_hooks);
80 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000081 error:
Brett Cannonfd074152012-04-14 14:10:13 -040082 PyErr_Print();
83 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020084 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 }
Brett Cannonfd074152012-04-14 14:10:13 -040086 Py_DECREF(path_hooks);
87}
88
89void
90_PyImportZip_Init(void)
91{
92 PyObject *path_hooks, *zimpimport;
93 int err = 0;
94
95 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020096 if (path_hooks == NULL) {
97 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040098 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020099 }
Brett Cannonfd074152012-04-14 14:10:13 -0400100
101 if (Py_VerboseFlag)
102 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 zimpimport = PyImport_ImportModule("zipimport");
105 if (zimpimport == NULL) {
106 PyErr_Clear(); /* No zip import module -- okay */
107 if (Py_VerboseFlag)
108 PySys_WriteStderr("# can't import zipimport\n");
109 }
110 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200111 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200112 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
113 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 Py_DECREF(zimpimport);
115 if (zipimporter == NULL) {
116 PyErr_Clear(); /* No zipimporter object -- okay */
117 if (Py_VerboseFlag)
118 PySys_WriteStderr(
119 "# can't import zipimport.zipimporter\n");
120 }
121 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400122 /* sys.path_hooks.insert(0, zipimporter) */
123 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400125 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (Py_VerboseFlag)
129 PySys_WriteStderr(
130 "# installed zipimport hook\n");
131 }
132 }
Brett Cannonfd074152012-04-14 14:10:13 -0400133
134 return;
135
136 error:
137 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400138 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000139}
140
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000141/* Locking primitives to prevent parallel imports of the same module
142 in different threads to return with a partially loaded module.
143 These calls are serialized by the global interpreter lock. */
144
145#ifdef WITH_THREAD
146
Guido van Rossum49b56061998-10-01 20:42:43 +0000147#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148
Guido van Rossum65d5b571998-12-21 19:32:43 +0000149static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200150static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000151static int import_lock_level = 0;
152
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000153void
154_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000155{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200156 unsigned long me = PyThread_get_thread_ident();
157 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 return; /* Too bad */
159 if (import_lock == NULL) {
160 import_lock = PyThread_allocate_lock();
161 if (import_lock == NULL)
162 return; /* Nothing much we can do. */
163 }
164 if (import_lock_thread == me) {
165 import_lock_level++;
166 return;
167 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200168 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
169 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 {
171 PyThreadState *tstate = PyEval_SaveThread();
172 PyThread_acquire_lock(import_lock, 1);
173 PyEval_RestoreThread(tstate);
174 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100175 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 import_lock_thread = me;
177 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000178}
179
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000180int
181_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000182{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200183 unsigned long me = PyThread_get_thread_ident();
184 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 return 0; /* Too bad */
186 if (import_lock_thread != me)
187 return -1;
188 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100189 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200191 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyThread_release_lock(import_lock);
193 }
194 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000195}
196
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200197/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000198 created child processes do not share locks with the parent.
199 We now acquire the import lock around fork() calls but on some platforms
200 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000201
202void
203_PyImport_ReInitLock(void)
204{
Christian Heimes418fd742015-04-19 21:08:42 +0200205 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200207 if (import_lock == NULL) {
208 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
209 }
210 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000211 if (import_lock_level > 1) {
212 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200213 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500214 /* The following could fail if the lock is already held, but forking as
215 a side-effect of an import is a) rare, b) nuts, and c) difficult to
216 do thanks to the lock only being held when doing individual module
217 locks per import. */
218 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000219 import_lock_thread = me;
220 import_lock_level--;
221 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200222 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000223 import_lock_level = 0;
224 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000225}
226
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000227#endif
228
Brett Cannon4caa61d2014-01-09 19:03:32 -0500229/*[clinic input]
230_imp.lock_held
231
232Return True if the import lock is currently held, else False.
233
234On platforms without threads, return False.
235[clinic start generated code]*/
236
Brett Cannon4caa61d2014-01-09 19:03:32 -0500237static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300238_imp_lock_held_impl(PyObject *module)
239/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000240{
Tim Peters69232342001-08-30 05:16:13 +0000241#ifdef WITH_THREAD
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200242 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000243#else
Serhiy Storchaka370fd202017-03-08 20:47:48 +0200244 Py_RETURN_FALSE;
Tim Peters69232342001-08-30 05:16:13 +0000245#endif
246}
247
Brett Cannon4caa61d2014-01-09 19:03:32 -0500248/*[clinic input]
249_imp.acquire_lock
250
251Acquires the interpreter's import lock for the current thread.
252
253This lock should be used by import hooks to ensure thread-safety when importing
254modules. On platforms without threads, this function does nothing.
255[clinic start generated code]*/
256
Brett Cannon4caa61d2014-01-09 19:03:32 -0500257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300258_imp_acquire_lock_impl(PyObject *module)
259/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000260{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000261#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000263#endif
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200264 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265}
266
Brett Cannon4caa61d2014-01-09 19:03:32 -0500267/*[clinic input]
268_imp.release_lock
269
270Release the interpreter's import lock.
271
272On platforms without threads, this function does nothing.
273[clinic start generated code]*/
274
Brett Cannon4caa61d2014-01-09 19:03:32 -0500275static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300276_imp_release_lock_impl(PyObject *module)
277/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000278{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000279#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (_PyImport_ReleaseLock() < 0) {
281 PyErr_SetString(PyExc_RuntimeError,
282 "not holding the import lock");
283 return NULL;
284 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000285#endif
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200286 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000287}
288
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100289void
290_PyImport_Fini(void)
291{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200292 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100293#ifdef WITH_THREAD
294 if (import_lock != NULL) {
295 PyThread_free_lock(import_lock);
296 import_lock = NULL;
297 }
298#endif
299}
300
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301/* Helper for sys */
302
303PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000304PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 PyInterpreterState *interp = PyThreadState_GET()->interp;
307 if (interp->modules == NULL)
308 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
309 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310}
311
Guido van Rossum3f5da241990-12-20 15:06:42 +0000312
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000313/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200314static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 "path", "argv", "ps1", "ps2",
316 "last_type", "last_value", "last_traceback",
317 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200318 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* misc stuff */
320 "flags", "float_info",
321 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000322};
323
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200324static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 "stdin", "__stdin__",
326 "stdout", "__stdout__",
327 "stderr", "__stderr__",
328 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000329};
330
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000331/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000332
Guido van Rossum3f5da241990-12-20 15:06:42 +0000333void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000334PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000335{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200336 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 PyObject *key, *value, *dict;
338 PyInterpreterState *interp = PyThreadState_GET()->interp;
339 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200340 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200341 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (modules == NULL)
344 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* Delete some special variables first. These are common
347 places where user values hide and people complain when their
348 destructors fail. Since the modules containing them are
349 deleted *last* of all, they would come too late in the normal
350 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000351
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200352 /* XXX Perhaps these precautions are obsolete. Who knows? */
353
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200354 if (Py_VerboseFlag)
355 PySys_WriteStderr("# clear builtins._\n");
356 PyDict_SetItemString(interp->builtins, "_", Py_None);
357
358 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200360 PySys_WriteStderr("# clear sys.%s\n", *p);
361 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200363 for (p = sys_files; *p != NULL; p+=2) {
364 if (Py_VerboseFlag)
365 PySys_WriteStderr("# restore sys.%s\n", *p);
366 value = PyDict_GetItemString(interp->sysdict, *(p+1));
367 if (value == NULL)
368 value = Py_None;
369 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000371
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200372 /* We prepare a list which will receive (name, weakref) tuples of
373 modules when they are removed from sys.modules. The name is used
374 for diagnosis messages (in verbose mode), while the weakref helps
375 detect those modules which have been held alive. */
376 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200377 if (weaklist == NULL)
378 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200379
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200380#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200381 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200382 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
383 if (name && wr) { \
384 PyObject *tup = PyTuple_Pack(2, name, wr); \
385 PyList_Append(weaklist, tup); \
386 Py_XDECREF(tup); \
387 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200388 Py_XDECREF(wr); \
389 if (PyErr_Occurred()) \
390 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200393 /* Remove all modules from sys.modules, hoping that garbage collection
394 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 pos = 0;
396 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200397 if (PyModule_Check(value)) {
398 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200399 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200400 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyDict_SetItem(modules, key, Py_None);
402 }
403 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000404
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200405 /* Clear the modules dict. */
406 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200407 /* Restore the original builtins dict, to ensure that any
408 user data gets cleared. */
409 dict = PyDict_Copy(interp->builtins);
410 if (dict == NULL)
411 PyErr_Clear();
412 PyDict_Clear(interp->builtins);
413 if (PyDict_Update(interp->builtins, interp->builtins_copy))
414 PyErr_Clear();
415 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200416 /* Clear module dict copies stored in the interpreter state */
417 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200418 /* Collect references */
419 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200420 /* Dump GC stats before it's too late, since it uses the warnings
421 machinery. */
422 _PyGC_DumpShutdownStats();
423
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200424 /* Now, if there are any modules left alive, clear their globals to
425 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200426 up here, since they are kept alive in the interpreter state.
427
428 The special treatment of "builtins" here is because even
429 when it's not referenced as a module, its dictionary is
430 referenced by almost every module's __builtins__. Since
431 deleting a module clears its dictionary (even if there are
432 references left to it), we need to delete the "builtins"
433 module last. Likewise, we don't delete sys until the very
434 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200435 if (weaklist != NULL) {
436 Py_ssize_t i, n;
437 n = PyList_GET_SIZE(weaklist);
438 for (i = 0; i < n; i++) {
439 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200440 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200441 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
442 if (mod == Py_None)
443 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200444 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200445 dict = PyModule_GetDict(mod);
446 if (dict == interp->builtins || dict == interp->sysdict)
447 continue;
448 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200449 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200450 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200451 _PyModule_Clear(mod);
452 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200453 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200454 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000456
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200457 /* Next, delete sys and builtins (in that order) */
458 if (Py_VerboseFlag)
459 PySys_FormatStderr("# cleanup[3] wiping sys\n");
460 _PyModule_ClearDict(interp->sysdict);
461 if (Py_VerboseFlag)
462 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
463 _PyModule_ClearDict(interp->builtins);
464
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200465 /* Clear and delete the modules directory. Actual modules will
466 still be there only if imported during the execution of some
467 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 interp->modules = NULL;
469 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200470
471 /* Once more */
472 _PyGC_CollectNoFail();
473
474#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000475}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000476
477
Barry Warsaw28a691b2010-04-17 00:19:56 +0000478/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000479
480long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000481PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000482{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200483 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400484 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600485 PyObject *external, *pyc_magic;
486
487 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
488 if (external == NULL)
489 return -1;
490 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
491 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400492 if (pyc_magic == NULL)
493 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200494 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700495 Py_DECREF(pyc_magic);
496 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000497}
498
499
Brett Cannon3adc7b72012-07-09 14:22:12 -0400500extern const char * _PySys_ImplCacheTag;
501
Barry Warsaw28a691b2010-04-17 00:19:56 +0000502const char *
503PyImport_GetMagicTag(void)
504{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400505 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000506}
507
Brett Cannon98979b82012-07-02 15:13:11 -0400508
Guido van Rossum25ce5661997-08-02 03:10:38 +0000509/* Magic for extension modules (built-in as well as dynamically
510 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200511 once, we keep a static dictionary 'extensions' keyed by the tuple
512 (module name, module name) (for built-in modules) or by
513 (filename, module name) (for dynamically loaded modules), containing these
514 modules. A copy of the module's dictionary is stored by calling
515 _PyImport_FixupExtensionObject() immediately after the module initialization
516 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100517 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000518
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000519 Modules which do support multiple initialization set their m_size
520 field to a non-negative number (indicating the size of the
521 module-specific state). They are still recorded in the extensions
522 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000523*/
524
525int
Victor Stinner95872862011-03-07 18:20:56 +0100526_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
527 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000528{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500529 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500531 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (extensions == NULL) {
533 extensions = PyDict_New();
534 if (extensions == NULL)
535 return -1;
536 }
537 if (mod == NULL || !PyModule_Check(mod)) {
538 PyErr_BadInternalCall();
539 return -1;
540 }
541 def = PyModule_GetDef(mod);
542 if (!def) {
543 PyErr_BadInternalCall();
544 return -1;
545 }
546 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100547 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return -1;
549 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100550 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return -1;
552 }
553 if (def->m_size == -1) {
554 if (def->m_base.m_copy) {
555 /* Somebody already imported the module,
556 likely under a different name.
557 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200558 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 }
560 dict = PyModule_GetDict(mod);
561 if (dict == NULL)
562 return -1;
563 def->m_base.m_copy = PyDict_Copy(dict);
564 if (def->m_base.m_copy == NULL)
565 return -1;
566 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500567 key = PyTuple_Pack(2, filename, name);
568 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200569 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500570 res = PyDict_SetItem(extensions, key, (PyObject *)def);
571 Py_DECREF(key);
572 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200573 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575}
576
Victor Stinner49d3f252010-10-17 01:24:53 +0000577int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300578_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000579{
580 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100581 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100582 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100583 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000584 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100585 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
586 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000587 return res;
588}
589
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100591_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500593 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 PyModuleDef* def;
595 if (extensions == NULL)
596 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500597 key = PyTuple_Pack(2, filename, name);
598 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200599 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500600 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
601 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (def == NULL)
603 return NULL;
604 if (def->m_size == -1) {
605 /* Module does not support repeated initialization */
606 if (def->m_base.m_copy == NULL)
607 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100608 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (mod == NULL)
610 return NULL;
611 mdict = PyModule_GetDict(mod);
612 if (mdict == NULL)
613 return NULL;
614 if (PyDict_Update(mdict, def->m_base.m_copy))
615 return NULL;
616 }
617 else {
618 if (def->m_base.m_init == NULL)
619 return NULL;
620 mod = def->m_base.m_init();
621 if (mod == NULL)
622 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200623 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
624 Py_DECREF(mod);
625 return NULL;
626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 Py_DECREF(mod);
628 }
629 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100630 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 Py_DECREF(mod);
632 return NULL;
633 }
634 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100635 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 name, filename);
637 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000638
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000639}
640
Victor Stinner49d3f252010-10-17 01:24:53 +0000641PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000642_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000643{
Victor Stinner95872862011-03-07 18:20:56 +0100644 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100645 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100646 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000647 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100648 res = _PyImport_FindExtensionObject(nameobj, nameobj);
649 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000650 return res;
651}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000652
653/* Get the module object corresponding to a module name.
654 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000655 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000656 Because the former action is most common, THIS DOES NOT RETURN A
657 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658
Guido van Rossum79f25d91997-04-29 20:08:16 +0000659PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000660PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *modules = PyImport_GetModuleDict();
663 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000664
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200665 if ((m = PyDict_GetItemWithError(modules, name)) != NULL &&
666 PyModule_Check(m)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 return m;
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200668 }
669 if (PyErr_Occurred()) {
670 return NULL;
671 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000672 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (m == NULL)
674 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000675 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 Py_DECREF(m);
677 return NULL;
678 }
679 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000682}
683
Victor Stinner27ee0892011-03-04 12:57:09 +0000684PyObject *
685PyImport_AddModule(const char *name)
686{
687 PyObject *nameobj, *module;
688 nameobj = PyUnicode_FromString(name);
689 if (nameobj == NULL)
690 return NULL;
691 module = PyImport_AddModuleObject(nameobj);
692 Py_DECREF(nameobj);
693 return module;
694}
695
696
Tim Peters1cd70172004-08-02 03:52:12 +0000697/* Remove name from sys.modules, if it's there. */
698static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000699remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000702 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000704 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 Py_FatalError("import: deleting existing key in"
706 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000707}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000708
Christian Heimes3b06e532008-01-07 20:12:44 +0000709
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000710/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000711 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
712 * removed from sys.modules, to avoid leaving damaged module objects
713 * in sys.modules. The caller may wish to restore the original
714 * module object (if any) in this case; PyImport_ReloadModule is an
715 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000716 *
717 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
718 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000719 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000720PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300721PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return PyImport_ExecCodeModuleWithPathnames(
724 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000725}
726
727PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300728PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 return PyImport_ExecCodeModuleWithPathnames(
731 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000732}
733
734PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300735PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
736 const char *pathname,
737 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000738{
Victor Stinner27ee0892011-03-04 12:57:09 +0000739 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600740 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000741
742 nameobj = PyUnicode_FromString(name);
743 if (nameobj == NULL)
744 return NULL;
745
Victor Stinner27ee0892011-03-04 12:57:09 +0000746 if (cpathname != NULL) {
747 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
748 if (cpathobj == NULL)
749 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400750 }
751 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000752 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400753
754 if (pathname != NULL) {
755 pathobj = PyUnicode_DecodeFSDefault(pathname);
756 if (pathobj == NULL)
757 goto error;
758 }
759 else if (cpathobj != NULL) {
760 PyInterpreterState *interp = PyThreadState_GET()->interp;
761 _Py_IDENTIFIER(_get_sourcefile);
762
763 if (interp == NULL) {
764 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
765 "no interpreter!");
766 }
767
Eric Snow32439d62015-05-02 19:15:18 -0600768 external= PyObject_GetAttrString(interp->importlib,
769 "_bootstrap_external");
770 if (external != NULL) {
771 pathobj = _PyObject_CallMethodIdObjArgs(external,
772 &PyId__get_sourcefile, cpathobj,
773 NULL);
774 Py_DECREF(external);
775 }
Brett Cannona6473f92012-07-13 13:57:03 -0400776 if (pathobj == NULL)
777 PyErr_Clear();
778 }
779 else
780 pathobj = NULL;
781
Victor Stinner27ee0892011-03-04 12:57:09 +0000782 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
783error:
784 Py_DECREF(nameobj);
785 Py_XDECREF(pathobj);
786 Py_XDECREF(cpathobj);
787 return m;
788}
789
Brett Cannon18fc4e72014-04-04 10:01:46 -0400790static PyObject *
791module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000792{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400793 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000794
Victor Stinner27ee0892011-03-04 12:57:09 +0000795 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (m == NULL)
797 return NULL;
798 /* If the module is being reloaded, we get the old module back
799 and re-use its dict to exec the new code. */
800 d = PyModule_GetDict(m);
801 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
802 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400803 PyEval_GetBuiltins()) != 0) {
804 remove_module(name);
805 return NULL;
806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400808
Eric Snow08197a42014-05-12 17:54:55 -0600809 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400810}
811
812static PyObject *
813exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
814{
815 PyObject *modules = PyImport_GetModuleDict();
816 PyObject *v, *m;
817
818 v = PyEval_EvalCode(code_object, module_dict, module_dict);
819 if (v == NULL) {
820 remove_module(name);
821 return NULL;
822 }
823 Py_DECREF(v);
824
825 if ((m = PyDict_GetItem(modules, name)) == NULL) {
826 PyErr_Format(PyExc_ImportError,
827 "Loaded module %R not found in sys.modules",
828 name);
829 return NULL;
830 }
831
832 Py_INCREF(m);
833
834 return m;
835}
836
837PyObject*
838PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
839 PyObject *cpathname)
840{
Eric Snow32439d62015-05-02 19:15:18 -0600841 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600842 PyInterpreterState *interp = PyThreadState_GET()->interp;
843 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400844
845 d = module_dict_for_exec(name);
846 if (d == NULL) {
847 return NULL;
848 }
849
Eric Snow08197a42014-05-12 17:54:55 -0600850 if (pathname == NULL) {
851 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 }
Eric Snow32439d62015-05-02 19:15:18 -0600853 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
854 if (external == NULL)
855 return NULL;
856 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600857 &PyId__fix_up_module,
858 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600859 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600860 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600861 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600862 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 }
Eric Snow08197a42014-05-12 17:54:55 -0600864 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000865}
866
867
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000868static void
869update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 PyObject *constants, *tmp;
872 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (PyUnicode_Compare(co->co_filename, oldname))
875 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000876
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200877 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300878 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 constants = co->co_consts;
881 n = PyTuple_GET_SIZE(constants);
882 for (i = 0; i < n; i++) {
883 tmp = PyTuple_GET_ITEM(constants, i);
884 if (PyCode_Check(tmp))
885 update_code_filenames((PyCodeObject *)tmp,
886 oldname, newname);
887 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000888}
889
Victor Stinner2f42ae52011-03-20 00:41:24 +0100890static void
891update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000892{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100893 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000894
Victor Stinner2f42ae52011-03-20 00:41:24 +0100895 if (PyUnicode_Compare(co->co_filename, newname) == 0)
896 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 oldname = co->co_filename;
899 Py_INCREF(oldname);
900 update_code_filenames(co, oldname, newname);
901 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000902}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000903
Brett Cannon4caa61d2014-01-09 19:03:32 -0500904/*[clinic input]
905_imp._fix_co_filename
906
907 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
908 Code object to change.
909
910 path: unicode
911 File path to use.
912 /
913
914Changes code.co_filename to specify the passed-in file path.
915[clinic start generated code]*/
916
Brett Cannon4caa61d2014-01-09 19:03:32 -0500917static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300918_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400919 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300920/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700921
Brett Cannon4caa61d2014-01-09 19:03:32 -0500922{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500923 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700924
925 Py_RETURN_NONE;
926}
927
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000928
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000929/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700930static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000931
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000932
933/* Helper to test for built-in module */
934
935static int
Victor Stinner95872862011-03-07 18:20:56 +0100936is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000937{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200938 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200940 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (PyImport_Inittab[i].initfunc == NULL)
942 return -1;
943 else
944 return 1;
945 }
946 }
947 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000948}
949
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000950
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700951/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000952 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000953 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000954 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700955 this tells our caller that the path based finder could not find
956 a finder for this path item. Cache the result in
957 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +0000958 Returns a borrowed reference. */
959
960static PyObject *
961get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 PyObject *importer;
965 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 /* These conditions are the caller's responsibility: */
968 assert(PyList_Check(path_hooks));
969 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 nhooks = PyList_Size(path_hooks);
972 if (nhooks < 0)
973 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 importer = PyDict_GetItem(path_importer_cache, p);
976 if (importer != NULL)
977 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* set path_importer_cache[p] to None to avoid recursion */
980 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
981 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 for (j = 0; j < nhooks; j++) {
984 PyObject *hook = PyList_GetItem(path_hooks, j);
985 if (hook == NULL)
986 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100987 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (importer != NULL)
989 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
992 return NULL;
993 }
994 PyErr_Clear();
995 }
996 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400997 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 }
999 if (importer != NULL) {
1000 int err = PyDict_SetItem(path_importer_cache, p, importer);
1001 Py_DECREF(importer);
1002 if (err != 0)
1003 return NULL;
1004 }
1005 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001006}
1007
Christian Heimes9cd17752007-11-18 19:35:23 +00001008PyAPI_FUNC(PyObject *)
1009PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001011
Victor Stinner1e53bba2013-07-16 22:26:05 +02001012 path_importer_cache = PySys_GetObject("path_importer_cache");
1013 path_hooks = PySys_GetObject("path_hooks");
1014 if (path_importer_cache != NULL && path_hooks != NULL) {
1015 importer = get_path_importer(path_importer_cache,
1016 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 }
1018 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1019 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001020}
1021
Nick Coghland5cacbb2015-05-23 22:24:10 +10001022/*[clinic input]
1023_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001024
Nick Coghland5cacbb2015-05-23 22:24:10 +10001025 spec: object
1026 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001027
Nick Coghland5cacbb2015-05-23 22:24:10 +10001028Create an extension module.
1029[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001030
Nick Coghland5cacbb2015-05-23 22:24:10 +10001031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001032_imp_create_builtin(PyObject *module, PyObject *spec)
1033/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001036 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001037 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001038 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001039
Nick Coghland5cacbb2015-05-23 22:24:10 +10001040 name = PyObject_GetAttrString(spec, "name");
1041 if (name == NULL) {
1042 return NULL;
1043 }
1044
Victor Stinner5eb4f592013-11-14 22:38:52 +01001045 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001046 if (mod || PyErr_Occurred()) {
1047 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001048 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001049 return mod;
1050 }
1051
1052 namestr = PyUnicode_AsUTF8(name);
1053 if (namestr == NULL) {
1054 Py_DECREF(name);
1055 return NULL;
1056 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001059 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001060 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001062 /* Cannot re-init internal module ("sys" or "builtins") */
1063 mod = PyImport_AddModule(namestr);
1064 Py_DECREF(name);
1065 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001068 if (mod == NULL) {
1069 Py_DECREF(name);
1070 return NULL;
1071 }
1072 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1073 Py_DECREF(name);
1074 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1075 } else {
1076 /* Remember pointer to module init function. */
1077 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001078 if (def == NULL) {
1079 Py_DECREF(name);
1080 return NULL;
1081 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001082 def->m_base.m_init = p->initfunc;
1083 if (_PyImport_FixupExtensionObject(mod, name, name) < 0) {
1084 Py_DECREF(name);
1085 return NULL;
1086 }
1087 Py_DECREF(name);
1088 return mod;
1089 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 }
1091 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001092 Py_DECREF(name);
1093 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001094}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001095
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001096
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001097/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001098
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001099static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001100find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001101{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001102 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001103
Victor Stinner53dc7352011-03-20 01:50:21 +01001104 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 for (p = PyImport_FrozenModules; ; p++) {
1108 if (p->name == NULL)
1109 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001110 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 break;
1112 }
1113 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001114}
1115
Guido van Rossum79f25d91997-04-29 20:08:16 +00001116static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001117get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001118{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001119 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (p == NULL) {
1123 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001124 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 name);
1126 return NULL;
1127 }
1128 if (p->code == NULL) {
1129 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001130 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 name);
1132 return NULL;
1133 }
1134 size = p->size;
1135 if (size < 0)
1136 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001137 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001138}
1139
Brett Cannon8d110132009-03-15 02:20:16 +00001140static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001141is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001142{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001143 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (p == NULL) {
1147 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001148 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 name);
1150 return NULL;
1151 }
Brett Cannon8d110132009-03-15 02:20:16 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (size < 0)
1156 Py_RETURN_TRUE;
1157 else
1158 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001159}
1160
1161
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001162/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001163 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001164 an exception set if the initialization failed.
1165 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001166
1167int
Victor Stinner53dc7352011-03-20 01:50:21 +01001168PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001169{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001170 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001171 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 int ispackage;
1173 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001174
Victor Stinner53dc7352011-03-20 01:50:21 +01001175 p = find_frozen(name);
1176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (p == NULL)
1178 return 0;
1179 if (p->code == NULL) {
1180 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001181 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 name);
1183 return -1;
1184 }
1185 size = p->size;
1186 ispackage = (size < 0);
1187 if (ispackage)
1188 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001189 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (co == NULL)
1191 return -1;
1192 if (!PyCode_Check(co)) {
1193 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001194 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 name);
1196 goto err_return;
1197 }
1198 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001199 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001200 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001202 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (m == NULL)
1204 goto err_return;
1205 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001206 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 goto err_return;
1209 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 err = PyDict_SetItemString(d, "__path__", l);
1211 Py_DECREF(l);
1212 if (err != 0)
1213 goto err_return;
1214 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001215 d = module_dict_for_exec(name);
1216 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001217 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001218 }
1219 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (m == NULL)
1221 goto err_return;
1222 Py_DECREF(co);
1223 Py_DECREF(m);
1224 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001225err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 Py_DECREF(co);
1227 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001228}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001229
Victor Stinner53dc7352011-03-20 01:50:21 +01001230int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001231PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001232{
1233 PyObject *nameobj;
1234 int ret;
1235 nameobj = PyUnicode_InternFromString(name);
1236 if (nameobj == NULL)
1237 return -1;
1238 ret = PyImport_ImportFrozenModuleObject(nameobj);
1239 Py_DECREF(nameobj);
1240 return ret;
1241}
1242
Guido van Rossum74e6a111994-08-29 12:54:38 +00001243
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001244/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001245 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001246
Guido van Rossum79f25d91997-04-29 20:08:16 +00001247PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001248PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 PyObject *pname;
1251 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 pname = PyUnicode_FromString(name);
1254 if (pname == NULL)
1255 return NULL;
1256 result = PyImport_Import(pname);
1257 Py_DECREF(pname);
1258 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001259}
1260
Christian Heimes072c0f12008-01-03 23:01:04 +00001261/* Import a module without blocking
1262 *
1263 * At first it tries to fetch the module from sys.modules. If the module was
1264 * never loaded before it loads it with PyImport_ImportModule() unless another
1265 * thread holds the import lock. In the latter case the function raises an
1266 * ImportError instead of blocking.
1267 *
1268 * Returns the module object with incremented ref count.
1269 */
1270PyObject *
1271PyImport_ImportModuleNoBlock(const char *name)
1272{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001273 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001274}
1275
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001276
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001277/* Remove importlib frames from the traceback,
1278 * except in Verbose mode. */
1279static void
1280remove_importlib_frames(void)
1281{
1282 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001283 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001284 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001285 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001286 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001287 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001288 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001289
1290 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001291 from the traceback. We always trim chunks
1292 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001293
1294 PyErr_Fetch(&exception, &value, &base_tb);
1295 if (!exception || Py_VerboseFlag)
1296 goto done;
1297 if (PyType_IsSubtype((PyTypeObject *) exception,
1298 (PyTypeObject *) PyExc_ImportError))
1299 always_trim = 1;
1300
1301 prev_link = &base_tb;
1302 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001303 while (tb != NULL) {
1304 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1305 PyObject *next = (PyObject *) traceback->tb_next;
1306 PyFrameObject *frame = traceback->tb_frame;
1307 PyCodeObject *code = frame->f_code;
1308 int now_in_importlib;
1309
1310 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001311 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1312 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001313 if (now_in_importlib && !in_importlib) {
1314 /* This is the link to this chunk of importlib tracebacks */
1315 outer_link = prev_link;
1316 }
1317 in_importlib = now_in_importlib;
1318
1319 if (in_importlib &&
1320 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001321 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001322 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001323 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001324 prev_link = outer_link;
1325 }
1326 else {
1327 prev_link = (PyObject **) &traceback->tb_next;
1328 }
1329 tb = next;
1330 }
1331done:
1332 PyErr_Restore(exception, value, base_tb);
1333}
1334
1335
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001336static PyObject *
1337resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001338{
Eric Snowb523f842013-11-22 09:05:39 -07001339 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001340 _Py_IDENTIFIER(__package__);
1341 _Py_IDENTIFIER(__path__);
1342 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001343 _Py_IDENTIFIER(parent);
1344 PyObject *abs_name;
1345 PyObject *package = NULL;
1346 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001347 Py_ssize_t last_dot;
1348 PyObject *base;
1349 int level_up;
1350
1351 if (globals == NULL) {
1352 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1353 goto error;
1354 }
1355 if (!PyDict_Check(globals)) {
1356 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1357 goto error;
1358 }
1359 package = _PyDict_GetItemId(globals, &PyId___package__);
1360 if (package == Py_None) {
1361 package = NULL;
1362 }
1363 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1364
1365 if (package != NULL) {
1366 Py_INCREF(package);
1367 if (!PyUnicode_Check(package)) {
1368 PyErr_SetString(PyExc_TypeError, "package must be a string");
1369 goto error;
1370 }
1371 else if (spec != NULL && spec != Py_None) {
1372 int equal;
1373 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1374 if (parent == NULL) {
1375 goto error;
1376 }
1377
1378 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1379 Py_DECREF(parent);
1380 if (equal < 0) {
1381 goto error;
1382 }
1383 else if (equal == 0) {
1384 if (PyErr_WarnEx(PyExc_ImportWarning,
1385 "__package__ != __spec__.parent", 1) < 0) {
1386 goto error;
1387 }
1388 }
1389 }
1390 }
1391 else if (spec != NULL && spec != Py_None) {
1392 package = _PyObject_GetAttrId(spec, &PyId_parent);
1393 if (package == NULL) {
1394 goto error;
1395 }
1396 else if (!PyUnicode_Check(package)) {
1397 PyErr_SetString(PyExc_TypeError,
1398 "__spec__.parent must be a string");
1399 goto error;
1400 }
1401 }
1402 else {
1403 if (PyErr_WarnEx(PyExc_ImportWarning,
1404 "can't resolve package from __spec__ or __package__, "
1405 "falling back on __name__ and __path__", 1) < 0) {
1406 goto error;
1407 }
1408
1409 package = _PyDict_GetItemId(globals, &PyId___name__);
1410 if (package == NULL) {
1411 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1412 goto error;
1413 }
1414
1415 Py_INCREF(package);
1416 if (!PyUnicode_Check(package)) {
1417 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1418 goto error;
1419 }
1420
1421 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1422 Py_ssize_t dot;
1423
1424 if (PyUnicode_READY(package) < 0) {
1425 goto error;
1426 }
1427
1428 dot = PyUnicode_FindChar(package, '.',
1429 0, PyUnicode_GET_LENGTH(package), -1);
1430 if (dot == -2) {
1431 goto error;
1432 }
1433
1434 if (dot >= 0) {
1435 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1436 if (substr == NULL) {
1437 goto error;
1438 }
1439 Py_SETREF(package, substr);
1440 }
1441 }
1442 }
1443
1444 last_dot = PyUnicode_GET_LENGTH(package);
1445 if (last_dot == 0) {
1446 PyErr_SetString(PyExc_ImportError,
1447 "attempted relative import with no known parent package");
1448 goto error;
1449 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001450
1451 for (level_up = 1; level_up < level; level_up += 1) {
1452 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1453 if (last_dot == -2) {
1454 goto error;
1455 }
1456 else if (last_dot == -1) {
1457 PyErr_SetString(PyExc_ValueError,
1458 "attempted relative import beyond top-level "
1459 "package");
1460 goto error;
1461 }
1462 }
1463
1464 base = PyUnicode_Substring(package, 0, last_dot);
1465 Py_DECREF(package);
1466 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1467 return base;
1468 }
1469
1470 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1471 Py_DECREF(base);
1472 return abs_name;
1473
1474 error:
1475 Py_XDECREF(package);
1476 return NULL;
1477}
1478
1479PyObject *
1480PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1481 PyObject *locals, PyObject *fromlist,
1482 int level)
1483{
Brett Cannonfd074152012-04-14 14:10:13 -04001484 _Py_IDENTIFIER(_find_and_load);
1485 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001486 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001487 PyObject *final_mod = NULL;
1488 PyObject *mod = NULL;
1489 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001490 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001491 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001492
Brett Cannonfd074152012-04-14 14:10:13 -04001493 if (name == NULL) {
1494 PyErr_SetString(PyExc_ValueError, "Empty module name");
1495 goto error;
1496 }
1497
1498 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1499 for added performance. */
1500
1501 if (!PyUnicode_Check(name)) {
1502 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1503 goto error;
1504 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001505 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001506 goto error;
1507 }
1508 if (level < 0) {
1509 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1510 goto error;
1511 }
Brett Cannon849113a2016-01-22 15:25:50 -08001512
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001513 if (level > 0) {
1514 abs_name = resolve_name(name, globals, level);
1515 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001516 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001517 }
1518 else { /* level == 0 */
1519 if (PyUnicode_GET_LENGTH(name) == 0) {
1520 PyErr_SetString(PyExc_ValueError, "Empty module name");
1521 goto error;
1522 }
Brett Cannonfd074152012-04-14 14:10:13 -04001523 abs_name = name;
1524 Py_INCREF(abs_name);
1525 }
1526
Brett Cannonfd074152012-04-14 14:10:13 -04001527 mod = PyDict_GetItem(interp->modules, abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001528 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001529 _Py_IDENTIFIER(__spec__);
1530 _Py_IDENTIFIER(_initializing);
1531 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001532 PyObject *value = NULL;
1533 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001534 int initializing = 0;
1535
Brett Cannonfd074152012-04-14 14:10:13 -04001536 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001537 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001538 __spec__._initializing is true.
1539 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001540 stuffing the new module in sys.modules.
1541 */
Eric Snowb523f842013-11-22 09:05:39 -07001542 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1543 if (spec != NULL) {
1544 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1545 Py_DECREF(spec);
1546 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001547 if (value == NULL)
1548 PyErr_Clear();
1549 else {
1550 initializing = PyObject_IsTrue(value);
1551 Py_DECREF(value);
1552 if (initializing == -1)
1553 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001554 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001555 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1556 &PyId__lock_unlock_module, abs_name,
1557 NULL);
1558 if (value == NULL)
1559 goto error;
1560 Py_DECREF(value);
1561 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001562 }
Brett Cannonfd074152012-04-14 14:10:13 -04001563 }
1564 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001565 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001566 &PyId__find_and_load, abs_name,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001567 interp->import_func, NULL);
Brett Cannonfd074152012-04-14 14:10:13 -04001568 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001569 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001570 }
1571 }
1572
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001573 has_from = 0;
1574 if (fromlist != NULL && fromlist != Py_None) {
1575 has_from = PyObject_IsTrue(fromlist);
1576 if (has_from < 0)
1577 goto error;
1578 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001579 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001580 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1581 if (level == 0 || len > 0) {
1582 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001583
Victor Stinner744c34e2016-05-20 11:36:13 +02001584 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1585 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001586 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001587 }
1588
Victor Stinner744c34e2016-05-20 11:36:13 +02001589 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001590 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001591 final_mod = mod;
1592 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001593 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001594 }
1595
Brett Cannonfd074152012-04-14 14:10:13 -04001596 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001597 PyObject *front = PyUnicode_Substring(name, 0, dot);
1598 if (front == NULL) {
1599 goto error;
1600 }
1601
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001602 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001603 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001604 }
1605 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001606 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001607 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001608 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001609 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001610 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001611 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001612 }
Brett Cannonfd074152012-04-14 14:10:13 -04001613
1614 final_mod = PyDict_GetItem(interp->modules, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001615 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001616 if (final_mod == NULL) {
1617 PyErr_Format(PyExc_KeyError,
1618 "%R not in sys.modules as expected",
1619 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001620 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001621 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001622 Py_INCREF(final_mod);
Brett Cannonfd074152012-04-14 14:10:13 -04001623 }
1624 }
1625 else {
1626 final_mod = mod;
1627 Py_INCREF(mod);
1628 }
1629 }
1630 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001631 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001632 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001633 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001634 NULL);
1635 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001636
Brett Cannonfd074152012-04-14 14:10:13 -04001637 error:
1638 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001639 Py_XDECREF(mod);
1640 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001641 if (final_mod == NULL)
1642 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001643 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001644}
1645
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001646PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001647PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001648 PyObject *fromlist, int level)
1649{
1650 PyObject *nameobj, *mod;
1651 nameobj = PyUnicode_FromString(name);
1652 if (nameobj == NULL)
1653 return NULL;
1654 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1655 fromlist, level);
1656 Py_DECREF(nameobj);
1657 return mod;
1658}
1659
1660
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001661/* Re-import a module of any kind and return its module object, WITH
1662 INCREMENTED REFERENCE COUNT */
1663
Guido van Rossum79f25d91997-04-29 20:08:16 +00001664PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001665PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001666{
Brett Cannon62228db2012-04-29 14:38:11 -04001667 _Py_IDENTIFIER(reload);
1668 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001670 PyObject *imp = PyDict_GetItemString(modules, "imp");
1671 if (imp == NULL) {
1672 imp = PyImport_ImportModule("imp");
1673 if (imp == NULL) {
1674 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 }
Brett Cannon62228db2012-04-29 14:38:11 -04001677 else {
1678 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001680
Victor Stinner55ba38a2016-12-09 16:09:30 +01001681 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001682 Py_DECREF(imp);
1683 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001684}
1685
1686
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001687/* Higher-level import emulator which emulates the "import" statement
1688 more accurately -- it invokes the __import__() function from the
1689 builtins of the current globals. This means that the import is
1690 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001691 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001692 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001693 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001694 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001695
1696PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001697PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 static PyObject *silly_list = NULL;
1700 static PyObject *builtins_str = NULL;
1701 static PyObject *import_str = NULL;
1702 PyObject *globals = NULL;
1703 PyObject *import = NULL;
1704 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001705 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* Initialize constant string objects */
1709 if (silly_list == NULL) {
1710 import_str = PyUnicode_InternFromString("__import__");
1711 if (import_str == NULL)
1712 return NULL;
1713 builtins_str = PyUnicode_InternFromString("__builtins__");
1714 if (builtins_str == NULL)
1715 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001716 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (silly_list == NULL)
1718 return NULL;
1719 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 /* Get the builtins from current globals */
1722 globals = PyEval_GetGlobals();
1723 if (globals != NULL) {
1724 Py_INCREF(globals);
1725 builtins = PyObject_GetItem(globals, builtins_str);
1726 if (builtins == NULL)
1727 goto err;
1728 }
1729 else {
1730 /* No globals -- use standard builtins, and fake globals */
1731 builtins = PyImport_ImportModuleLevel("builtins",
1732 NULL, NULL, NULL, 0);
1733 if (builtins == NULL)
1734 return NULL;
1735 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1736 if (globals == NULL)
1737 goto err;
1738 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 /* Get the __import__ function from the builtins */
1741 if (PyDict_Check(builtins)) {
1742 import = PyObject_GetItem(builtins, import_str);
1743 if (import == NULL)
1744 PyErr_SetObject(PyExc_KeyError, import_str);
1745 }
1746 else
1747 import = PyObject_GetAttr(builtins, import_str);
1748 if (import == NULL)
1749 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001752 Always use absolute import here.
1753 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1755 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001756 if (r == NULL)
1757 goto err;
1758 Py_DECREF(r);
1759
1760 modules = PyImport_GetModuleDict();
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001761 r = PyDict_GetItemWithError(modules, module_name);
1762 if (r != NULL) {
Brett Cannonbc2eff32010-09-19 21:39:02 +00001763 Py_INCREF(r);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001764 }
1765 else if (!PyErr_Occurred()) {
1766 PyErr_SetObject(PyExc_KeyError, module_name);
1767 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001768
1769 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 Py_XDECREF(globals);
1771 Py_XDECREF(builtins);
1772 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001775}
1776
Brett Cannon4caa61d2014-01-09 19:03:32 -05001777/*[clinic input]
1778_imp.extension_suffixes
1779
1780Returns the list of file suffixes used to identify extension modules.
1781[clinic start generated code]*/
1782
Brett Cannon4caa61d2014-01-09 19:03:32 -05001783static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001784_imp_extension_suffixes_impl(PyObject *module)
1785/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001788 const char *suffix;
1789 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 list = PyList_New(0);
1792 if (list == NULL)
1793 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001794#ifdef HAVE_DYNAMIC_LOADING
1795 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1796 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 if (item == NULL) {
1798 Py_DECREF(list);
1799 return NULL;
1800 }
1801 if (PyList_Append(list, item) < 0) {
1802 Py_DECREF(list);
1803 Py_DECREF(item);
1804 return NULL;
1805 }
1806 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001807 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 }
Brett Cannon2657df42012-05-04 15:20:40 -04001809#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001811}
1812
Brett Cannon4caa61d2014-01-09 19:03:32 -05001813/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001814_imp.init_frozen
1815
1816 name: unicode
1817 /
1818
1819Initializes a frozen module.
1820[clinic start generated code]*/
1821
Brett Cannon4caa61d2014-01-09 19:03:32 -05001822static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001823_imp_init_frozen_impl(PyObject *module, PyObject *name)
1824/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 int ret;
1827 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001828
Victor Stinner53dc7352011-03-20 01:50:21 +01001829 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (ret < 0)
1831 return NULL;
1832 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001833 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001835 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 Py_XINCREF(m);
1837 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001838}
1839
Brett Cannon4caa61d2014-01-09 19:03:32 -05001840/*[clinic input]
1841_imp.get_frozen_object
1842
1843 name: unicode
1844 /
1845
1846Create a code object for a frozen module.
1847[clinic start generated code]*/
1848
Brett Cannon4caa61d2014-01-09 19:03:32 -05001849static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001850_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1851/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001854}
1855
Brett Cannon4caa61d2014-01-09 19:03:32 -05001856/*[clinic input]
1857_imp.is_frozen_package
1858
1859 name: unicode
1860 /
1861
1862Returns True if the module name is of a frozen package.
1863[clinic start generated code]*/
1864
Brett Cannon4caa61d2014-01-09 19:03:32 -05001865static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001866_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1867/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001870}
1871
Brett Cannon4caa61d2014-01-09 19:03:32 -05001872/*[clinic input]
1873_imp.is_builtin
1874
1875 name: unicode
1876 /
1877
1878Returns True if the module name corresponds to a built-in module.
1879[clinic start generated code]*/
1880
Guido van Rossum79f25d91997-04-29 20:08:16 +00001881static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001882_imp_is_builtin_impl(PyObject *module, PyObject *name)
1883/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001884{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001885 return PyLong_FromLong(is_builtin(name));
1886}
1887
1888/*[clinic input]
1889_imp.is_frozen
1890
1891 name: unicode
1892 /
1893
1894Returns True if the module name corresponds to a frozen module.
1895[clinic start generated code]*/
1896
Brett Cannon4caa61d2014-01-09 19:03:32 -05001897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001898_imp_is_frozen_impl(PyObject *module, PyObject *name)
1899/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001900{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001901 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 p = find_frozen(name);
1904 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001905}
1906
Larry Hastings1df0b352015-08-24 19:53:56 -07001907/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1908static int
1909exec_builtin_or_dynamic(PyObject *mod) {
1910 PyModuleDef *def;
1911 void *state;
1912
1913 if (!PyModule_Check(mod)) {
1914 return 0;
1915 }
1916
1917 def = PyModule_GetDef(mod);
1918 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001919 return 0;
1920 }
Brett Cannon52794db2016-09-07 17:00:43 -07001921
Larry Hastings1df0b352015-08-24 19:53:56 -07001922 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001923 if (state) {
1924 /* Already initialized; skip reload */
1925 return 0;
1926 }
Brett Cannon52794db2016-09-07 17:00:43 -07001927
Larry Hastings1df0b352015-08-24 19:53:56 -07001928 return PyModule_ExecDef(mod, def);
1929}
1930
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001931#ifdef HAVE_DYNAMIC_LOADING
1932
Brett Cannon4caa61d2014-01-09 19:03:32 -05001933/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10001934_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05001935
Nick Coghland5cacbb2015-05-23 22:24:10 +10001936 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05001937 file: object = NULL
1938 /
1939
Nick Coghland5cacbb2015-05-23 22:24:10 +10001940Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05001941[clinic start generated code]*/
1942
Brett Cannon4caa61d2014-01-09 19:03:32 -05001943static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001944_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
1945/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001946{
Nick Coghland5cacbb2015-05-23 22:24:10 +10001947 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001948 FILE *fp;
1949
Nick Coghland5cacbb2015-05-23 22:24:10 +10001950 name = PyObject_GetAttrString(spec, "name");
1951 if (name == NULL) {
1952 return NULL;
1953 }
1954
1955 path = PyObject_GetAttrString(spec, "origin");
1956 if (path == NULL) {
1957 Py_DECREF(name);
1958 return NULL;
1959 }
1960
1961 mod = _PyImport_FindExtensionObject(name, path);
1962 if (mod != NULL) {
1963 Py_DECREF(name);
1964 Py_DECREF(path);
1965 Py_INCREF(mod);
1966 return mod;
1967 }
1968
Brett Cannon4caa61d2014-01-09 19:03:32 -05001969 if (file != NULL) {
1970 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001971 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001972 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001973 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001975 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001977 else
1978 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001979
1980 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
1981
1982 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001983 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (fp)
1985 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001986 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001987}
1988
Nick Coghland5cacbb2015-05-23 22:24:10 +10001989/*[clinic input]
1990_imp.exec_dynamic -> int
1991
1992 mod: object
1993 /
1994
1995Initialize an extension module.
1996[clinic start generated code]*/
1997
1998static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001999_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2000/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002001{
Larry Hastings1df0b352015-08-24 19:53:56 -07002002 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002003}
2004
2005
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002006#endif /* HAVE_DYNAMIC_LOADING */
2007
Larry Hastings7726ac92014-01-31 22:03:12 -08002008/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002009_imp.exec_builtin -> int
2010
2011 mod: object
2012 /
2013
2014Initialize a built-in module.
2015[clinic start generated code]*/
2016
2017static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002018_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2019/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002020{
2021 return exec_builtin_or_dynamic(mod);
2022}
2023
Barry Warsaw28a691b2010-04-17 00:19:56 +00002024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002025PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002026"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002027
Guido van Rossum79f25d91997-04-29 20:08:16 +00002028static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002029 _IMP_EXTENSION_SUFFIXES_METHODDEF
2030 _IMP_LOCK_HELD_METHODDEF
2031 _IMP_ACQUIRE_LOCK_METHODDEF
2032 _IMP_RELEASE_LOCK_METHODDEF
2033 _IMP_GET_FROZEN_OBJECT_METHODDEF
2034 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002035 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002036 _IMP_INIT_FROZEN_METHODDEF
2037 _IMP_IS_BUILTIN_METHODDEF
2038 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002039 _IMP_CREATE_DYNAMIC_METHODDEF
2040 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002041 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002042 _IMP__FIX_CO_FILENAME_METHODDEF
2043 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002044};
2045
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002046
Martin v. Löwis1a214512008-06-11 05:26:20 +00002047static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002049 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 doc_imp,
2051 0,
2052 imp_methods,
2053 NULL,
2054 NULL,
2055 NULL,
2056 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002057};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002058
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002059PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002060PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 m = PyModule_Create(&impmodule);
2065 if (m == NULL)
2066 goto failure;
2067 d = PyModule_GetDict(m);
2068 if (d == NULL)
2069 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002072 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 Py_XDECREF(m);
2074 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002075}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002076
2077
Guido van Rossumb18618d2000-05-03 23:44:39 +00002078/* API for embedding applications that want to add their own entries
2079 to the table of built-in modules. This should normally be called
2080 *before* Py_Initialize(). When the table resize fails, -1 is
2081 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002082
2083 After a similar function by Just van Rossum. */
2084
2085int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002086PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 static struct _inittab *our_copy = NULL;
2089 struct _inittab *p;
2090 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 /* Count the number of entries in both tables */
2093 for (n = 0; newtab[n].name != NULL; n++)
2094 ;
2095 if (n == 0)
2096 return 0; /* Nothing to do */
2097 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2098 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* Allocate new memory for the combined table */
2101 p = our_copy;
2102 PyMem_RESIZE(p, struct _inittab, i+n+1);
2103 if (p == NULL)
2104 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 /* Copy the tables into the new memory */
2107 if (our_copy != PyImport_Inittab)
2108 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2109 PyImport_Inittab = our_copy = p;
2110 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002113}
2114
2115/* Shorthand to add a single entry given a name and a function */
2116
2117int
Brett Cannona826f322009-04-02 03:41:46 +00002118PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002123
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002124 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002128}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002129
2130#ifdef __cplusplus
2131}
2132#endif