blob: 7554bf8627225b5532a6f2ca46e1f0eaf81324dc [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 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06008#include "internal/pystate.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000010#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020012#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000013#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000014#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020015#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016
Guido van Rossum55a83382000-09-20 20:31:38 +000017#ifdef HAVE_FCNTL_H
18#include <fcntl.h>
19#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000021extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000022#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000023
Barry Warsaw28a691b2010-04-17 00:19:56 +000024#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000025
Victor Stinner95872862011-03-07 18:20:56 +010026/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000027static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000028
Guido van Rossum771c6c81997-10-31 18:37:24 +000029/* This table is defined in config.c: */
30extern struct _inittab _PyImport_Inittab[];
31
32struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000033
Victor Stinnerd0296212011-03-14 14:04:10 -040034static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000035
Brett Cannon4caa61d2014-01-09 19:03:32 -050036/*[clinic input]
37module _imp
38[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030039/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040040
41#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050042
Guido van Rossum1ae940a1995-01-02 19:04:15 +000043/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
45void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000046_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000047{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020048 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040049 initstr = PyUnicode_InternFromString("__init__");
50 if (initstr == NULL)
51 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020052 interp->builtins_copy = PyDict_Copy(interp->builtins);
53 if (interp->builtins_copy == NULL)
54 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055}
56
Guido van Rossum25ce5661997-08-02 03:10:38 +000057void
Just van Rossum52e14d62002-12-30 22:08:05 +000058_PyImportHooks_Init(void)
59{
Brett Cannonfd074152012-04-14 14:10:13 -040060 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000062
Brett Cannonfd074152012-04-14 14:10:13 -040063 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 v = PyList_New(0);
65 if (v == NULL)
66 goto error;
67 err = PySys_SetObject("meta_path", v);
68 Py_DECREF(v);
69 if (err)
70 goto error;
71 v = PyDict_New();
72 if (v == NULL)
73 goto error;
74 err = PySys_SetObject("path_importer_cache", v);
75 Py_DECREF(v);
76 if (err)
77 goto error;
78 path_hooks = PyList_New(0);
79 if (path_hooks == NULL)
80 goto error;
81 err = PySys_SetObject("path_hooks", path_hooks);
82 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000083 error:
Brett Cannonfd074152012-04-14 14:10:13 -040084 PyErr_Print();
85 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020086 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 }
Brett Cannonfd074152012-04-14 14:10:13 -040088 Py_DECREF(path_hooks);
89}
90
91void
92_PyImportZip_Init(void)
93{
94 PyObject *path_hooks, *zimpimport;
95 int err = 0;
96
97 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020098 if (path_hooks == NULL) {
99 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400100 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200101 }
Brett Cannonfd074152012-04-14 14:10:13 -0400102
103 if (Py_VerboseFlag)
104 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 zimpimport = PyImport_ImportModule("zipimport");
107 if (zimpimport == NULL) {
108 PyErr_Clear(); /* No zip import module -- okay */
109 if (Py_VerboseFlag)
110 PySys_WriteStderr("# can't import zipimport\n");
111 }
112 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200113 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200114 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
115 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 Py_DECREF(zimpimport);
117 if (zipimporter == NULL) {
118 PyErr_Clear(); /* No zipimporter object -- okay */
119 if (Py_VerboseFlag)
120 PySys_WriteStderr(
121 "# can't import zipimport.zipimporter\n");
122 }
123 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400124 /* sys.path_hooks.insert(0, zipimporter) */
125 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400127 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400129 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (Py_VerboseFlag)
131 PySys_WriteStderr(
132 "# installed zipimport hook\n");
133 }
134 }
Brett Cannonfd074152012-04-14 14:10:13 -0400135
136 return;
137
138 error:
139 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400140 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000141}
142
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000143/* Locking primitives to prevent parallel imports of the same module
144 in different threads to return with a partially loaded module.
145 These calls are serialized by the global interpreter lock. */
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
Brett Cannon4caa61d2014-01-09 19:03:32 -0500227/*[clinic input]
228_imp.lock_held
229
230Return True if the import lock is currently held, else False.
231
232On platforms without threads, return False.
233[clinic start generated code]*/
234
Brett Cannon4caa61d2014-01-09 19:03:32 -0500235static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300236_imp_lock_held_impl(PyObject *module)
237/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000238{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200239 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000240}
241
Brett Cannon4caa61d2014-01-09 19:03:32 -0500242/*[clinic input]
243_imp.acquire_lock
244
245Acquires the interpreter's import lock for the current thread.
246
247This lock should be used by import hooks to ensure thread-safety when importing
248modules. On platforms without threads, this function does nothing.
249[clinic start generated code]*/
250
Brett Cannon4caa61d2014-01-09 19:03:32 -0500251static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300252_imp_acquire_lock_impl(PyObject *module)
253/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200256 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000257}
258
Brett Cannon4caa61d2014-01-09 19:03:32 -0500259/*[clinic input]
260_imp.release_lock
261
262Release the interpreter's import lock.
263
264On platforms without threads, this function does nothing.
265[clinic start generated code]*/
266
Brett Cannon4caa61d2014-01-09 19:03:32 -0500267static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300268_imp_release_lock_impl(PyObject *module)
269/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (_PyImport_ReleaseLock() < 0) {
272 PyErr_SetString(PyExc_RuntimeError,
273 "not holding the import lock");
274 return NULL;
275 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200276 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000277}
278
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100279void
280_PyImport_Fini(void)
281{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200282 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100283 if (import_lock != NULL) {
284 PyThread_free_lock(import_lock);
285 import_lock = NULL;
286 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100287}
288
Guido van Rossum25ce5661997-08-02 03:10:38 +0000289/* Helper for sys */
290
291PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000292PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000293{
Eric Snow93c92f72017-09-13 23:46:04 -0700294 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snow3f9eee62017-09-15 16:35:20 -0600295 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700296 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600297 }
Eric Snow93c92f72017-09-13 23:46:04 -0700298 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000299}
300
Eric Snowd393c1b2017-09-14 12:18:12 -0600301/* In some corner cases it is important to be sure that the import
302 machinery has been initialized (or not cleaned up yet). For
303 example, see issue #4236 and PyModule_Create2(). */
304
305int
306_PyImport_IsInitialized(PyInterpreterState *interp)
307{
308 if (interp->modules == NULL)
309 return 0;
310 return 1;
311}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000312
Eric Snow3f9eee62017-09-15 16:35:20 -0600313PyObject *
314_PyImport_GetModuleId(struct _Py_Identifier *nameid)
315{
316 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
317 if (name == NULL) {
318 return NULL;
319 }
320 return PyImport_GetModule(name);
321}
322
323int
324_PyImport_SetModule(PyObject *name, PyObject *m)
325{
326 PyObject *modules = PyImport_GetModuleDict();
327 return PyObject_SetItem(modules, name, m);
328}
329
330int
331_PyImport_SetModuleString(const char *name, PyObject *m)
332{
333 PyObject *modules = PyImport_GetModuleDict();
334 return PyMapping_SetItemString(modules, name, m);
335}
336
337PyObject *
338PyImport_GetModule(PyObject *name)
339{
340 PyObject *m;
341 PyObject *modules = PyImport_GetModuleDict();
342 if (modules == NULL) {
343 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
344 return NULL;
345 }
346 Py_INCREF(modules);
347 if (PyDict_CheckExact(modules)) {
348 m = PyDict_GetItemWithError(modules, name); /* borrowed */
349 Py_XINCREF(m);
350 }
351 else {
352 m = PyObject_GetItem(modules, name);
353 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
354 PyErr_Clear();
355 }
356 }
357 Py_DECREF(modules);
358 return m;
359}
360
361
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000362/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200363static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 "path", "argv", "ps1", "ps2",
365 "last_type", "last_value", "last_traceback",
366 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200367 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 /* misc stuff */
369 "flags", "float_info",
370 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000371};
372
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200373static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 "stdin", "__stdin__",
375 "stdout", "__stdout__",
376 "stderr", "__stderr__",
377 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000378};
379
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000380/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000381
Guido van Rossum3f5da241990-12-20 15:06:42 +0000382void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000383PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000384{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200385 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyObject *key, *value, *dict;
387 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snowd393c1b2017-09-14 12:18:12 -0600388 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200389 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200390 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (modules == NULL)
393 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Delete some special variables first. These are common
396 places where user values hide and people complain when their
397 destructors fail. Since the modules containing them are
398 deleted *last* of all, they would come too late in the normal
399 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000400
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200401 /* XXX Perhaps these precautions are obsolete. Who knows? */
402
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200403 if (Py_VerboseFlag)
404 PySys_WriteStderr("# clear builtins._\n");
405 PyDict_SetItemString(interp->builtins, "_", Py_None);
406
407 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200409 PySys_WriteStderr("# clear sys.%s\n", *p);
410 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200412 for (p = sys_files; *p != NULL; p+=2) {
413 if (Py_VerboseFlag)
414 PySys_WriteStderr("# restore sys.%s\n", *p);
415 value = PyDict_GetItemString(interp->sysdict, *(p+1));
416 if (value == NULL)
417 value = Py_None;
418 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000420
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200421 /* We prepare a list which will receive (name, weakref) tuples of
422 modules when they are removed from sys.modules. The name is used
423 for diagnosis messages (in verbose mode), while the weakref helps
424 detect those modules which have been held alive. */
425 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200426 if (weaklist == NULL)
427 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200428
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200429#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200430 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200431 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
432 if (name && wr) { \
433 PyObject *tup = PyTuple_Pack(2, name, wr); \
434 PyList_Append(weaklist, tup); \
435 Py_XDECREF(tup); \
436 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200437 Py_XDECREF(wr); \
438 if (PyErr_Occurred()) \
439 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600441#define CLEAR_MODULE(name, mod) \
442 if (PyModule_Check(mod)) { \
443 if (Py_VerboseFlag && PyUnicode_Check(name)) \
444 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
445 STORE_MODULE_WEAKREF(name, mod); \
446 PyObject_SetItem(modules, name, Py_None); \
447 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000448
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200449 /* Remove all modules from sys.modules, hoping that garbage collection
450 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600451 if (PyDict_CheckExact(modules)) {
452 pos = 0;
453 while (PyDict_Next(modules, &pos, &key, &value)) {
454 CLEAR_MODULE(key, value);
455 }
456 }
457 else {
458 PyObject *iterator = PyObject_GetIter(modules);
459 if (iterator == NULL) {
460 PyErr_Clear();
461 }
462 else {
463 while ((key = PyIter_Next(iterator))) {
464 value = PyObject_GetItem(modules, key);
465 if (value == NULL) {
466 PyErr_Clear();
467 continue;
468 }
469 CLEAR_MODULE(key, value);
470 Py_DECREF(value);
471 Py_DECREF(key);
472 }
473 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 }
475 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000476
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200477 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600478 if (PyDict_CheckExact(modules)) {
479 PyDict_Clear(modules);
480 }
481 else {
482 _Py_IDENTIFIER(clear);
483 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL)
484 PyErr_Clear();
485 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200486 /* Restore the original builtins dict, to ensure that any
487 user data gets cleared. */
488 dict = PyDict_Copy(interp->builtins);
489 if (dict == NULL)
490 PyErr_Clear();
491 PyDict_Clear(interp->builtins);
492 if (PyDict_Update(interp->builtins, interp->builtins_copy))
493 PyErr_Clear();
494 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200495 /* Clear module dict copies stored in the interpreter state */
496 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200497 /* Collect references */
498 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200499 /* Dump GC stats before it's too late, since it uses the warnings
500 machinery. */
501 _PyGC_DumpShutdownStats();
502
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200503 /* Now, if there are any modules left alive, clear their globals to
504 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200505 up here, since they are kept alive in the interpreter state.
506
507 The special treatment of "builtins" here is because even
508 when it's not referenced as a module, its dictionary is
509 referenced by almost every module's __builtins__. Since
510 deleting a module clears its dictionary (even if there are
511 references left to it), we need to delete the "builtins"
512 module last. Likewise, we don't delete sys until the very
513 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200514 if (weaklist != NULL) {
515 Py_ssize_t i, n;
516 n = PyList_GET_SIZE(weaklist);
517 for (i = 0; i < n; i++) {
518 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200519 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200520 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
521 if (mod == Py_None)
522 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200523 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200524 dict = PyModule_GetDict(mod);
525 if (dict == interp->builtins || dict == interp->sysdict)
526 continue;
527 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200528 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200529 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200530 _PyModule_Clear(mod);
531 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200532 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200533 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000535
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200536 /* Next, delete sys and builtins (in that order) */
537 if (Py_VerboseFlag)
538 PySys_FormatStderr("# cleanup[3] wiping sys\n");
539 _PyModule_ClearDict(interp->sysdict);
540 if (Py_VerboseFlag)
541 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
542 _PyModule_ClearDict(interp->builtins);
543
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200544 /* Clear and delete the modules directory. Actual modules will
545 still be there only if imported during the execution of some
546 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700547 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200549
550 /* Once more */
551 _PyGC_CollectNoFail();
552
553#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000554}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000555
556
Barry Warsaw28a691b2010-04-17 00:19:56 +0000557/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000558
559long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000560PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000561{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200562 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400563 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600564 PyObject *external, *pyc_magic;
565
566 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
567 if (external == NULL)
568 return -1;
569 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
570 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400571 if (pyc_magic == NULL)
572 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200573 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700574 Py_DECREF(pyc_magic);
575 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000576}
577
578
Brett Cannon3adc7b72012-07-09 14:22:12 -0400579extern const char * _PySys_ImplCacheTag;
580
Barry Warsaw28a691b2010-04-17 00:19:56 +0000581const char *
582PyImport_GetMagicTag(void)
583{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400584 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000585}
586
Brett Cannon98979b82012-07-02 15:13:11 -0400587
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588/* Magic for extension modules (built-in as well as dynamically
589 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200590 once, we keep a static dictionary 'extensions' keyed by the tuple
591 (module name, module name) (for built-in modules) or by
592 (filename, module name) (for dynamically loaded modules), containing these
593 modules. A copy of the module's dictionary is stored by calling
594 _PyImport_FixupExtensionObject() immediately after the module initialization
595 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100596 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000597
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000598 Modules which do support multiple initialization set their m_size
599 field to a non-negative number (indicating the size of the
600 module-specific state). They are still recorded in the extensions
601 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000602*/
603
604int
Victor Stinner95872862011-03-07 18:20:56 +0100605_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600606 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000607{
Eric Snowd393c1b2017-09-14 12:18:12 -0600608 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500610 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (extensions == NULL) {
612 extensions = PyDict_New();
613 if (extensions == NULL)
614 return -1;
615 }
616 if (mod == NULL || !PyModule_Check(mod)) {
617 PyErr_BadInternalCall();
618 return -1;
619 }
620 def = PyModule_GetDef(mod);
621 if (!def) {
622 PyErr_BadInternalCall();
623 return -1;
624 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600625 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return -1;
627 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600628 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return -1;
630 }
631 if (def->m_size == -1) {
632 if (def->m_base.m_copy) {
633 /* Somebody already imported the module,
634 likely under a different name.
635 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200636 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
638 dict = PyModule_GetDict(mod);
639 if (dict == NULL)
640 return -1;
641 def->m_base.m_copy = PyDict_Copy(dict);
642 if (def->m_base.m_copy == NULL)
643 return -1;
644 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500645 key = PyTuple_Pack(2, filename, name);
646 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200647 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500648 res = PyDict_SetItem(extensions, key, (PyObject *)def);
649 Py_DECREF(key);
650 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200651 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653}
654
Victor Stinner49d3f252010-10-17 01:24:53 +0000655int
Eric Snowd393c1b2017-09-14 12:18:12 -0600656_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000657{
658 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100659 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100660 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100661 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000662 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600663 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100664 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000665 return res;
666}
667
Guido van Rossum25ce5661997-08-02 03:10:38 +0000668PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100669_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670{
Eric Snowd393c1b2017-09-14 12:18:12 -0600671 PyObject *modules = PyImport_GetModuleDict();
672 return _PyImport_FindExtensionObjectEx(name, filename, modules);
673}
674
675PyObject *
676_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
677 PyObject *modules)
678{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500679 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 PyModuleDef* def;
681 if (extensions == NULL)
682 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500683 key = PyTuple_Pack(2, filename, name);
684 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200685 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500686 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
687 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (def == NULL)
689 return NULL;
690 if (def->m_size == -1) {
691 /* Module does not support repeated initialization */
692 if (def->m_base.m_copy == NULL)
693 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600694 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (mod == NULL)
696 return NULL;
697 mdict = PyModule_GetDict(mod);
698 if (mdict == NULL)
699 return NULL;
700 if (PyDict_Update(mdict, def->m_base.m_copy))
701 return NULL;
702 }
703 else {
704 if (def->m_base.m_init == NULL)
705 return NULL;
706 mod = def->m_base.m_init();
707 if (mod == NULL)
708 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600709 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200710 Py_DECREF(mod);
711 return NULL;
712 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 Py_DECREF(mod);
714 }
715 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600716 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 Py_DECREF(mod);
718 return NULL;
719 }
720 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100721 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 name, filename);
723 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000724
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000725}
726
Victor Stinner49d3f252010-10-17 01:24:53 +0000727PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600728_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000729{
Victor Stinner95872862011-03-07 18:20:56 +0100730 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100731 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100732 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000733 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600734 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100735 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000736 return res;
737}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000738
739/* Get the module object corresponding to a module name.
740 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000741 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000742 Because the former action is most common, THIS DOES NOT RETURN A
743 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000744
Guido van Rossum79f25d91997-04-29 20:08:16 +0000745PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000746PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600749 return _PyImport_AddModuleObject(name, modules);
750}
751
752PyObject *
753_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
754{
Eric Snow86b7afd2017-09-04 17:54:09 -0600755 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600756 if (PyDict_CheckExact(modules)) {
757 m = PyDict_GetItemWithError(modules, name);
758 }
759 else {
760 m = PyObject_GetItem(modules, name);
761 // For backward-comaptibility we copy the behavior
762 // of PyDict_GetItemWithError().
763 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
764 PyErr_Clear();
765 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200766 }
767 if (PyErr_Occurred()) {
768 return NULL;
769 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600770 if (m != NULL && PyModule_Check(m)) {
771 return m;
772 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000773 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 if (m == NULL)
775 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600776 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 Py_DECREF(m);
778 return NULL;
779 }
780 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783}
784
Victor Stinner27ee0892011-03-04 12:57:09 +0000785PyObject *
786PyImport_AddModule(const char *name)
787{
788 PyObject *nameobj, *module;
789 nameobj = PyUnicode_FromString(name);
790 if (nameobj == NULL)
791 return NULL;
792 module = PyImport_AddModuleObject(nameobj);
793 Py_DECREF(nameobj);
794 return module;
795}
796
797
Tim Peters1cd70172004-08-02 03:52:12 +0000798/* Remove name from sys.modules, if it's there. */
799static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000800remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyObject *modules = PyImport_GetModuleDict();
Eric Snow3f9eee62017-09-15 16:35:20 -0600803 if (PyMapping_DelItem(modules, name) < 0) {
804 if (!PyMapping_HasKey(modules, name)) {
805 return;
806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 Py_FatalError("import: deleting existing key in"
808 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600809 }
Tim Peters1cd70172004-08-02 03:52:12 +0000810}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000811
Christian Heimes3b06e532008-01-07 20:12:44 +0000812
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000813/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000814 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
815 * removed from sys.modules, to avoid leaving damaged module objects
816 * in sys.modules. The caller may wish to restore the original
817 * module object (if any) in this case; PyImport_ReloadModule is an
818 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000819 *
820 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
821 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000822 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000823PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300824PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 return PyImport_ExecCodeModuleWithPathnames(
827 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000828}
829
830PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300831PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 return PyImport_ExecCodeModuleWithPathnames(
834 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000835}
836
837PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300838PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
839 const char *pathname,
840 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000841{
Victor Stinner27ee0892011-03-04 12:57:09 +0000842 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600843 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000844
845 nameobj = PyUnicode_FromString(name);
846 if (nameobj == NULL)
847 return NULL;
848
Victor Stinner27ee0892011-03-04 12:57:09 +0000849 if (cpathname != NULL) {
850 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
851 if (cpathobj == NULL)
852 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400853 }
854 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000855 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400856
857 if (pathname != NULL) {
858 pathobj = PyUnicode_DecodeFSDefault(pathname);
859 if (pathobj == NULL)
860 goto error;
861 }
862 else if (cpathobj != NULL) {
863 PyInterpreterState *interp = PyThreadState_GET()->interp;
864 _Py_IDENTIFIER(_get_sourcefile);
865
866 if (interp == NULL) {
867 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
868 "no interpreter!");
869 }
870
Eric Snow32439d62015-05-02 19:15:18 -0600871 external= PyObject_GetAttrString(interp->importlib,
872 "_bootstrap_external");
873 if (external != NULL) {
874 pathobj = _PyObject_CallMethodIdObjArgs(external,
875 &PyId__get_sourcefile, cpathobj,
876 NULL);
877 Py_DECREF(external);
878 }
Brett Cannona6473f92012-07-13 13:57:03 -0400879 if (pathobj == NULL)
880 PyErr_Clear();
881 }
882 else
883 pathobj = NULL;
884
Victor Stinner27ee0892011-03-04 12:57:09 +0000885 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
886error:
887 Py_DECREF(nameobj);
888 Py_XDECREF(pathobj);
889 Py_XDECREF(cpathobj);
890 return m;
891}
892
Brett Cannon18fc4e72014-04-04 10:01:46 -0400893static PyObject *
894module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000895{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400896 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000897
Victor Stinner27ee0892011-03-04 12:57:09 +0000898 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (m == NULL)
900 return NULL;
901 /* If the module is being reloaded, we get the old module back
902 and re-use its dict to exec the new code. */
903 d = PyModule_GetDict(m);
904 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
905 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400906 PyEval_GetBuiltins()) != 0) {
907 remove_module(name);
908 return NULL;
909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400911
Eric Snow08197a42014-05-12 17:54:55 -0600912 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400913}
914
915static PyObject *
916exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
917{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400918 PyObject *v, *m;
919
920 v = PyEval_EvalCode(code_object, module_dict, module_dict);
921 if (v == NULL) {
922 remove_module(name);
923 return NULL;
924 }
925 Py_DECREF(v);
926
Eric Snow3f9eee62017-09-15 16:35:20 -0600927 m = PyImport_GetModule(name);
928 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400929 PyErr_Format(PyExc_ImportError,
930 "Loaded module %R not found in sys.modules",
931 name);
932 return NULL;
933 }
934
Brett Cannon18fc4e72014-04-04 10:01:46 -0400935 return m;
936}
937
938PyObject*
939PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
940 PyObject *cpathname)
941{
Eric Snow32439d62015-05-02 19:15:18 -0600942 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600943 PyInterpreterState *interp = PyThreadState_GET()->interp;
944 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400945
946 d = module_dict_for_exec(name);
947 if (d == NULL) {
948 return NULL;
949 }
950
Eric Snow08197a42014-05-12 17:54:55 -0600951 if (pathname == NULL) {
952 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 }
Eric Snow32439d62015-05-02 19:15:18 -0600954 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
955 if (external == NULL)
956 return NULL;
957 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600958 &PyId__fix_up_module,
959 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600960 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600961 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600962 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600963 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
Eric Snow08197a42014-05-12 17:54:55 -0600965 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000966}
967
968
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000969static void
970update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 PyObject *constants, *tmp;
973 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (PyUnicode_Compare(co->co_filename, oldname))
976 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000977
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200978 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300979 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 constants = co->co_consts;
982 n = PyTuple_GET_SIZE(constants);
983 for (i = 0; i < n; i++) {
984 tmp = PyTuple_GET_ITEM(constants, i);
985 if (PyCode_Check(tmp))
986 update_code_filenames((PyCodeObject *)tmp,
987 oldname, newname);
988 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000989}
990
Victor Stinner2f42ae52011-03-20 00:41:24 +0100991static void
992update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000993{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100994 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000995
Victor Stinner2f42ae52011-03-20 00:41:24 +0100996 if (PyUnicode_Compare(co->co_filename, newname) == 0)
997 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 oldname = co->co_filename;
1000 Py_INCREF(oldname);
1001 update_code_filenames(co, oldname, newname);
1002 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001003}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001004
Brett Cannon4caa61d2014-01-09 19:03:32 -05001005/*[clinic input]
1006_imp._fix_co_filename
1007
1008 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1009 Code object to change.
1010
1011 path: unicode
1012 File path to use.
1013 /
1014
1015Changes code.co_filename to specify the passed-in file path.
1016[clinic start generated code]*/
1017
Brett Cannon4caa61d2014-01-09 19:03:32 -05001018static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001019_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001020 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001021/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001022
Brett Cannon4caa61d2014-01-09 19:03:32 -05001023{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001024 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001025
1026 Py_RETURN_NONE;
1027}
1028
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001029
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001030/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001031static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001032
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001033
1034/* Helper to test for built-in module */
1035
1036static int
Victor Stinner95872862011-03-07 18:20:56 +01001037is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001038{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001039 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001041 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (PyImport_Inittab[i].initfunc == NULL)
1043 return -1;
1044 else
1045 return 1;
1046 }
1047 }
1048 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001049}
1050
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001051
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001052/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001053 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001054 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001055 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001056 this tells our caller that the path based finder could not find
1057 a finder for this path item. Cache the result in
1058 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001059 Returns a borrowed reference. */
1060
1061static PyObject *
1062get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyObject *importer;
1066 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 /* These conditions are the caller's responsibility: */
1069 assert(PyList_Check(path_hooks));
1070 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 nhooks = PyList_Size(path_hooks);
1073 if (nhooks < 0)
1074 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 importer = PyDict_GetItem(path_importer_cache, p);
1077 if (importer != NULL)
1078 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* set path_importer_cache[p] to None to avoid recursion */
1081 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1082 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 for (j = 0; j < nhooks; j++) {
1085 PyObject *hook = PyList_GetItem(path_hooks, j);
1086 if (hook == NULL)
1087 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001088 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 if (importer != NULL)
1090 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1093 return NULL;
1094 }
1095 PyErr_Clear();
1096 }
1097 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001098 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 }
1100 if (importer != NULL) {
1101 int err = PyDict_SetItem(path_importer_cache, p, importer);
1102 Py_DECREF(importer);
1103 if (err != 0)
1104 return NULL;
1105 }
1106 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001107}
1108
Christian Heimes9cd17752007-11-18 19:35:23 +00001109PyAPI_FUNC(PyObject *)
1110PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001112
Victor Stinner1e53bba2013-07-16 22:26:05 +02001113 path_importer_cache = PySys_GetObject("path_importer_cache");
1114 path_hooks = PySys_GetObject("path_hooks");
1115 if (path_importer_cache != NULL && path_hooks != NULL) {
1116 importer = get_path_importer(path_importer_cache,
1117 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 }
1119 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1120 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001121}
1122
Nick Coghland5cacbb2015-05-23 22:24:10 +10001123/*[clinic input]
1124_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001125
Nick Coghland5cacbb2015-05-23 22:24:10 +10001126 spec: object
1127 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001128
Nick Coghland5cacbb2015-05-23 22:24:10 +10001129Create an extension module.
1130[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001131
Nick Coghland5cacbb2015-05-23 22:24:10 +10001132static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001133_imp_create_builtin(PyObject *module, PyObject *spec)
1134/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001137 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001138 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001139 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001140
Nick Coghland5cacbb2015-05-23 22:24:10 +10001141 name = PyObject_GetAttrString(spec, "name");
1142 if (name == NULL) {
1143 return NULL;
1144 }
1145
Victor Stinner5eb4f592013-11-14 22:38:52 +01001146 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001147 if (mod || PyErr_Occurred()) {
1148 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001149 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001150 return mod;
1151 }
1152
1153 namestr = PyUnicode_AsUTF8(name);
1154 if (namestr == NULL) {
1155 Py_DECREF(name);
1156 return NULL;
1157 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001158
Eric Snowd393c1b2017-09-14 12:18:12 -06001159 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001161 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001162 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001164 /* Cannot re-init internal module ("sys" or "builtins") */
1165 mod = PyImport_AddModule(namestr);
1166 Py_DECREF(name);
1167 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001170 if (mod == NULL) {
1171 Py_DECREF(name);
1172 return NULL;
1173 }
1174 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1175 Py_DECREF(name);
1176 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1177 } else {
1178 /* Remember pointer to module init function. */
1179 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001180 if (def == NULL) {
1181 Py_DECREF(name);
1182 return NULL;
1183 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001184 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001185 if (modules == NULL) {
1186 modules = PyImport_GetModuleDict();
1187 }
1188 if (_PyImport_FixupExtensionObject(mod, name, name,
1189 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001190 Py_DECREF(name);
1191 return NULL;
1192 }
1193 Py_DECREF(name);
1194 return mod;
1195 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 }
1197 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001198 Py_DECREF(name);
1199 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001200}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001201
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001202
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001203/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001204
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001205static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001206find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001207{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001208 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001209
Victor Stinner53dc7352011-03-20 01:50:21 +01001210 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 for (p = PyImport_FrozenModules; ; p++) {
1214 if (p->name == NULL)
1215 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001216 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 break;
1218 }
1219 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001220}
1221
Guido van Rossum79f25d91997-04-29 20:08:16 +00001222static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001223get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001224{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001225 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (p == NULL) {
1229 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001230 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 name);
1232 return NULL;
1233 }
1234 if (p->code == NULL) {
1235 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001236 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 name);
1238 return NULL;
1239 }
1240 size = p->size;
1241 if (size < 0)
1242 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001243 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001244}
1245
Brett Cannon8d110132009-03-15 02:20:16 +00001246static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001247is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001248{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001249 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (p == NULL) {
1253 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001254 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 name);
1256 return NULL;
1257 }
Brett Cannon8d110132009-03-15 02:20:16 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (size < 0)
1262 Py_RETURN_TRUE;
1263 else
1264 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001265}
1266
1267
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001268/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001269 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001270 an exception set if the initialization failed.
1271 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001272
1273int
Victor Stinner53dc7352011-03-20 01:50:21 +01001274PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001275{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001276 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001277 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 int ispackage;
1279 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001280
Victor Stinner53dc7352011-03-20 01:50:21 +01001281 p = find_frozen(name);
1282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (p == NULL)
1284 return 0;
1285 if (p->code == NULL) {
1286 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001287 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 name);
1289 return -1;
1290 }
1291 size = p->size;
1292 ispackage = (size < 0);
1293 if (ispackage)
1294 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001295 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (co == NULL)
1297 return -1;
1298 if (!PyCode_Check(co)) {
1299 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001300 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 name);
1302 goto err_return;
1303 }
1304 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001305 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001306 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001308 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (m == NULL)
1310 goto err_return;
1311 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001312 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 goto err_return;
1315 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 err = PyDict_SetItemString(d, "__path__", l);
1317 Py_DECREF(l);
1318 if (err != 0)
1319 goto err_return;
1320 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001321 d = module_dict_for_exec(name);
1322 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001323 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001324 }
1325 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (m == NULL)
1327 goto err_return;
1328 Py_DECREF(co);
1329 Py_DECREF(m);
1330 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001331err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_DECREF(co);
1333 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001334}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001335
Victor Stinner53dc7352011-03-20 01:50:21 +01001336int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001337PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001338{
1339 PyObject *nameobj;
1340 int ret;
1341 nameobj = PyUnicode_InternFromString(name);
1342 if (nameobj == NULL)
1343 return -1;
1344 ret = PyImport_ImportFrozenModuleObject(nameobj);
1345 Py_DECREF(nameobj);
1346 return ret;
1347}
1348
Guido van Rossum74e6a111994-08-29 12:54:38 +00001349
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001350/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001351 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001352
Guido van Rossum79f25d91997-04-29 20:08:16 +00001353PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001354PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyObject *pname;
1357 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 pname = PyUnicode_FromString(name);
1360 if (pname == NULL)
1361 return NULL;
1362 result = PyImport_Import(pname);
1363 Py_DECREF(pname);
1364 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001365}
1366
Christian Heimes072c0f12008-01-03 23:01:04 +00001367/* Import a module without blocking
1368 *
1369 * At first it tries to fetch the module from sys.modules. If the module was
1370 * never loaded before it loads it with PyImport_ImportModule() unless another
1371 * thread holds the import lock. In the latter case the function raises an
1372 * ImportError instead of blocking.
1373 *
1374 * Returns the module object with incremented ref count.
1375 */
1376PyObject *
1377PyImport_ImportModuleNoBlock(const char *name)
1378{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001379 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001380}
1381
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001382
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001383/* Remove importlib frames from the traceback,
1384 * except in Verbose mode. */
1385static void
1386remove_importlib_frames(void)
1387{
1388 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001389 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001390 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001391 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001392 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001393 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001394 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001395
1396 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001397 from the traceback. We always trim chunks
1398 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001399
1400 PyErr_Fetch(&exception, &value, &base_tb);
1401 if (!exception || Py_VerboseFlag)
1402 goto done;
1403 if (PyType_IsSubtype((PyTypeObject *) exception,
1404 (PyTypeObject *) PyExc_ImportError))
1405 always_trim = 1;
1406
1407 prev_link = &base_tb;
1408 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001409 while (tb != NULL) {
1410 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1411 PyObject *next = (PyObject *) traceback->tb_next;
1412 PyFrameObject *frame = traceback->tb_frame;
1413 PyCodeObject *code = frame->f_code;
1414 int now_in_importlib;
1415
1416 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001417 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1418 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001419 if (now_in_importlib && !in_importlib) {
1420 /* This is the link to this chunk of importlib tracebacks */
1421 outer_link = prev_link;
1422 }
1423 in_importlib = now_in_importlib;
1424
1425 if (in_importlib &&
1426 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001427 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001428 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001429 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001430 prev_link = outer_link;
1431 }
1432 else {
1433 prev_link = (PyObject **) &traceback->tb_next;
1434 }
1435 tb = next;
1436 }
1437done:
1438 PyErr_Restore(exception, value, base_tb);
1439}
1440
1441
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001442static PyObject *
1443resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001444{
Eric Snowb523f842013-11-22 09:05:39 -07001445 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001446 _Py_IDENTIFIER(__package__);
1447 _Py_IDENTIFIER(__path__);
1448 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001449 _Py_IDENTIFIER(parent);
1450 PyObject *abs_name;
1451 PyObject *package = NULL;
1452 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001453 Py_ssize_t last_dot;
1454 PyObject *base;
1455 int level_up;
1456
1457 if (globals == NULL) {
1458 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1459 goto error;
1460 }
1461 if (!PyDict_Check(globals)) {
1462 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1463 goto error;
1464 }
1465 package = _PyDict_GetItemId(globals, &PyId___package__);
1466 if (package == Py_None) {
1467 package = NULL;
1468 }
1469 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1470
1471 if (package != NULL) {
1472 Py_INCREF(package);
1473 if (!PyUnicode_Check(package)) {
1474 PyErr_SetString(PyExc_TypeError, "package must be a string");
1475 goto error;
1476 }
1477 else if (spec != NULL && spec != Py_None) {
1478 int equal;
1479 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1480 if (parent == NULL) {
1481 goto error;
1482 }
1483
1484 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1485 Py_DECREF(parent);
1486 if (equal < 0) {
1487 goto error;
1488 }
1489 else if (equal == 0) {
1490 if (PyErr_WarnEx(PyExc_ImportWarning,
1491 "__package__ != __spec__.parent", 1) < 0) {
1492 goto error;
1493 }
1494 }
1495 }
1496 }
1497 else if (spec != NULL && spec != Py_None) {
1498 package = _PyObject_GetAttrId(spec, &PyId_parent);
1499 if (package == NULL) {
1500 goto error;
1501 }
1502 else if (!PyUnicode_Check(package)) {
1503 PyErr_SetString(PyExc_TypeError,
1504 "__spec__.parent must be a string");
1505 goto error;
1506 }
1507 }
1508 else {
1509 if (PyErr_WarnEx(PyExc_ImportWarning,
1510 "can't resolve package from __spec__ or __package__, "
1511 "falling back on __name__ and __path__", 1) < 0) {
1512 goto error;
1513 }
1514
1515 package = _PyDict_GetItemId(globals, &PyId___name__);
1516 if (package == NULL) {
1517 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1518 goto error;
1519 }
1520
1521 Py_INCREF(package);
1522 if (!PyUnicode_Check(package)) {
1523 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1524 goto error;
1525 }
1526
1527 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1528 Py_ssize_t dot;
1529
1530 if (PyUnicode_READY(package) < 0) {
1531 goto error;
1532 }
1533
1534 dot = PyUnicode_FindChar(package, '.',
1535 0, PyUnicode_GET_LENGTH(package), -1);
1536 if (dot == -2) {
1537 goto error;
1538 }
1539
1540 if (dot >= 0) {
1541 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1542 if (substr == NULL) {
1543 goto error;
1544 }
1545 Py_SETREF(package, substr);
1546 }
1547 }
1548 }
1549
1550 last_dot = PyUnicode_GET_LENGTH(package);
1551 if (last_dot == 0) {
1552 PyErr_SetString(PyExc_ImportError,
1553 "attempted relative import with no known parent package");
1554 goto error;
1555 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001556
1557 for (level_up = 1; level_up < level; level_up += 1) {
1558 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1559 if (last_dot == -2) {
1560 goto error;
1561 }
1562 else if (last_dot == -1) {
1563 PyErr_SetString(PyExc_ValueError,
1564 "attempted relative import beyond top-level "
1565 "package");
1566 goto error;
1567 }
1568 }
1569
1570 base = PyUnicode_Substring(package, 0, last_dot);
1571 Py_DECREF(package);
1572 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1573 return base;
1574 }
1575
1576 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1577 Py_DECREF(base);
1578 return abs_name;
1579
1580 error:
1581 Py_XDECREF(package);
1582 return NULL;
1583}
1584
1585PyObject *
1586PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1587 PyObject *locals, PyObject *fromlist,
1588 int level)
1589{
Brett Cannonfd074152012-04-14 14:10:13 -04001590 _Py_IDENTIFIER(_find_and_load);
1591 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001592 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001593 PyObject *final_mod = NULL;
1594 PyObject *mod = NULL;
1595 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001596 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001597 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001598
Brett Cannonfd074152012-04-14 14:10:13 -04001599 if (name == NULL) {
1600 PyErr_SetString(PyExc_ValueError, "Empty module name");
1601 goto error;
1602 }
1603
1604 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1605 for added performance. */
1606
1607 if (!PyUnicode_Check(name)) {
1608 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1609 goto error;
1610 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001611 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001612 goto error;
1613 }
1614 if (level < 0) {
1615 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1616 goto error;
1617 }
Brett Cannon849113a2016-01-22 15:25:50 -08001618
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001619 if (level > 0) {
1620 abs_name = resolve_name(name, globals, level);
1621 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001622 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001623 }
1624 else { /* level == 0 */
1625 if (PyUnicode_GET_LENGTH(name) == 0) {
1626 PyErr_SetString(PyExc_ValueError, "Empty module name");
1627 goto error;
1628 }
Brett Cannonfd074152012-04-14 14:10:13 -04001629 abs_name = name;
1630 Py_INCREF(abs_name);
1631 }
1632
Eric Snow3f9eee62017-09-15 16:35:20 -06001633 mod = PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001634 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001635 _Py_IDENTIFIER(__spec__);
1636 _Py_IDENTIFIER(_initializing);
1637 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001638 PyObject *value = NULL;
1639 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001640 int initializing = 0;
1641
Antoine Pitrou03989852012-08-28 00:24:52 +02001642 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001643 __spec__._initializing is true.
1644 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001645 stuffing the new module in sys.modules.
1646 */
Eric Snowb523f842013-11-22 09:05:39 -07001647 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1648 if (spec != NULL) {
1649 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1650 Py_DECREF(spec);
1651 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001652 if (value == NULL)
1653 PyErr_Clear();
1654 else {
1655 initializing = PyObject_IsTrue(value);
1656 Py_DECREF(value);
1657 if (initializing == -1)
1658 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001659 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001660 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1661 &PyId__lock_unlock_module, abs_name,
1662 NULL);
1663 if (value == NULL)
1664 goto error;
1665 Py_DECREF(value);
1666 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001667 }
Brett Cannonfd074152012-04-14 14:10:13 -04001668 }
1669 else {
INADA Naoki1a87de72017-10-03 19:46:34 +09001670 static int ximporttime = 0;
1671 static int import_level;
1672 static _PyTime_t accumulated;
1673 _Py_IDENTIFIER(importtime);
1674
1675 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1676
Eric Snow3f9eee62017-09-15 16:35:20 -06001677 Py_XDECREF(mod);
Christian Heimes3d2b4072017-09-30 00:53:19 +02001678
INADA Naoki1a87de72017-10-03 19:46:34 +09001679 /* XOptions is initialized after first some imports.
1680 * So we can't have negative cache.
1681 * Anyway, importlib.__find_and_load is much slower than
1682 * _PyDict_GetItemId()
1683 */
1684 if (ximporttime == 0) {
1685 PyObject *xoptions = PySys_GetXOptions();
1686 if (xoptions) {
1687 PyObject *value = _PyDict_GetItemId(xoptions, &PyId_importtime);
1688 ximporttime = (value == Py_True);
1689 }
1690 if (ximporttime) {
1691 fputs("import time: self [us] | cumulative | imported package\n",
1692 stderr);
1693 }
1694 }
1695
1696 if (ximporttime) {
1697 import_level++;
1698 t1 = _PyTime_GetMonotonicClock();
1699 accumulated = 0;
1700 }
1701
Christian Heimes3d2b4072017-09-30 00:53:19 +02001702 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1703 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1704
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001705 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001706 &PyId__find_and_load, abs_name,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001707 interp->import_func, NULL);
Christian Heimes3d2b4072017-09-30 00:53:19 +02001708
1709 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1710 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1711 mod != NULL);
1712
INADA Naoki1a87de72017-10-03 19:46:34 +09001713 if (ximporttime) {
1714 _PyTime_t cum = _PyTime_GetMonotonicClock() - t1;
1715
1716 import_level--;
1717 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1718 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1719 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1720 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1721
1722 accumulated = accumulated_copy + cum;
1723 }
1724
Brett Cannonfd074152012-04-14 14:10:13 -04001725 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001726 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001727 }
1728 }
1729
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001730 has_from = 0;
1731 if (fromlist != NULL && fromlist != Py_None) {
1732 has_from = PyObject_IsTrue(fromlist);
1733 if (has_from < 0)
1734 goto error;
1735 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001736 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001737 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1738 if (level == 0 || len > 0) {
1739 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001740
Victor Stinner744c34e2016-05-20 11:36:13 +02001741 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1742 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001743 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001744 }
1745
Victor Stinner744c34e2016-05-20 11:36:13 +02001746 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001747 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001748 final_mod = mod;
1749 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001750 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001751 }
1752
Brett Cannonfd074152012-04-14 14:10:13 -04001753 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001754 PyObject *front = PyUnicode_Substring(name, 0, dot);
1755 if (front == NULL) {
1756 goto error;
1757 }
1758
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001759 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001760 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001761 }
1762 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001763 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001764 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001765 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001766 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001767 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001768 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001769 }
Brett Cannonfd074152012-04-14 14:10:13 -04001770
Eric Snow3f9eee62017-09-15 16:35:20 -06001771 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001772 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001773 if (final_mod == NULL) {
1774 PyErr_Format(PyExc_KeyError,
1775 "%R not in sys.modules as expected",
1776 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001777 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001778 }
Brett Cannonfd074152012-04-14 14:10:13 -04001779 }
1780 }
1781 else {
1782 final_mod = mod;
1783 Py_INCREF(mod);
1784 }
1785 }
1786 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001787 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001788 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001789 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001790 NULL);
1791 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001792
Brett Cannonfd074152012-04-14 14:10:13 -04001793 error:
1794 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001795 Py_XDECREF(mod);
1796 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001797 if (final_mod == NULL)
1798 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001799 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001800}
1801
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001802PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001803PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001804 PyObject *fromlist, int level)
1805{
1806 PyObject *nameobj, *mod;
1807 nameobj = PyUnicode_FromString(name);
1808 if (nameobj == NULL)
1809 return NULL;
1810 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1811 fromlist, level);
1812 Py_DECREF(nameobj);
1813 return mod;
1814}
1815
1816
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001817/* Re-import a module of any kind and return its module object, WITH
1818 INCREMENTED REFERENCE COUNT */
1819
Guido van Rossum79f25d91997-04-29 20:08:16 +00001820PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001821PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001822{
Eric Snow3f9eee62017-09-15 16:35:20 -06001823 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001824 _Py_IDENTIFIER(reload);
1825 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001826 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001827 if (imp == NULL) {
1828 imp = PyImport_ImportModule("imp");
1829 if (imp == NULL) {
1830 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001833
Victor Stinner55ba38a2016-12-09 16:09:30 +01001834 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001835 Py_DECREF(imp);
1836 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001837}
1838
1839
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001840/* Higher-level import emulator which emulates the "import" statement
1841 more accurately -- it invokes the __import__() function from the
1842 builtins of the current globals. This means that the import is
1843 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001844 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001845 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001846 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001847 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001848
1849PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001850PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 static PyObject *silly_list = NULL;
1853 static PyObject *builtins_str = NULL;
1854 static PyObject *import_str = NULL;
1855 PyObject *globals = NULL;
1856 PyObject *import = NULL;
1857 PyObject *builtins = NULL;
1858 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 /* Initialize constant string objects */
1861 if (silly_list == NULL) {
1862 import_str = PyUnicode_InternFromString("__import__");
1863 if (import_str == NULL)
1864 return NULL;
1865 builtins_str = PyUnicode_InternFromString("__builtins__");
1866 if (builtins_str == NULL)
1867 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001868 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (silly_list == NULL)
1870 return NULL;
1871 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 /* Get the builtins from current globals */
1874 globals = PyEval_GetGlobals();
1875 if (globals != NULL) {
1876 Py_INCREF(globals);
1877 builtins = PyObject_GetItem(globals, builtins_str);
1878 if (builtins == NULL)
1879 goto err;
1880 }
1881 else {
1882 /* No globals -- use standard builtins, and fake globals */
1883 builtins = PyImport_ImportModuleLevel("builtins",
1884 NULL, NULL, NULL, 0);
1885 if (builtins == NULL)
1886 return NULL;
1887 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1888 if (globals == NULL)
1889 goto err;
1890 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 /* Get the __import__ function from the builtins */
1893 if (PyDict_Check(builtins)) {
1894 import = PyObject_GetItem(builtins, import_str);
1895 if (import == NULL)
1896 PyErr_SetObject(PyExc_KeyError, import_str);
1897 }
1898 else
1899 import = PyObject_GetAttr(builtins, import_str);
1900 if (import == NULL)
1901 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001904 Always use absolute import here.
1905 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1907 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001908 if (r == NULL)
1909 goto err;
1910 Py_DECREF(r);
1911
Eric Snow3f9eee62017-09-15 16:35:20 -06001912 r = PyImport_GetModule(module_name);
1913 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001914 PyErr_SetObject(PyExc_KeyError, module_name);
1915 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001916
1917 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 Py_XDECREF(globals);
1919 Py_XDECREF(builtins);
1920 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001923}
1924
Brett Cannon4caa61d2014-01-09 19:03:32 -05001925/*[clinic input]
1926_imp.extension_suffixes
1927
1928Returns the list of file suffixes used to identify extension modules.
1929[clinic start generated code]*/
1930
Brett Cannon4caa61d2014-01-09 19:03:32 -05001931static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001932_imp_extension_suffixes_impl(PyObject *module)
1933/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001936 const char *suffix;
1937 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 list = PyList_New(0);
1940 if (list == NULL)
1941 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001942#ifdef HAVE_DYNAMIC_LOADING
1943 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1944 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (item == NULL) {
1946 Py_DECREF(list);
1947 return NULL;
1948 }
1949 if (PyList_Append(list, item) < 0) {
1950 Py_DECREF(list);
1951 Py_DECREF(item);
1952 return NULL;
1953 }
1954 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001955 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 }
Brett Cannon2657df42012-05-04 15:20:40 -04001957#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001959}
1960
Brett Cannon4caa61d2014-01-09 19:03:32 -05001961/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001962_imp.init_frozen
1963
1964 name: unicode
1965 /
1966
1967Initializes a frozen module.
1968[clinic start generated code]*/
1969
Brett Cannon4caa61d2014-01-09 19:03:32 -05001970static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001971_imp_init_frozen_impl(PyObject *module, PyObject *name)
1972/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 int ret;
1975 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001976
Victor Stinner53dc7352011-03-20 01:50:21 +01001977 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 if (ret < 0)
1979 return NULL;
1980 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001981 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001983 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Py_XINCREF(m);
1985 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001986}
1987
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988/*[clinic input]
1989_imp.get_frozen_object
1990
1991 name: unicode
1992 /
1993
1994Create a code object for a frozen module.
1995[clinic start generated code]*/
1996
Brett Cannon4caa61d2014-01-09 19:03:32 -05001997static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001998_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1999/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002002}
2003
Brett Cannon4caa61d2014-01-09 19:03:32 -05002004/*[clinic input]
2005_imp.is_frozen_package
2006
2007 name: unicode
2008 /
2009
2010Returns True if the module name is of a frozen package.
2011[clinic start generated code]*/
2012
Brett Cannon4caa61d2014-01-09 19:03:32 -05002013static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002014_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2015/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002018}
2019
Brett Cannon4caa61d2014-01-09 19:03:32 -05002020/*[clinic input]
2021_imp.is_builtin
2022
2023 name: unicode
2024 /
2025
2026Returns True if the module name corresponds to a built-in module.
2027[clinic start generated code]*/
2028
Guido van Rossum79f25d91997-04-29 20:08:16 +00002029static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002030_imp_is_builtin_impl(PyObject *module, PyObject *name)
2031/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002032{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002033 return PyLong_FromLong(is_builtin(name));
2034}
2035
2036/*[clinic input]
2037_imp.is_frozen
2038
2039 name: unicode
2040 /
2041
2042Returns True if the module name corresponds to a frozen module.
2043[clinic start generated code]*/
2044
Brett Cannon4caa61d2014-01-09 19:03:32 -05002045static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002046_imp_is_frozen_impl(PyObject *module, PyObject *name)
2047/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002048{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002049 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 p = find_frozen(name);
2052 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002053}
2054
Larry Hastings1df0b352015-08-24 19:53:56 -07002055/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2056static int
2057exec_builtin_or_dynamic(PyObject *mod) {
2058 PyModuleDef *def;
2059 void *state;
2060
2061 if (!PyModule_Check(mod)) {
2062 return 0;
2063 }
2064
2065 def = PyModule_GetDef(mod);
2066 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002067 return 0;
2068 }
Brett Cannon52794db2016-09-07 17:00:43 -07002069
Larry Hastings1df0b352015-08-24 19:53:56 -07002070 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002071 if (state) {
2072 /* Already initialized; skip reload */
2073 return 0;
2074 }
Brett Cannon52794db2016-09-07 17:00:43 -07002075
Larry Hastings1df0b352015-08-24 19:53:56 -07002076 return PyModule_ExecDef(mod, def);
2077}
2078
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002079#ifdef HAVE_DYNAMIC_LOADING
2080
Brett Cannon4caa61d2014-01-09 19:03:32 -05002081/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002082_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002083
Nick Coghland5cacbb2015-05-23 22:24:10 +10002084 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002085 file: object = NULL
2086 /
2087
Nick Coghland5cacbb2015-05-23 22:24:10 +10002088Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002089[clinic start generated code]*/
2090
Brett Cannon4caa61d2014-01-09 19:03:32 -05002091static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002092_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2093/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002094{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002095 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002096 FILE *fp;
2097
Nick Coghland5cacbb2015-05-23 22:24:10 +10002098 name = PyObject_GetAttrString(spec, "name");
2099 if (name == NULL) {
2100 return NULL;
2101 }
2102
2103 path = PyObject_GetAttrString(spec, "origin");
2104 if (path == NULL) {
2105 Py_DECREF(name);
2106 return NULL;
2107 }
2108
2109 mod = _PyImport_FindExtensionObject(name, path);
2110 if (mod != NULL) {
2111 Py_DECREF(name);
2112 Py_DECREF(path);
2113 Py_INCREF(mod);
2114 return mod;
2115 }
2116
Brett Cannon4caa61d2014-01-09 19:03:32 -05002117 if (file != NULL) {
2118 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002119 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002120 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002121 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002123 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002125 else
2126 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002127
2128 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2129
2130 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002131 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 if (fp)
2133 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002134 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002135}
2136
Nick Coghland5cacbb2015-05-23 22:24:10 +10002137/*[clinic input]
2138_imp.exec_dynamic -> int
2139
2140 mod: object
2141 /
2142
2143Initialize an extension module.
2144[clinic start generated code]*/
2145
2146static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002147_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2148/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002149{
Larry Hastings1df0b352015-08-24 19:53:56 -07002150 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002151}
2152
2153
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002154#endif /* HAVE_DYNAMIC_LOADING */
2155
Larry Hastings7726ac92014-01-31 22:03:12 -08002156/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002157_imp.exec_builtin -> int
2158
2159 mod: object
2160 /
2161
2162Initialize a built-in module.
2163[clinic start generated code]*/
2164
2165static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002166_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2167/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002168{
2169 return exec_builtin_or_dynamic(mod);
2170}
2171
Barry Warsaw28a691b2010-04-17 00:19:56 +00002172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002173PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002174"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002175
Guido van Rossum79f25d91997-04-29 20:08:16 +00002176static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002177 _IMP_EXTENSION_SUFFIXES_METHODDEF
2178 _IMP_LOCK_HELD_METHODDEF
2179 _IMP_ACQUIRE_LOCK_METHODDEF
2180 _IMP_RELEASE_LOCK_METHODDEF
2181 _IMP_GET_FROZEN_OBJECT_METHODDEF
2182 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002183 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002184 _IMP_INIT_FROZEN_METHODDEF
2185 _IMP_IS_BUILTIN_METHODDEF
2186 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002187 _IMP_CREATE_DYNAMIC_METHODDEF
2188 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002189 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002190 _IMP__FIX_CO_FILENAME_METHODDEF
2191 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002192};
2193
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002194
Martin v. Löwis1a214512008-06-11 05:26:20 +00002195static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002197 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 doc_imp,
2199 0,
2200 imp_methods,
2201 NULL,
2202 NULL,
2203 NULL,
2204 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002205};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002206
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002207PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002208PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 m = PyModule_Create(&impmodule);
2213 if (m == NULL)
2214 goto failure;
2215 d = PyModule_GetDict(m);
2216 if (d == NULL)
2217 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002220 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 Py_XDECREF(m);
2222 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002223}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002224
2225
Guido van Rossumb18618d2000-05-03 23:44:39 +00002226/* API for embedding applications that want to add their own entries
2227 to the table of built-in modules. This should normally be called
2228 *before* Py_Initialize(). When the table resize fails, -1 is
2229 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002230
2231 After a similar function by Just van Rossum. */
2232
2233int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002234PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 static struct _inittab *our_copy = NULL;
2237 struct _inittab *p;
2238 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Count the number of entries in both tables */
2241 for (n = 0; newtab[n].name != NULL; n++)
2242 ;
2243 if (n == 0)
2244 return 0; /* Nothing to do */
2245 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2246 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 /* Allocate new memory for the combined table */
2249 p = our_copy;
2250 PyMem_RESIZE(p, struct _inittab, i+n+1);
2251 if (p == NULL)
2252 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* Copy the tables into the new memory */
2255 if (our_copy != PyImport_Inittab)
2256 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2257 PyImport_Inittab = our_copy = p;
2258 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002261}
2262
2263/* Shorthand to add a single entry given a name and a function */
2264
2265int
Brett Cannona826f322009-04-02 03:41:46 +00002266PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002271
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002272 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002276}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002277
2278#ifdef __cplusplus
2279}
2280#endif