blob: dc79685abd48739b7eb3a35b067bea0108904663 [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;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010033static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000034
Brett Cannon4caa61d2014-01-09 19:03:32 -050035/*[clinic input]
36module _imp
37[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030038/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040039
40#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050041
Guido van Rossum1ae940a1995-01-02 19:04:15 +000042/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043
Victor Stinnerf7e5b562017-11-15 15:48:08 -080044_PyInitError
Victor Stinner672b6ba2017-12-06 17:25:50 +010045_PyImport_Init(PyInterpreterState *interp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020047 interp->builtins_copy = PyDict_Copy(interp->builtins);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080048 if (interp->builtins_copy == NULL) {
49 return _Py_INIT_ERR("Can't backup builtins dict");
50 }
51 return _Py_INIT_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052}
53
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054_PyInitError
Just van Rossum52e14d62002-12-30 22:08:05 +000055_PyImportHooks_Init(void)
56{
Brett Cannonfd074152012-04-14 14:10:13 -040057 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000059
Brett Cannonfd074152012-04-14 14:10:13 -040060 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 v = PyList_New(0);
62 if (v == NULL)
63 goto error;
64 err = PySys_SetObject("meta_path", v);
65 Py_DECREF(v);
66 if (err)
67 goto error;
68 v = PyDict_New();
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("path_importer_cache", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 path_hooks = PyList_New(0);
76 if (path_hooks == NULL)
77 goto error;
78 err = PySys_SetObject("path_hooks", path_hooks);
79 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 }
Brett Cannonfd074152012-04-14 14:10:13 -040082 Py_DECREF(path_hooks);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080083 return _Py_INIT_OK();
84
85 error:
86 PyErr_Print();
87 return _Py_INIT_ERR("initializing sys.meta_path, sys.path_hooks, "
88 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040089}
90
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091_PyInitError
Brett Cannonfd074152012-04-14 14:10:13 -040092_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
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800136 return _Py_INIT_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400137
138 error:
139 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800140 return _Py_INIT_ERR("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
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100289void
290_PyImport_Fini2(void)
291{
292 /* Use the same memory allocator than PyImport_ExtendInittab(). */
293 PyMemAllocatorEx old_alloc;
294 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
295
296 /* Free memory allocated by PyImport_ExtendInittab() */
297 PyMem_RawFree(inittab_copy);
298
299 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
300}
301
Guido van Rossum25ce5661997-08-02 03:10:38 +0000302/* Helper for sys */
303
304PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000305PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306{
Eric Snow93c92f72017-09-13 23:46:04 -0700307 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snow3f9eee62017-09-15 16:35:20 -0600308 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700309 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600310 }
Eric Snow93c92f72017-09-13 23:46:04 -0700311 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000312}
313
Eric Snowd393c1b2017-09-14 12:18:12 -0600314/* In some corner cases it is important to be sure that the import
315 machinery has been initialized (or not cleaned up yet). For
316 example, see issue #4236 and PyModule_Create2(). */
317
318int
319_PyImport_IsInitialized(PyInterpreterState *interp)
320{
321 if (interp->modules == NULL)
322 return 0;
323 return 1;
324}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000325
Eric Snow3f9eee62017-09-15 16:35:20 -0600326PyObject *
327_PyImport_GetModuleId(struct _Py_Identifier *nameid)
328{
329 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
330 if (name == NULL) {
331 return NULL;
332 }
333 return PyImport_GetModule(name);
334}
335
336int
337_PyImport_SetModule(PyObject *name, PyObject *m)
338{
339 PyObject *modules = PyImport_GetModuleDict();
340 return PyObject_SetItem(modules, name, m);
341}
342
343int
344_PyImport_SetModuleString(const char *name, PyObject *m)
345{
346 PyObject *modules = PyImport_GetModuleDict();
347 return PyMapping_SetItemString(modules, name, m);
348}
349
350PyObject *
351PyImport_GetModule(PyObject *name)
352{
353 PyObject *m;
354 PyObject *modules = PyImport_GetModuleDict();
355 if (modules == NULL) {
356 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
357 return NULL;
358 }
359 Py_INCREF(modules);
360 if (PyDict_CheckExact(modules)) {
361 m = PyDict_GetItemWithError(modules, name); /* borrowed */
362 Py_XINCREF(m);
363 }
364 else {
365 m = PyObject_GetItem(modules, name);
366 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
367 PyErr_Clear();
368 }
369 }
370 Py_DECREF(modules);
371 return m;
372}
373
374
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000375/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200376static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 "path", "argv", "ps1", "ps2",
378 "last_type", "last_value", "last_traceback",
379 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200380 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 /* misc stuff */
382 "flags", "float_info",
383 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000384};
385
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200386static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 "stdin", "__stdin__",
388 "stdout", "__stdout__",
389 "stderr", "__stderr__",
390 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000391};
392
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000393/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000394
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000396PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200398 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 PyObject *key, *value, *dict;
400 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snowd393c1b2017-09-14 12:18:12 -0600401 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200402 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200403 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (modules == NULL)
406 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* Delete some special variables first. These are common
409 places where user values hide and people complain when their
410 destructors fail. Since the modules containing them are
411 deleted *last* of all, they would come too late in the normal
412 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000413
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200414 /* XXX Perhaps these precautions are obsolete. Who knows? */
415
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200416 if (Py_VerboseFlag)
417 PySys_WriteStderr("# clear builtins._\n");
418 PyDict_SetItemString(interp->builtins, "_", Py_None);
419
420 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200422 PySys_WriteStderr("# clear sys.%s\n", *p);
423 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200425 for (p = sys_files; *p != NULL; p+=2) {
426 if (Py_VerboseFlag)
427 PySys_WriteStderr("# restore sys.%s\n", *p);
428 value = PyDict_GetItemString(interp->sysdict, *(p+1));
429 if (value == NULL)
430 value = Py_None;
431 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000433
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200434 /* We prepare a list which will receive (name, weakref) tuples of
435 modules when they are removed from sys.modules. The name is used
436 for diagnosis messages (in verbose mode), while the weakref helps
437 detect those modules which have been held alive. */
438 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200439 if (weaklist == NULL)
440 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200441
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200442#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200443 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200444 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
445 if (name && wr) { \
446 PyObject *tup = PyTuple_Pack(2, name, wr); \
447 PyList_Append(weaklist, tup); \
448 Py_XDECREF(tup); \
449 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450 Py_XDECREF(wr); \
451 if (PyErr_Occurred()) \
452 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600454#define CLEAR_MODULE(name, mod) \
455 if (PyModule_Check(mod)) { \
456 if (Py_VerboseFlag && PyUnicode_Check(name)) \
457 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
458 STORE_MODULE_WEAKREF(name, mod); \
459 PyObject_SetItem(modules, name, Py_None); \
460 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000461
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200462 /* Remove all modules from sys.modules, hoping that garbage collection
463 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600464 if (PyDict_CheckExact(modules)) {
465 pos = 0;
466 while (PyDict_Next(modules, &pos, &key, &value)) {
467 CLEAR_MODULE(key, value);
468 }
469 }
470 else {
471 PyObject *iterator = PyObject_GetIter(modules);
472 if (iterator == NULL) {
473 PyErr_Clear();
474 }
475 else {
476 while ((key = PyIter_Next(iterator))) {
477 value = PyObject_GetItem(modules, key);
478 if (value == NULL) {
479 PyErr_Clear();
480 continue;
481 }
482 CLEAR_MODULE(key, value);
483 Py_DECREF(value);
484 Py_DECREF(key);
485 }
486 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 }
488 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000489
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200490 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600491 if (PyDict_CheckExact(modules)) {
492 PyDict_Clear(modules);
493 }
494 else {
495 _Py_IDENTIFIER(clear);
496 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL)
497 PyErr_Clear();
498 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200499 /* Restore the original builtins dict, to ensure that any
500 user data gets cleared. */
501 dict = PyDict_Copy(interp->builtins);
502 if (dict == NULL)
503 PyErr_Clear();
504 PyDict_Clear(interp->builtins);
505 if (PyDict_Update(interp->builtins, interp->builtins_copy))
506 PyErr_Clear();
507 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200508 /* Clear module dict copies stored in the interpreter state */
509 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200510 /* Collect references */
511 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200512 /* Dump GC stats before it's too late, since it uses the warnings
513 machinery. */
514 _PyGC_DumpShutdownStats();
515
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200516 /* Now, if there are any modules left alive, clear their globals to
517 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200518 up here, since they are kept alive in the interpreter state.
519
520 The special treatment of "builtins" here is because even
521 when it's not referenced as a module, its dictionary is
522 referenced by almost every module's __builtins__. Since
523 deleting a module clears its dictionary (even if there are
524 references left to it), we need to delete the "builtins"
525 module last. Likewise, we don't delete sys until the very
526 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200527 if (weaklist != NULL) {
528 Py_ssize_t i, n;
529 n = PyList_GET_SIZE(weaklist);
530 for (i = 0; i < n; i++) {
531 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200532 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200533 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
534 if (mod == Py_None)
535 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200536 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200537 dict = PyModule_GetDict(mod);
538 if (dict == interp->builtins || dict == interp->sysdict)
539 continue;
540 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200541 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200542 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200543 _PyModule_Clear(mod);
544 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200545 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200546 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000548
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200549 /* Next, delete sys and builtins (in that order) */
550 if (Py_VerboseFlag)
551 PySys_FormatStderr("# cleanup[3] wiping sys\n");
552 _PyModule_ClearDict(interp->sysdict);
553 if (Py_VerboseFlag)
554 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
555 _PyModule_ClearDict(interp->builtins);
556
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200557 /* Clear and delete the modules directory. Actual modules will
558 still be there only if imported during the execution of some
559 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700560 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200562
563 /* Once more */
564 _PyGC_CollectNoFail();
565
566#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000567}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000568
569
Barry Warsaw28a691b2010-04-17 00:19:56 +0000570/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000571
572long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000573PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000574{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200575 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400576 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600577 PyObject *external, *pyc_magic;
578
579 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
580 if (external == NULL)
581 return -1;
582 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
583 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400584 if (pyc_magic == NULL)
585 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200586 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700587 Py_DECREF(pyc_magic);
588 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000589}
590
591
Brett Cannon3adc7b72012-07-09 14:22:12 -0400592extern const char * _PySys_ImplCacheTag;
593
Barry Warsaw28a691b2010-04-17 00:19:56 +0000594const char *
595PyImport_GetMagicTag(void)
596{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400597 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000598}
599
Brett Cannon98979b82012-07-02 15:13:11 -0400600
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601/* Magic for extension modules (built-in as well as dynamically
602 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200603 once, we keep a static dictionary 'extensions' keyed by the tuple
604 (module name, module name) (for built-in modules) or by
605 (filename, module name) (for dynamically loaded modules), containing these
606 modules. A copy of the module's dictionary is stored by calling
607 _PyImport_FixupExtensionObject() immediately after the module initialization
608 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100609 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000611 Modules which do support multiple initialization set their m_size
612 field to a non-negative number (indicating the size of the
613 module-specific state). They are still recorded in the extensions
614 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000615*/
616
617int
Victor Stinner95872862011-03-07 18:20:56 +0100618_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600619 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620{
Eric Snowd393c1b2017-09-14 12:18:12 -0600621 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500623 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (extensions == NULL) {
625 extensions = PyDict_New();
626 if (extensions == NULL)
627 return -1;
628 }
629 if (mod == NULL || !PyModule_Check(mod)) {
630 PyErr_BadInternalCall();
631 return -1;
632 }
633 def = PyModule_GetDef(mod);
634 if (!def) {
635 PyErr_BadInternalCall();
636 return -1;
637 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600638 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return -1;
640 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600641 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return -1;
643 }
644 if (def->m_size == -1) {
645 if (def->m_base.m_copy) {
646 /* Somebody already imported the module,
647 likely under a different name.
648 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200649 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
651 dict = PyModule_GetDict(mod);
652 if (dict == NULL)
653 return -1;
654 def->m_base.m_copy = PyDict_Copy(dict);
655 if (def->m_base.m_copy == NULL)
656 return -1;
657 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500658 key = PyTuple_Pack(2, filename, name);
659 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200660 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500661 res = PyDict_SetItem(extensions, key, (PyObject *)def);
662 Py_DECREF(key);
663 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200664 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000666}
667
Victor Stinner49d3f252010-10-17 01:24:53 +0000668int
Eric Snowd393c1b2017-09-14 12:18:12 -0600669_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000670{
671 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100672 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100673 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100674 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000675 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600676 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100677 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000678 return res;
679}
680
Guido van Rossum25ce5661997-08-02 03:10:38 +0000681PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100682_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000683{
Eric Snowd393c1b2017-09-14 12:18:12 -0600684 PyObject *modules = PyImport_GetModuleDict();
685 return _PyImport_FindExtensionObjectEx(name, filename, modules);
686}
687
688PyObject *
689_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
690 PyObject *modules)
691{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500692 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 PyModuleDef* def;
694 if (extensions == NULL)
695 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500696 key = PyTuple_Pack(2, filename, name);
697 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200698 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500699 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
700 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (def == NULL)
702 return NULL;
703 if (def->m_size == -1) {
704 /* Module does not support repeated initialization */
705 if (def->m_base.m_copy == NULL)
706 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600707 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (mod == NULL)
709 return NULL;
710 mdict = PyModule_GetDict(mod);
711 if (mdict == NULL)
712 return NULL;
713 if (PyDict_Update(mdict, def->m_base.m_copy))
714 return NULL;
715 }
716 else {
717 if (def->m_base.m_init == NULL)
718 return NULL;
719 mod = def->m_base.m_init();
720 if (mod == NULL)
721 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600722 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200723 Py_DECREF(mod);
724 return NULL;
725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 Py_DECREF(mod);
727 }
728 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600729 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 Py_DECREF(mod);
731 return NULL;
732 }
733 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100734 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 name, filename);
736 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000737
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000738}
739
Victor Stinner49d3f252010-10-17 01:24:53 +0000740PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600741_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000742{
Victor Stinner95872862011-03-07 18:20:56 +0100743 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100744 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100745 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000746 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600747 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100748 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000749 return res;
750}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000751
752/* Get the module object corresponding to a module name.
753 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000754 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000755 Because the former action is most common, THIS DOES NOT RETURN A
756 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000757
Guido van Rossum79f25d91997-04-29 20:08:16 +0000758PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000759PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600762 return _PyImport_AddModuleObject(name, modules);
763}
764
765PyObject *
766_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
767{
Eric Snow86b7afd2017-09-04 17:54:09 -0600768 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600769 if (PyDict_CheckExact(modules)) {
770 m = PyDict_GetItemWithError(modules, name);
771 }
772 else {
773 m = PyObject_GetItem(modules, name);
774 // For backward-comaptibility we copy the behavior
775 // of PyDict_GetItemWithError().
776 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
777 PyErr_Clear();
778 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200779 }
780 if (PyErr_Occurred()) {
781 return NULL;
782 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600783 if (m != NULL && PyModule_Check(m)) {
784 return m;
785 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000786 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (m == NULL)
788 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600789 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 Py_DECREF(m);
791 return NULL;
792 }
793 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000796}
797
Victor Stinner27ee0892011-03-04 12:57:09 +0000798PyObject *
799PyImport_AddModule(const char *name)
800{
801 PyObject *nameobj, *module;
802 nameobj = PyUnicode_FromString(name);
803 if (nameobj == NULL)
804 return NULL;
805 module = PyImport_AddModuleObject(nameobj);
806 Py_DECREF(nameobj);
807 return module;
808}
809
810
Tim Peters1cd70172004-08-02 03:52:12 +0000811/* Remove name from sys.modules, if it's there. */
812static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000813remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 PyObject *modules = PyImport_GetModuleDict();
Eric Snow3f9eee62017-09-15 16:35:20 -0600816 if (PyMapping_DelItem(modules, name) < 0) {
817 if (!PyMapping_HasKey(modules, name)) {
818 return;
819 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 Py_FatalError("import: deleting existing key in"
821 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600822 }
Tim Peters1cd70172004-08-02 03:52:12 +0000823}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000824
Christian Heimes3b06e532008-01-07 20:12:44 +0000825
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000826/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000827 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
828 * removed from sys.modules, to avoid leaving damaged module objects
829 * in sys.modules. The caller may wish to restore the original
830 * module object (if any) in this case; PyImport_ReloadModule is an
831 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000832 *
833 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
834 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000835 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000836PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300837PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return PyImport_ExecCodeModuleWithPathnames(
840 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000841}
842
843PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300844PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return PyImport_ExecCodeModuleWithPathnames(
847 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000848}
849
850PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300851PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
852 const char *pathname,
853 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000854{
Victor Stinner27ee0892011-03-04 12:57:09 +0000855 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600856 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000857
858 nameobj = PyUnicode_FromString(name);
859 if (nameobj == NULL)
860 return NULL;
861
Victor Stinner27ee0892011-03-04 12:57:09 +0000862 if (cpathname != NULL) {
863 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
864 if (cpathobj == NULL)
865 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400866 }
867 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000868 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400869
870 if (pathname != NULL) {
871 pathobj = PyUnicode_DecodeFSDefault(pathname);
872 if (pathobj == NULL)
873 goto error;
874 }
875 else if (cpathobj != NULL) {
876 PyInterpreterState *interp = PyThreadState_GET()->interp;
877 _Py_IDENTIFIER(_get_sourcefile);
878
879 if (interp == NULL) {
880 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
881 "no interpreter!");
882 }
883
Eric Snow32439d62015-05-02 19:15:18 -0600884 external= PyObject_GetAttrString(interp->importlib,
885 "_bootstrap_external");
886 if (external != NULL) {
887 pathobj = _PyObject_CallMethodIdObjArgs(external,
888 &PyId__get_sourcefile, cpathobj,
889 NULL);
890 Py_DECREF(external);
891 }
Brett Cannona6473f92012-07-13 13:57:03 -0400892 if (pathobj == NULL)
893 PyErr_Clear();
894 }
895 else
896 pathobj = NULL;
897
Victor Stinner27ee0892011-03-04 12:57:09 +0000898 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
899error:
900 Py_DECREF(nameobj);
901 Py_XDECREF(pathobj);
902 Py_XDECREF(cpathobj);
903 return m;
904}
905
Brett Cannon18fc4e72014-04-04 10:01:46 -0400906static PyObject *
907module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000908{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400909 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000910
Victor Stinner27ee0892011-03-04 12:57:09 +0000911 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (m == NULL)
913 return NULL;
914 /* If the module is being reloaded, we get the old module back
915 and re-use its dict to exec the new code. */
916 d = PyModule_GetDict(m);
917 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
918 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400919 PyEval_GetBuiltins()) != 0) {
920 remove_module(name);
921 return NULL;
922 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400924
Eric Snow08197a42014-05-12 17:54:55 -0600925 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400926}
927
928static PyObject *
929exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
930{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400931 PyObject *v, *m;
932
933 v = PyEval_EvalCode(code_object, module_dict, module_dict);
934 if (v == NULL) {
935 remove_module(name);
936 return NULL;
937 }
938 Py_DECREF(v);
939
Eric Snow3f9eee62017-09-15 16:35:20 -0600940 m = PyImport_GetModule(name);
941 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400942 PyErr_Format(PyExc_ImportError,
943 "Loaded module %R not found in sys.modules",
944 name);
945 return NULL;
946 }
947
Brett Cannon18fc4e72014-04-04 10:01:46 -0400948 return m;
949}
950
951PyObject*
952PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
953 PyObject *cpathname)
954{
Eric Snow32439d62015-05-02 19:15:18 -0600955 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600956 PyInterpreterState *interp = PyThreadState_GET()->interp;
957 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400958
959 d = module_dict_for_exec(name);
960 if (d == NULL) {
961 return NULL;
962 }
963
Eric Snow08197a42014-05-12 17:54:55 -0600964 if (pathname == NULL) {
965 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
Eric Snow32439d62015-05-02 19:15:18 -0600967 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
968 if (external == NULL)
969 return NULL;
970 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600971 &PyId__fix_up_module,
972 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600973 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600974 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600975 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600976 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 }
Eric Snow08197a42014-05-12 17:54:55 -0600978 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000979}
980
981
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000982static void
983update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject *constants, *tmp;
986 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (PyUnicode_Compare(co->co_filename, oldname))
989 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000990
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200991 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300992 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 constants = co->co_consts;
995 n = PyTuple_GET_SIZE(constants);
996 for (i = 0; i < n; i++) {
997 tmp = PyTuple_GET_ITEM(constants, i);
998 if (PyCode_Check(tmp))
999 update_code_filenames((PyCodeObject *)tmp,
1000 oldname, newname);
1001 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001002}
1003
Victor Stinner2f42ae52011-03-20 00:41:24 +01001004static void
1005update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001006{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001007 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001008
Victor Stinner2f42ae52011-03-20 00:41:24 +01001009 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1010 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 oldname = co->co_filename;
1013 Py_INCREF(oldname);
1014 update_code_filenames(co, oldname, newname);
1015 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001016}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001017
Brett Cannon4caa61d2014-01-09 19:03:32 -05001018/*[clinic input]
1019_imp._fix_co_filename
1020
1021 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1022 Code object to change.
1023
1024 path: unicode
1025 File path to use.
1026 /
1027
1028Changes code.co_filename to specify the passed-in file path.
1029[clinic start generated code]*/
1030
Brett Cannon4caa61d2014-01-09 19:03:32 -05001031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001032_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001033 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001034/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001035
Brett Cannon4caa61d2014-01-09 19:03:32 -05001036{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001037 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001038
1039 Py_RETURN_NONE;
1040}
1041
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001042
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001043/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001044static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001045
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001046
1047/* Helper to test for built-in module */
1048
1049static int
Victor Stinner95872862011-03-07 18:20:56 +01001050is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001051{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001052 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001054 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (PyImport_Inittab[i].initfunc == NULL)
1056 return -1;
1057 else
1058 return 1;
1059 }
1060 }
1061 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001062}
1063
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001064
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001065/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001066 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001067 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001068 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001069 this tells our caller that the path based finder could not find
1070 a finder for this path item. Cache the result in
1071 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001072 Returns a borrowed reference. */
1073
1074static PyObject *
1075get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyObject *importer;
1079 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* These conditions are the caller's responsibility: */
1082 assert(PyList_Check(path_hooks));
1083 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 nhooks = PyList_Size(path_hooks);
1086 if (nhooks < 0)
1087 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 importer = PyDict_GetItem(path_importer_cache, p);
1090 if (importer != NULL)
1091 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /* set path_importer_cache[p] to None to avoid recursion */
1094 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1095 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 for (j = 0; j < nhooks; j++) {
1098 PyObject *hook = PyList_GetItem(path_hooks, j);
1099 if (hook == NULL)
1100 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001101 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (importer != NULL)
1103 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1106 return NULL;
1107 }
1108 PyErr_Clear();
1109 }
1110 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001111 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 }
1113 if (importer != NULL) {
1114 int err = PyDict_SetItem(path_importer_cache, p, importer);
1115 Py_DECREF(importer);
1116 if (err != 0)
1117 return NULL;
1118 }
1119 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001120}
1121
Christian Heimes9cd17752007-11-18 19:35:23 +00001122PyAPI_FUNC(PyObject *)
1123PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001125
Victor Stinner1e53bba2013-07-16 22:26:05 +02001126 path_importer_cache = PySys_GetObject("path_importer_cache");
1127 path_hooks = PySys_GetObject("path_hooks");
1128 if (path_importer_cache != NULL && path_hooks != NULL) {
1129 importer = get_path_importer(path_importer_cache,
1130 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 }
1132 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1133 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001134}
1135
Nick Coghland5cacbb2015-05-23 22:24:10 +10001136/*[clinic input]
1137_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001138
Nick Coghland5cacbb2015-05-23 22:24:10 +10001139 spec: object
1140 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001141
Nick Coghland5cacbb2015-05-23 22:24:10 +10001142Create an extension module.
1143[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001144
Nick Coghland5cacbb2015-05-23 22:24:10 +10001145static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001146_imp_create_builtin(PyObject *module, PyObject *spec)
1147/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001150 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001151 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001152 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001153
Nick Coghland5cacbb2015-05-23 22:24:10 +10001154 name = PyObject_GetAttrString(spec, "name");
1155 if (name == NULL) {
1156 return NULL;
1157 }
1158
Victor Stinner5eb4f592013-11-14 22:38:52 +01001159 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001160 if (mod || PyErr_Occurred()) {
1161 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001162 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001163 return mod;
1164 }
1165
1166 namestr = PyUnicode_AsUTF8(name);
1167 if (namestr == NULL) {
1168 Py_DECREF(name);
1169 return NULL;
1170 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001171
Eric Snowd393c1b2017-09-14 12:18:12 -06001172 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001174 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001175 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001177 /* Cannot re-init internal module ("sys" or "builtins") */
1178 mod = PyImport_AddModule(namestr);
1179 Py_DECREF(name);
1180 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001183 if (mod == NULL) {
1184 Py_DECREF(name);
1185 return NULL;
1186 }
1187 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1188 Py_DECREF(name);
1189 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1190 } else {
1191 /* Remember pointer to module init function. */
1192 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001193 if (def == NULL) {
1194 Py_DECREF(name);
1195 return NULL;
1196 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001197 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001198 if (modules == NULL) {
1199 modules = PyImport_GetModuleDict();
1200 }
1201 if (_PyImport_FixupExtensionObject(mod, name, name,
1202 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001203 Py_DECREF(name);
1204 return NULL;
1205 }
1206 Py_DECREF(name);
1207 return mod;
1208 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 }
1210 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001211 Py_DECREF(name);
1212 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001213}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001214
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001215
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001216/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001217
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001218static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001219find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001220{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001221 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001222
Victor Stinner53dc7352011-03-20 01:50:21 +01001223 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 for (p = PyImport_FrozenModules; ; p++) {
1227 if (p->name == NULL)
1228 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001229 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 break;
1231 }
1232 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001233}
1234
Guido van Rossum79f25d91997-04-29 20:08:16 +00001235static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001236get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001237{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001238 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (p == NULL) {
1242 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001243 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 name);
1245 return NULL;
1246 }
1247 if (p->code == NULL) {
1248 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001249 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 name);
1251 return NULL;
1252 }
1253 size = p->size;
1254 if (size < 0)
1255 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001256 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001257}
1258
Brett Cannon8d110132009-03-15 02:20:16 +00001259static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001260is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001261{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001262 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (p == NULL) {
1266 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001267 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 name);
1269 return NULL;
1270 }
Brett Cannon8d110132009-03-15 02:20:16 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (size < 0)
1275 Py_RETURN_TRUE;
1276 else
1277 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001278}
1279
1280
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001281/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001282 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001283 an exception set if the initialization failed.
1284 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001285
1286int
Victor Stinner53dc7352011-03-20 01:50:21 +01001287PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001288{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001289 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001290 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 int ispackage;
1292 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001293
Victor Stinner53dc7352011-03-20 01:50:21 +01001294 p = find_frozen(name);
1295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (p == NULL)
1297 return 0;
1298 if (p->code == NULL) {
1299 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001300 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 name);
1302 return -1;
1303 }
1304 size = p->size;
1305 ispackage = (size < 0);
1306 if (ispackage)
1307 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001308 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (co == NULL)
1310 return -1;
1311 if (!PyCode_Check(co)) {
1312 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001313 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 name);
1315 goto err_return;
1316 }
1317 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001318 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001319 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001321 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (m == NULL)
1323 goto err_return;
1324 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001325 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 goto err_return;
1328 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 err = PyDict_SetItemString(d, "__path__", l);
1330 Py_DECREF(l);
1331 if (err != 0)
1332 goto err_return;
1333 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001334 d = module_dict_for_exec(name);
1335 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001336 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001337 }
1338 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (m == NULL)
1340 goto err_return;
1341 Py_DECREF(co);
1342 Py_DECREF(m);
1343 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 Py_DECREF(co);
1346 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001347}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001348
Victor Stinner53dc7352011-03-20 01:50:21 +01001349int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001350PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001351{
1352 PyObject *nameobj;
1353 int ret;
1354 nameobj = PyUnicode_InternFromString(name);
1355 if (nameobj == NULL)
1356 return -1;
1357 ret = PyImport_ImportFrozenModuleObject(nameobj);
1358 Py_DECREF(nameobj);
1359 return ret;
1360}
1361
Guido van Rossum74e6a111994-08-29 12:54:38 +00001362
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001363/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001364 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001365
Guido van Rossum79f25d91997-04-29 20:08:16 +00001366PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001367PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyObject *pname;
1370 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 pname = PyUnicode_FromString(name);
1373 if (pname == NULL)
1374 return NULL;
1375 result = PyImport_Import(pname);
1376 Py_DECREF(pname);
1377 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001378}
1379
Christian Heimes072c0f12008-01-03 23:01:04 +00001380/* Import a module without blocking
1381 *
1382 * At first it tries to fetch the module from sys.modules. If the module was
1383 * never loaded before it loads it with PyImport_ImportModule() unless another
1384 * thread holds the import lock. In the latter case the function raises an
1385 * ImportError instead of blocking.
1386 *
1387 * Returns the module object with incremented ref count.
1388 */
1389PyObject *
1390PyImport_ImportModuleNoBlock(const char *name)
1391{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001392 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001393}
1394
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001395
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001396/* Remove importlib frames from the traceback,
1397 * except in Verbose mode. */
1398static void
1399remove_importlib_frames(void)
1400{
1401 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001402 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001403 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001404 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001405 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001406 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001407 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001408
1409 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001410 from the traceback. We always trim chunks
1411 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001412
1413 PyErr_Fetch(&exception, &value, &base_tb);
1414 if (!exception || Py_VerboseFlag)
1415 goto done;
1416 if (PyType_IsSubtype((PyTypeObject *) exception,
1417 (PyTypeObject *) PyExc_ImportError))
1418 always_trim = 1;
1419
1420 prev_link = &base_tb;
1421 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001422 while (tb != NULL) {
1423 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1424 PyObject *next = (PyObject *) traceback->tb_next;
1425 PyFrameObject *frame = traceback->tb_frame;
1426 PyCodeObject *code = frame->f_code;
1427 int now_in_importlib;
1428
1429 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001430 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1431 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001432 if (now_in_importlib && !in_importlib) {
1433 /* This is the link to this chunk of importlib tracebacks */
1434 outer_link = prev_link;
1435 }
1436 in_importlib = now_in_importlib;
1437
1438 if (in_importlib &&
1439 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001440 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001441 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001442 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001443 prev_link = outer_link;
1444 }
1445 else {
1446 prev_link = (PyObject **) &traceback->tb_next;
1447 }
1448 tb = next;
1449 }
1450done:
1451 PyErr_Restore(exception, value, base_tb);
1452}
1453
1454
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001455static PyObject *
1456resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001457{
Eric Snowb523f842013-11-22 09:05:39 -07001458 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001459 _Py_IDENTIFIER(__package__);
1460 _Py_IDENTIFIER(__path__);
1461 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001462 _Py_IDENTIFIER(parent);
1463 PyObject *abs_name;
1464 PyObject *package = NULL;
1465 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001466 Py_ssize_t last_dot;
1467 PyObject *base;
1468 int level_up;
1469
1470 if (globals == NULL) {
1471 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1472 goto error;
1473 }
1474 if (!PyDict_Check(globals)) {
1475 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1476 goto error;
1477 }
1478 package = _PyDict_GetItemId(globals, &PyId___package__);
1479 if (package == Py_None) {
1480 package = NULL;
1481 }
1482 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1483
1484 if (package != NULL) {
1485 Py_INCREF(package);
1486 if (!PyUnicode_Check(package)) {
1487 PyErr_SetString(PyExc_TypeError, "package must be a string");
1488 goto error;
1489 }
1490 else if (spec != NULL && spec != Py_None) {
1491 int equal;
1492 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1493 if (parent == NULL) {
1494 goto error;
1495 }
1496
1497 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1498 Py_DECREF(parent);
1499 if (equal < 0) {
1500 goto error;
1501 }
1502 else if (equal == 0) {
1503 if (PyErr_WarnEx(PyExc_ImportWarning,
1504 "__package__ != __spec__.parent", 1) < 0) {
1505 goto error;
1506 }
1507 }
1508 }
1509 }
1510 else if (spec != NULL && spec != Py_None) {
1511 package = _PyObject_GetAttrId(spec, &PyId_parent);
1512 if (package == NULL) {
1513 goto error;
1514 }
1515 else if (!PyUnicode_Check(package)) {
1516 PyErr_SetString(PyExc_TypeError,
1517 "__spec__.parent must be a string");
1518 goto error;
1519 }
1520 }
1521 else {
1522 if (PyErr_WarnEx(PyExc_ImportWarning,
1523 "can't resolve package from __spec__ or __package__, "
1524 "falling back on __name__ and __path__", 1) < 0) {
1525 goto error;
1526 }
1527
1528 package = _PyDict_GetItemId(globals, &PyId___name__);
1529 if (package == NULL) {
1530 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1531 goto error;
1532 }
1533
1534 Py_INCREF(package);
1535 if (!PyUnicode_Check(package)) {
1536 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1537 goto error;
1538 }
1539
1540 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1541 Py_ssize_t dot;
1542
1543 if (PyUnicode_READY(package) < 0) {
1544 goto error;
1545 }
1546
1547 dot = PyUnicode_FindChar(package, '.',
1548 0, PyUnicode_GET_LENGTH(package), -1);
1549 if (dot == -2) {
1550 goto error;
1551 }
1552
1553 if (dot >= 0) {
1554 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1555 if (substr == NULL) {
1556 goto error;
1557 }
1558 Py_SETREF(package, substr);
1559 }
1560 }
1561 }
1562
1563 last_dot = PyUnicode_GET_LENGTH(package);
1564 if (last_dot == 0) {
1565 PyErr_SetString(PyExc_ImportError,
1566 "attempted relative import with no known parent package");
1567 goto error;
1568 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001569
1570 for (level_up = 1; level_up < level; level_up += 1) {
1571 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1572 if (last_dot == -2) {
1573 goto error;
1574 }
1575 else if (last_dot == -1) {
1576 PyErr_SetString(PyExc_ValueError,
1577 "attempted relative import beyond top-level "
1578 "package");
1579 goto error;
1580 }
1581 }
1582
1583 base = PyUnicode_Substring(package, 0, last_dot);
1584 Py_DECREF(package);
1585 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1586 return base;
1587 }
1588
1589 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1590 Py_DECREF(base);
1591 return abs_name;
1592
1593 error:
1594 Py_XDECREF(package);
1595 return NULL;
1596}
1597
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001598static PyObject *
1599import_find_and_load(PyObject *abs_name)
1600{
1601 _Py_IDENTIFIER(_find_and_load);
1602 PyObject *mod = NULL;
1603 PyInterpreterState *interp = PyThreadState_GET()->interp;
1604 int import_time = interp->core_config.import_time;
1605 static int import_level;
1606 static _PyTime_t accumulated;
1607
1608 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1609
1610 /* XOptions is initialized after first some imports.
1611 * So we can't have negative cache before completed initialization.
1612 * Anyway, importlib._find_and_load is much slower than
1613 * _PyDict_GetItemIdWithError().
1614 */
1615 if (import_time) {
1616 static int header = 1;
1617 if (header) {
1618 fputs("import time: self [us] | cumulative | imported package\n",
1619 stderr);
1620 header = 0;
1621 }
1622
1623 import_level++;
1624 t1 = _PyTime_GetPerfCounter();
1625 accumulated = 0;
1626 }
1627
1628 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1629 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1630
1631 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1632 &PyId__find_and_load, abs_name,
1633 interp->import_func, NULL);
1634
1635 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1636 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1637 mod != NULL);
1638
1639 if (import_time) {
1640 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1641
1642 import_level--;
1643 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1644 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1645 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1646 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1647
1648 accumulated = accumulated_copy + cum;
1649 }
1650
1651 return mod;
1652}
1653
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001654PyObject *
1655PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1656 PyObject *locals, PyObject *fromlist,
1657 int level)
1658{
Brett Cannonfd074152012-04-14 14:10:13 -04001659 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001660 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001661 PyObject *final_mod = NULL;
1662 PyObject *mod = NULL;
1663 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001664 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001665 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001666
Brett Cannonfd074152012-04-14 14:10:13 -04001667 if (name == NULL) {
1668 PyErr_SetString(PyExc_ValueError, "Empty module name");
1669 goto error;
1670 }
1671
1672 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1673 for added performance. */
1674
1675 if (!PyUnicode_Check(name)) {
1676 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1677 goto error;
1678 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001679 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001680 goto error;
1681 }
1682 if (level < 0) {
1683 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1684 goto error;
1685 }
Brett Cannon849113a2016-01-22 15:25:50 -08001686
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001687 if (level > 0) {
1688 abs_name = resolve_name(name, globals, level);
1689 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001690 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001691 }
1692 else { /* level == 0 */
1693 if (PyUnicode_GET_LENGTH(name) == 0) {
1694 PyErr_SetString(PyExc_ValueError, "Empty module name");
1695 goto error;
1696 }
Brett Cannonfd074152012-04-14 14:10:13 -04001697 abs_name = name;
1698 Py_INCREF(abs_name);
1699 }
1700
Eric Snow3f9eee62017-09-15 16:35:20 -06001701 mod = PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001702 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001703 _Py_IDENTIFIER(__spec__);
1704 _Py_IDENTIFIER(_initializing);
1705 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001706 PyObject *value = NULL;
1707 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001708 int initializing = 0;
1709
Antoine Pitrou03989852012-08-28 00:24:52 +02001710 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001711 __spec__._initializing is true.
1712 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001713 stuffing the new module in sys.modules.
1714 */
Eric Snowb523f842013-11-22 09:05:39 -07001715 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1716 if (spec != NULL) {
1717 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1718 Py_DECREF(spec);
1719 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001720 if (value == NULL)
1721 PyErr_Clear();
1722 else {
1723 initializing = PyObject_IsTrue(value);
1724 Py_DECREF(value);
1725 if (initializing == -1)
1726 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001727 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001728 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1729 &PyId__lock_unlock_module, abs_name,
1730 NULL);
1731 if (value == NULL)
1732 goto error;
1733 Py_DECREF(value);
1734 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001735 }
Brett Cannonfd074152012-04-14 14:10:13 -04001736 }
1737 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001738 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001739 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001740 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001741 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001742 }
1743 }
1744
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001745 has_from = 0;
1746 if (fromlist != NULL && fromlist != Py_None) {
1747 has_from = PyObject_IsTrue(fromlist);
1748 if (has_from < 0)
1749 goto error;
1750 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001751 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001752 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1753 if (level == 0 || len > 0) {
1754 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001755
Victor Stinner744c34e2016-05-20 11:36:13 +02001756 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1757 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001758 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001759 }
1760
Victor Stinner744c34e2016-05-20 11:36:13 +02001761 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001762 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001763 final_mod = mod;
1764 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001765 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001766 }
1767
Brett Cannonfd074152012-04-14 14:10:13 -04001768 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001769 PyObject *front = PyUnicode_Substring(name, 0, dot);
1770 if (front == NULL) {
1771 goto error;
1772 }
1773
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001774 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001775 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001776 }
1777 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001778 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001779 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001780 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001781 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001782 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001783 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001784 }
Brett Cannonfd074152012-04-14 14:10:13 -04001785
Eric Snow3f9eee62017-09-15 16:35:20 -06001786 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001787 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001788 if (final_mod == NULL) {
1789 PyErr_Format(PyExc_KeyError,
1790 "%R not in sys.modules as expected",
1791 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001792 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001793 }
Brett Cannonfd074152012-04-14 14:10:13 -04001794 }
1795 }
1796 else {
1797 final_mod = mod;
1798 Py_INCREF(mod);
1799 }
1800 }
1801 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001802 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001803 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001804 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001805 NULL);
1806 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001807
Brett Cannonfd074152012-04-14 14:10:13 -04001808 error:
1809 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001810 Py_XDECREF(mod);
1811 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001812 if (final_mod == NULL)
1813 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001814 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001815}
1816
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001817PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001818PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001819 PyObject *fromlist, int level)
1820{
1821 PyObject *nameobj, *mod;
1822 nameobj = PyUnicode_FromString(name);
1823 if (nameobj == NULL)
1824 return NULL;
1825 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1826 fromlist, level);
1827 Py_DECREF(nameobj);
1828 return mod;
1829}
1830
1831
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001832/* Re-import a module of any kind and return its module object, WITH
1833 INCREMENTED REFERENCE COUNT */
1834
Guido van Rossum79f25d91997-04-29 20:08:16 +00001835PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001836PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001837{
Eric Snow3f9eee62017-09-15 16:35:20 -06001838 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001839 _Py_IDENTIFIER(reload);
1840 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001841 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001842 if (imp == NULL) {
1843 imp = PyImport_ImportModule("imp");
1844 if (imp == NULL) {
1845 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001848
Victor Stinner55ba38a2016-12-09 16:09:30 +01001849 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001850 Py_DECREF(imp);
1851 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001852}
1853
1854
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001855/* Higher-level import emulator which emulates the "import" statement
1856 more accurately -- it invokes the __import__() function from the
1857 builtins of the current globals. This means that the import is
1858 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001859 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001860 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001861 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001862 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001863
1864PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001865PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 static PyObject *silly_list = NULL;
1868 static PyObject *builtins_str = NULL;
1869 static PyObject *import_str = NULL;
1870 PyObject *globals = NULL;
1871 PyObject *import = NULL;
1872 PyObject *builtins = NULL;
1873 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 /* Initialize constant string objects */
1876 if (silly_list == NULL) {
1877 import_str = PyUnicode_InternFromString("__import__");
1878 if (import_str == NULL)
1879 return NULL;
1880 builtins_str = PyUnicode_InternFromString("__builtins__");
1881 if (builtins_str == NULL)
1882 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001883 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (silly_list == NULL)
1885 return NULL;
1886 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 /* Get the builtins from current globals */
1889 globals = PyEval_GetGlobals();
1890 if (globals != NULL) {
1891 Py_INCREF(globals);
1892 builtins = PyObject_GetItem(globals, builtins_str);
1893 if (builtins == NULL)
1894 goto err;
1895 }
1896 else {
1897 /* No globals -- use standard builtins, and fake globals */
1898 builtins = PyImport_ImportModuleLevel("builtins",
1899 NULL, NULL, NULL, 0);
1900 if (builtins == NULL)
1901 return NULL;
1902 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1903 if (globals == NULL)
1904 goto err;
1905 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 /* Get the __import__ function from the builtins */
1908 if (PyDict_Check(builtins)) {
1909 import = PyObject_GetItem(builtins, import_str);
1910 if (import == NULL)
1911 PyErr_SetObject(PyExc_KeyError, import_str);
1912 }
1913 else
1914 import = PyObject_GetAttr(builtins, import_str);
1915 if (import == NULL)
1916 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001919 Always use absolute import here.
1920 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1922 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001923 if (r == NULL)
1924 goto err;
1925 Py_DECREF(r);
1926
Eric Snow3f9eee62017-09-15 16:35:20 -06001927 r = PyImport_GetModule(module_name);
1928 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001929 PyErr_SetObject(PyExc_KeyError, module_name);
1930 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001931
1932 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 Py_XDECREF(globals);
1934 Py_XDECREF(builtins);
1935 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001938}
1939
Brett Cannon4caa61d2014-01-09 19:03:32 -05001940/*[clinic input]
1941_imp.extension_suffixes
1942
1943Returns the list of file suffixes used to identify extension modules.
1944[clinic start generated code]*/
1945
Brett Cannon4caa61d2014-01-09 19:03:32 -05001946static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001947_imp_extension_suffixes_impl(PyObject *module)
1948/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001951 const char *suffix;
1952 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 list = PyList_New(0);
1955 if (list == NULL)
1956 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001957#ifdef HAVE_DYNAMIC_LOADING
1958 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1959 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (item == NULL) {
1961 Py_DECREF(list);
1962 return NULL;
1963 }
1964 if (PyList_Append(list, item) < 0) {
1965 Py_DECREF(list);
1966 Py_DECREF(item);
1967 return NULL;
1968 }
1969 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001970 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 }
Brett Cannon2657df42012-05-04 15:20:40 -04001972#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001974}
1975
Brett Cannon4caa61d2014-01-09 19:03:32 -05001976/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001977_imp.init_frozen
1978
1979 name: unicode
1980 /
1981
1982Initializes a frozen module.
1983[clinic start generated code]*/
1984
Brett Cannon4caa61d2014-01-09 19:03:32 -05001985static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001986_imp_init_frozen_impl(PyObject *module, PyObject *name)
1987/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 int ret;
1990 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001991
Victor Stinner53dc7352011-03-20 01:50:21 +01001992 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (ret < 0)
1994 return NULL;
1995 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001996 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001998 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 Py_XINCREF(m);
2000 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002001}
2002
Brett Cannon4caa61d2014-01-09 19:03:32 -05002003/*[clinic input]
2004_imp.get_frozen_object
2005
2006 name: unicode
2007 /
2008
2009Create a code object for a frozen module.
2010[clinic start generated code]*/
2011
Brett Cannon4caa61d2014-01-09 19:03:32 -05002012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002013_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2014/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002017}
2018
Brett Cannon4caa61d2014-01-09 19:03:32 -05002019/*[clinic input]
2020_imp.is_frozen_package
2021
2022 name: unicode
2023 /
2024
2025Returns True if the module name is of a frozen package.
2026[clinic start generated code]*/
2027
Brett Cannon4caa61d2014-01-09 19:03:32 -05002028static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002029_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2030/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002033}
2034
Brett Cannon4caa61d2014-01-09 19:03:32 -05002035/*[clinic input]
2036_imp.is_builtin
2037
2038 name: unicode
2039 /
2040
2041Returns True if the module name corresponds to a built-in module.
2042[clinic start generated code]*/
2043
Guido van Rossum79f25d91997-04-29 20:08:16 +00002044static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002045_imp_is_builtin_impl(PyObject *module, PyObject *name)
2046/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002047{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002048 return PyLong_FromLong(is_builtin(name));
2049}
2050
2051/*[clinic input]
2052_imp.is_frozen
2053
2054 name: unicode
2055 /
2056
2057Returns True if the module name corresponds to a frozen module.
2058[clinic start generated code]*/
2059
Brett Cannon4caa61d2014-01-09 19:03:32 -05002060static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002061_imp_is_frozen_impl(PyObject *module, PyObject *name)
2062/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002063{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002064 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 p = find_frozen(name);
2067 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002068}
2069
Larry Hastings1df0b352015-08-24 19:53:56 -07002070/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2071static int
2072exec_builtin_or_dynamic(PyObject *mod) {
2073 PyModuleDef *def;
2074 void *state;
2075
2076 if (!PyModule_Check(mod)) {
2077 return 0;
2078 }
2079
2080 def = PyModule_GetDef(mod);
2081 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002082 return 0;
2083 }
Brett Cannon52794db2016-09-07 17:00:43 -07002084
Larry Hastings1df0b352015-08-24 19:53:56 -07002085 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002086 if (state) {
2087 /* Already initialized; skip reload */
2088 return 0;
2089 }
Brett Cannon52794db2016-09-07 17:00:43 -07002090
Larry Hastings1df0b352015-08-24 19:53:56 -07002091 return PyModule_ExecDef(mod, def);
2092}
2093
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002094#ifdef HAVE_DYNAMIC_LOADING
2095
Brett Cannon4caa61d2014-01-09 19:03:32 -05002096/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002097_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002098
Nick Coghland5cacbb2015-05-23 22:24:10 +10002099 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002100 file: object = NULL
2101 /
2102
Nick Coghland5cacbb2015-05-23 22:24:10 +10002103Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002104[clinic start generated code]*/
2105
Brett Cannon4caa61d2014-01-09 19:03:32 -05002106static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002107_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2108/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002109{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002110 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002111 FILE *fp;
2112
Nick Coghland5cacbb2015-05-23 22:24:10 +10002113 name = PyObject_GetAttrString(spec, "name");
2114 if (name == NULL) {
2115 return NULL;
2116 }
2117
2118 path = PyObject_GetAttrString(spec, "origin");
2119 if (path == NULL) {
2120 Py_DECREF(name);
2121 return NULL;
2122 }
2123
2124 mod = _PyImport_FindExtensionObject(name, path);
2125 if (mod != NULL) {
2126 Py_DECREF(name);
2127 Py_DECREF(path);
2128 Py_INCREF(mod);
2129 return mod;
2130 }
2131
Brett Cannon4caa61d2014-01-09 19:03:32 -05002132 if (file != NULL) {
2133 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002134 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002135 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002136 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002140 else
2141 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002142
2143 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2144
2145 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002146 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (fp)
2148 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002149 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002150}
2151
Nick Coghland5cacbb2015-05-23 22:24:10 +10002152/*[clinic input]
2153_imp.exec_dynamic -> int
2154
2155 mod: object
2156 /
2157
2158Initialize an extension module.
2159[clinic start generated code]*/
2160
2161static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002162_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2163/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002164{
Larry Hastings1df0b352015-08-24 19:53:56 -07002165 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002166}
2167
2168
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002169#endif /* HAVE_DYNAMIC_LOADING */
2170
Larry Hastings7726ac92014-01-31 22:03:12 -08002171/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002172_imp.exec_builtin -> int
2173
2174 mod: object
2175 /
2176
2177Initialize a built-in module.
2178[clinic start generated code]*/
2179
2180static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002181_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2182/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002183{
2184 return exec_builtin_or_dynamic(mod);
2185}
2186
Barry Warsaw28a691b2010-04-17 00:19:56 +00002187
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002188PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002189"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002190
Guido van Rossum79f25d91997-04-29 20:08:16 +00002191static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002192 _IMP_EXTENSION_SUFFIXES_METHODDEF
2193 _IMP_LOCK_HELD_METHODDEF
2194 _IMP_ACQUIRE_LOCK_METHODDEF
2195 _IMP_RELEASE_LOCK_METHODDEF
2196 _IMP_GET_FROZEN_OBJECT_METHODDEF
2197 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002198 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002199 _IMP_INIT_FROZEN_METHODDEF
2200 _IMP_IS_BUILTIN_METHODDEF
2201 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002202 _IMP_CREATE_DYNAMIC_METHODDEF
2203 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002204 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002205 _IMP__FIX_CO_FILENAME_METHODDEF
2206 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002207};
2208
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002209
Martin v. Löwis1a214512008-06-11 05:26:20 +00002210static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002212 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 doc_imp,
2214 0,
2215 imp_methods,
2216 NULL,
2217 NULL,
2218 NULL,
2219 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002220};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002221
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002222PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002223PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 m = PyModule_Create(&impmodule);
2228 if (m == NULL)
2229 goto failure;
2230 d = PyModule_GetDict(m);
2231 if (d == NULL)
2232 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002235 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_XDECREF(m);
2237 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002238}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002239
2240
Guido van Rossumb18618d2000-05-03 23:44:39 +00002241/* API for embedding applications that want to add their own entries
2242 to the table of built-in modules. This should normally be called
2243 *before* Py_Initialize(). When the table resize fails, -1 is
2244 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002245
2246 After a similar function by Just van Rossum. */
2247
2248int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002249PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 struct _inittab *p;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002252 Py_ssize_t i, n;
2253 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* Count the number of entries in both tables */
2256 for (n = 0; newtab[n].name != NULL; n++)
2257 ;
2258 if (n == 0)
2259 return 0; /* Nothing to do */
2260 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2261 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002262
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002263 /* Force default raw memory allocator to get a known allocator to be able
2264 to release the memory in _PyImport_Fini2() */
2265 PyMemAllocatorEx old_alloc;
2266 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 /* Allocate new memory for the combined table */
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002269 if ((i + n + 1) <= PY_SSIZE_T_MAX / sizeof(struct _inittab)) {
2270 size_t size = sizeof(struct _inittab) * (i + n + 1);
2271 p = PyMem_RawRealloc(inittab_copy, size);
2272 }
2273 else {
2274 p = NULL;
2275 }
2276 if (p == NULL) {
2277 res = -1;
2278 goto done;
2279 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002280
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002281 /* Copy the tables into the new memory at the first call
2282 to PyImport_ExtendInittab(). */
2283 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002285 }
2286 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2287 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002288
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002289done:
2290 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2291 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002292}
2293
2294/* Shorthand to add a single entry given a name and a function */
2295
2296int
Brett Cannona826f322009-04-02 03:41:46 +00002297PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002302
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002303 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002307}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002308
2309#ifdef __cplusplus
2310}
2311#endif