blob: e761f65c66ba7f0ccd358230d0a7e924d822f4b9 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module definition and import implementation */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00006#undef Yield /* undefine macro conflicting with winbase.h */
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08007#include "internal/hash.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{
ukwksk5e6312c2018-05-15 04:10:52 +090094 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040095 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
ukwksk5e6312c2018-05-15 04:10:52 +0900106 zipimport = PyImport_ImportModule("zipimport");
107 if (zipimport == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 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);
ukwksk5e6312c2018-05-15 04:10:52 +0900114 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200115 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900116 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 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{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200307 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
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);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300366 if (m == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600367 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;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200400 PyInterpreterState *interp = _PyInterpreterState_Get();
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");
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300418 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300419 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300420 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200421
422 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200424 PySys_WriteStderr("# clear sys.%s\n", *p);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300425 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300426 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200429 for (p = sys_files; *p != NULL; p+=2) {
430 if (Py_VerboseFlag)
431 PySys_WriteStderr("# restore sys.%s\n", *p);
432 value = PyDict_GetItemString(interp->sysdict, *(p+1));
433 if (value == NULL)
434 value = Py_None;
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300435 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300436 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300437 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000439
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200440 /* We prepare a list which will receive (name, weakref) tuples of
441 modules when they are removed from sys.modules. The name is used
442 for diagnosis messages (in verbose mode), while the weakref helps
443 detect those modules which have been held alive. */
444 weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300445 if (weaklist == NULL) {
446 PyErr_WriteUnraisable(NULL);
447 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200448
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200449#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200451 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300452 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200453 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300454 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300455 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300456 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300458 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200459 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300460 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300461 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300462 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600464#define CLEAR_MODULE(name, mod) \
465 if (PyModule_Check(mod)) { \
466 if (Py_VerboseFlag && PyUnicode_Check(name)) \
467 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
468 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300469 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300470 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300471 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600472 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000473
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200474 /* Remove all modules from sys.modules, hoping that garbage collection
475 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600476 if (PyDict_CheckExact(modules)) {
477 pos = 0;
478 while (PyDict_Next(modules, &pos, &key, &value)) {
479 CLEAR_MODULE(key, value);
480 }
481 }
482 else {
483 PyObject *iterator = PyObject_GetIter(modules);
484 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300485 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600486 }
487 else {
488 while ((key = PyIter_Next(iterator))) {
489 value = PyObject_GetItem(modules, key);
490 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300491 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600492 continue;
493 }
494 CLEAR_MODULE(key, value);
495 Py_DECREF(value);
496 Py_DECREF(key);
497 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300498 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300499 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300500 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600501 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
503 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000504
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200505 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600506 if (PyDict_CheckExact(modules)) {
507 PyDict_Clear(modules);
508 }
509 else {
510 _Py_IDENTIFIER(clear);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300511 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
512 PyErr_WriteUnraisable(NULL);
513 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600514 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200515 /* Restore the original builtins dict, to ensure that any
516 user data gets cleared. */
517 dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300518 if (dict == NULL) {
519 PyErr_WriteUnraisable(NULL);
520 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200521 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300522 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200523 PyErr_Clear();
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300524 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200525 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200526 /* Clear module dict copies stored in the interpreter state */
527 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200528 /* Collect references */
529 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200530 /* Dump GC stats before it's too late, since it uses the warnings
531 machinery. */
532 _PyGC_DumpShutdownStats();
533
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200534 /* Now, if there are any modules left alive, clear their globals to
535 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200536 up here, since they are kept alive in the interpreter state.
537
538 The special treatment of "builtins" here is because even
539 when it's not referenced as a module, its dictionary is
540 referenced by almost every module's __builtins__. Since
541 deleting a module clears its dictionary (even if there are
542 references left to it), we need to delete the "builtins"
543 module last. Likewise, we don't delete sys until the very
544 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200545 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200546 Py_ssize_t i;
547 /* Since dict is ordered in CPython 3.6+, modules are saved in
548 importing order. First clear modules imported later. */
549 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200550 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200551 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200552 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
553 if (mod == Py_None)
554 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200555 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200556 dict = PyModule_GetDict(mod);
557 if (dict == interp->builtins || dict == interp->sysdict)
558 continue;
559 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200560 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200561 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200562 _PyModule_Clear(mod);
563 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200564 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200565 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000567
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200568 /* Next, delete sys and builtins (in that order) */
569 if (Py_VerboseFlag)
570 PySys_FormatStderr("# cleanup[3] wiping sys\n");
571 _PyModule_ClearDict(interp->sysdict);
572 if (Py_VerboseFlag)
573 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
574 _PyModule_ClearDict(interp->builtins);
575
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200576 /* Clear and delete the modules directory. Actual modules will
577 still be there only if imported during the execution of some
578 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700579 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200581
582 /* Once more */
583 _PyGC_CollectNoFail();
584
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300585#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200586#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000587}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000588
589
Barry Warsaw28a691b2010-04-17 00:19:56 +0000590/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000591
592long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000593PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000594{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200595 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200596 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600597 PyObject *external, *pyc_magic;
598
599 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
600 if (external == NULL)
601 return -1;
602 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
603 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400604 if (pyc_magic == NULL)
605 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200606 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700607 Py_DECREF(pyc_magic);
608 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609}
610
611
Brett Cannon3adc7b72012-07-09 14:22:12 -0400612extern const char * _PySys_ImplCacheTag;
613
Barry Warsaw28a691b2010-04-17 00:19:56 +0000614const char *
615PyImport_GetMagicTag(void)
616{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400617 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000618}
619
Brett Cannon98979b82012-07-02 15:13:11 -0400620
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621/* Magic for extension modules (built-in as well as dynamically
622 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200623 once, we keep a static dictionary 'extensions' keyed by the tuple
624 (module name, module name) (for built-in modules) or by
625 (filename, module name) (for dynamically loaded modules), containing these
626 modules. A copy of the module's dictionary is stored by calling
627 _PyImport_FixupExtensionObject() immediately after the module initialization
628 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100629 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000630
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000631 Modules which do support multiple initialization set their m_size
632 field to a non-negative number (indicating the size of the
633 module-specific state). They are still recorded in the extensions
634 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000635*/
636
637int
Victor Stinner95872862011-03-07 18:20:56 +0100638_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600639 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000640{
Eric Snowd393c1b2017-09-14 12:18:12 -0600641 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500643 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (extensions == NULL) {
645 extensions = PyDict_New();
646 if (extensions == NULL)
647 return -1;
648 }
649 if (mod == NULL || !PyModule_Check(mod)) {
650 PyErr_BadInternalCall();
651 return -1;
652 }
653 def = PyModule_GetDef(mod);
654 if (!def) {
655 PyErr_BadInternalCall();
656 return -1;
657 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600658 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 return -1;
660 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600661 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 return -1;
663 }
664 if (def->m_size == -1) {
665 if (def->m_base.m_copy) {
666 /* Somebody already imported the module,
667 likely under a different name.
668 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200669 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
671 dict = PyModule_GetDict(mod);
672 if (dict == NULL)
673 return -1;
674 def->m_base.m_copy = PyDict_Copy(dict);
675 if (def->m_base.m_copy == NULL)
676 return -1;
677 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500678 key = PyTuple_Pack(2, filename, name);
679 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200680 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500681 res = PyDict_SetItem(extensions, key, (PyObject *)def);
682 Py_DECREF(key);
683 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200684 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000686}
687
Victor Stinner49d3f252010-10-17 01:24:53 +0000688int
Eric Snowd393c1b2017-09-14 12:18:12 -0600689_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000690{
691 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100692 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100693 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100694 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000695 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600696 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100697 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000698 return res;
699}
700
Guido van Rossum25ce5661997-08-02 03:10:38 +0000701PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100702_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000703{
Eric Snowd393c1b2017-09-14 12:18:12 -0600704 PyObject *modules = PyImport_GetModuleDict();
705 return _PyImport_FindExtensionObjectEx(name, filename, modules);
706}
707
708PyObject *
709_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
710 PyObject *modules)
711{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500712 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyModuleDef* def;
714 if (extensions == NULL)
715 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500716 key = PyTuple_Pack(2, filename, name);
717 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200718 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500719 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
720 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (def == NULL)
722 return NULL;
723 if (def->m_size == -1) {
724 /* Module does not support repeated initialization */
725 if (def->m_base.m_copy == NULL)
726 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600727 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (mod == NULL)
729 return NULL;
730 mdict = PyModule_GetDict(mod);
731 if (mdict == NULL)
732 return NULL;
733 if (PyDict_Update(mdict, def->m_base.m_copy))
734 return NULL;
735 }
736 else {
737 if (def->m_base.m_init == NULL)
738 return NULL;
739 mod = def->m_base.m_init();
740 if (mod == NULL)
741 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600742 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200743 Py_DECREF(mod);
744 return NULL;
745 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 Py_DECREF(mod);
747 }
748 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600749 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 Py_DECREF(mod);
751 return NULL;
752 }
753 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100754 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 name, filename);
756 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000757
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000758}
759
Victor Stinner49d3f252010-10-17 01:24:53 +0000760PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600761_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000762{
Victor Stinner95872862011-03-07 18:20:56 +0100763 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100764 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100765 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000766 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600767 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100768 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000769 return res;
770}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000771
772/* Get the module object corresponding to a module name.
773 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000774 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000775 Because the former action is most common, THIS DOES NOT RETURN A
776 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000777
Guido van Rossum79f25d91997-04-29 20:08:16 +0000778PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000779PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600782 return _PyImport_AddModuleObject(name, modules);
783}
784
785PyObject *
786_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
787{
Eric Snow86b7afd2017-09-04 17:54:09 -0600788 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600789 if (PyDict_CheckExact(modules)) {
790 m = PyDict_GetItemWithError(modules, name);
791 }
792 else {
793 m = PyObject_GetItem(modules, name);
794 // For backward-comaptibility we copy the behavior
795 // of PyDict_GetItemWithError().
796 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
797 PyErr_Clear();
798 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200799 }
800 if (PyErr_Occurred()) {
801 return NULL;
802 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600803 if (m != NULL && PyModule_Check(m)) {
804 return m;
805 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000806 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (m == NULL)
808 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600809 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 Py_DECREF(m);
811 return NULL;
812 }
813 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000816}
817
Victor Stinner27ee0892011-03-04 12:57:09 +0000818PyObject *
819PyImport_AddModule(const char *name)
820{
821 PyObject *nameobj, *module;
822 nameobj = PyUnicode_FromString(name);
823 if (nameobj == NULL)
824 return NULL;
825 module = PyImport_AddModuleObject(nameobj);
826 Py_DECREF(nameobj);
827 return module;
828}
829
830
Tim Peters1cd70172004-08-02 03:52:12 +0000831/* Remove name from sys.modules, if it's there. */
832static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000833remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *modules = PyImport_GetModuleDict();
Eric Snow3f9eee62017-09-15 16:35:20 -0600836 if (PyMapping_DelItem(modules, name) < 0) {
837 if (!PyMapping_HasKey(modules, name)) {
838 return;
839 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 Py_FatalError("import: deleting existing key in"
841 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600842 }
Tim Peters1cd70172004-08-02 03:52:12 +0000843}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000844
Christian Heimes3b06e532008-01-07 20:12:44 +0000845
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000846/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000847 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
848 * removed from sys.modules, to avoid leaving damaged module objects
849 * in sys.modules. The caller may wish to restore the original
850 * module object (if any) in this case; PyImport_ReloadModule is an
851 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000852 *
853 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
854 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000855 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000856PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300857PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 return PyImport_ExecCodeModuleWithPathnames(
860 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000861}
862
863PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300864PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 return PyImport_ExecCodeModuleWithPathnames(
867 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000868}
869
870PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300871PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
872 const char *pathname,
873 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000874{
Victor Stinner27ee0892011-03-04 12:57:09 +0000875 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600876 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000877
878 nameobj = PyUnicode_FromString(name);
879 if (nameobj == NULL)
880 return NULL;
881
Victor Stinner27ee0892011-03-04 12:57:09 +0000882 if (cpathname != NULL) {
883 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
884 if (cpathobj == NULL)
885 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400886 }
887 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000888 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400889
890 if (pathname != NULL) {
891 pathobj = PyUnicode_DecodeFSDefault(pathname);
892 if (pathobj == NULL)
893 goto error;
894 }
895 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200896 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400897 _Py_IDENTIFIER(_get_sourcefile);
898
899 if (interp == NULL) {
900 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
901 "no interpreter!");
902 }
903
Eric Snow32439d62015-05-02 19:15:18 -0600904 external= PyObject_GetAttrString(interp->importlib,
905 "_bootstrap_external");
906 if (external != NULL) {
907 pathobj = _PyObject_CallMethodIdObjArgs(external,
908 &PyId__get_sourcefile, cpathobj,
909 NULL);
910 Py_DECREF(external);
911 }
Brett Cannona6473f92012-07-13 13:57:03 -0400912 if (pathobj == NULL)
913 PyErr_Clear();
914 }
915 else
916 pathobj = NULL;
917
Victor Stinner27ee0892011-03-04 12:57:09 +0000918 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
919error:
920 Py_DECREF(nameobj);
921 Py_XDECREF(pathobj);
922 Py_XDECREF(cpathobj);
923 return m;
924}
925
Brett Cannon18fc4e72014-04-04 10:01:46 -0400926static PyObject *
927module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000928{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400929 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000930
Victor Stinner27ee0892011-03-04 12:57:09 +0000931 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (m == NULL)
933 return NULL;
934 /* If the module is being reloaded, we get the old module back
935 and re-use its dict to exec the new code. */
936 d = PyModule_GetDict(m);
937 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
938 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400939 PyEval_GetBuiltins()) != 0) {
940 remove_module(name);
941 return NULL;
942 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400944
Eric Snow08197a42014-05-12 17:54:55 -0600945 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400946}
947
948static PyObject *
949exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
950{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400951 PyObject *v, *m;
952
953 v = PyEval_EvalCode(code_object, module_dict, module_dict);
954 if (v == NULL) {
955 remove_module(name);
956 return NULL;
957 }
958 Py_DECREF(v);
959
Eric Snow3f9eee62017-09-15 16:35:20 -0600960 m = PyImport_GetModule(name);
961 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400962 PyErr_Format(PyExc_ImportError,
963 "Loaded module %R not found in sys.modules",
964 name);
965 return NULL;
966 }
967
Brett Cannon18fc4e72014-04-04 10:01:46 -0400968 return m;
969}
970
971PyObject*
972PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
973 PyObject *cpathname)
974{
Eric Snow32439d62015-05-02 19:15:18 -0600975 PyObject *d, *external, *res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200976 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow08197a42014-05-12 17:54:55 -0600977 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400978
979 d = module_dict_for_exec(name);
980 if (d == NULL) {
981 return NULL;
982 }
983
Eric Snow08197a42014-05-12 17:54:55 -0600984 if (pathname == NULL) {
985 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 }
Eric Snow32439d62015-05-02 19:15:18 -0600987 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
988 if (external == NULL)
989 return NULL;
990 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600991 &PyId__fix_up_module,
992 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600993 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600994 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600995 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600996 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
Eric Snow08197a42014-05-12 17:54:55 -0600998 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000999}
1000
1001
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001002static void
1003update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyObject *constants, *tmp;
1006 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (PyUnicode_Compare(co->co_filename, oldname))
1009 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001010
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001011 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001012 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 constants = co->co_consts;
1015 n = PyTuple_GET_SIZE(constants);
1016 for (i = 0; i < n; i++) {
1017 tmp = PyTuple_GET_ITEM(constants, i);
1018 if (PyCode_Check(tmp))
1019 update_code_filenames((PyCodeObject *)tmp,
1020 oldname, newname);
1021 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001022}
1023
Victor Stinner2f42ae52011-03-20 00:41:24 +01001024static void
1025update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001026{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001027 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001028
Victor Stinner2f42ae52011-03-20 00:41:24 +01001029 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1030 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 oldname = co->co_filename;
1033 Py_INCREF(oldname);
1034 update_code_filenames(co, oldname, newname);
1035 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001036}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001037
Brett Cannon4caa61d2014-01-09 19:03:32 -05001038/*[clinic input]
1039_imp._fix_co_filename
1040
1041 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1042 Code object to change.
1043
1044 path: unicode
1045 File path to use.
1046 /
1047
1048Changes code.co_filename to specify the passed-in file path.
1049[clinic start generated code]*/
1050
Brett Cannon4caa61d2014-01-09 19:03:32 -05001051static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001052_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001053 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001054/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001055
Brett Cannon4caa61d2014-01-09 19:03:32 -05001056{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001057 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001058
1059 Py_RETURN_NONE;
1060}
1061
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001062
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001063/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001064static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001065
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001066
1067/* Helper to test for built-in module */
1068
1069static int
Victor Stinner95872862011-03-07 18:20:56 +01001070is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001071{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001072 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001074 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (PyImport_Inittab[i].initfunc == NULL)
1076 return -1;
1077 else
1078 return 1;
1079 }
1080 }
1081 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001082}
1083
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001084
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001085/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001086 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001087 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001088 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001089 this tells our caller that the path based finder could not find
1090 a finder for this path item. Cache the result in
1091 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001092 Returns a borrowed reference. */
1093
1094static PyObject *
1095get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *importer;
1099 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 /* These conditions are the caller's responsibility: */
1102 assert(PyList_Check(path_hooks));
1103 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 nhooks = PyList_Size(path_hooks);
1106 if (nhooks < 0)
1107 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 importer = PyDict_GetItem(path_importer_cache, p);
1110 if (importer != NULL)
1111 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 /* set path_importer_cache[p] to None to avoid recursion */
1114 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1115 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 for (j = 0; j < nhooks; j++) {
1118 PyObject *hook = PyList_GetItem(path_hooks, j);
1119 if (hook == NULL)
1120 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001121 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (importer != NULL)
1123 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1126 return NULL;
1127 }
1128 PyErr_Clear();
1129 }
1130 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001131 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 }
1133 if (importer != NULL) {
1134 int err = PyDict_SetItem(path_importer_cache, p, importer);
1135 Py_DECREF(importer);
1136 if (err != 0)
1137 return NULL;
1138 }
1139 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001140}
1141
Benjamin Petersone5024512018-09-12 12:06:42 -07001142PyObject *
Christian Heimes9cd17752007-11-18 19:35:23 +00001143PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001145
Victor Stinner1e53bba2013-07-16 22:26:05 +02001146 path_importer_cache = PySys_GetObject("path_importer_cache");
1147 path_hooks = PySys_GetObject("path_hooks");
1148 if (path_importer_cache != NULL && path_hooks != NULL) {
1149 importer = get_path_importer(path_importer_cache,
1150 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }
1152 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1153 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001154}
1155
Nick Coghland5cacbb2015-05-23 22:24:10 +10001156/*[clinic input]
1157_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001158
Nick Coghland5cacbb2015-05-23 22:24:10 +10001159 spec: object
1160 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001161
Nick Coghland5cacbb2015-05-23 22:24:10 +10001162Create an extension module.
1163[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001164
Nick Coghland5cacbb2015-05-23 22:24:10 +10001165static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001166_imp_create_builtin(PyObject *module, PyObject *spec)
1167/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001170 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001171 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001172 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001173
Nick Coghland5cacbb2015-05-23 22:24:10 +10001174 name = PyObject_GetAttrString(spec, "name");
1175 if (name == NULL) {
1176 return NULL;
1177 }
1178
Victor Stinner5eb4f592013-11-14 22:38:52 +01001179 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001180 if (mod || PyErr_Occurred()) {
1181 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001182 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001183 return mod;
1184 }
1185
1186 namestr = PyUnicode_AsUTF8(name);
1187 if (namestr == NULL) {
1188 Py_DECREF(name);
1189 return NULL;
1190 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001191
Eric Snowd393c1b2017-09-14 12:18:12 -06001192 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001194 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001195 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001197 /* Cannot re-init internal module ("sys" or "builtins") */
1198 mod = PyImport_AddModule(namestr);
1199 Py_DECREF(name);
1200 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001203 if (mod == NULL) {
1204 Py_DECREF(name);
1205 return NULL;
1206 }
1207 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1208 Py_DECREF(name);
1209 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1210 } else {
1211 /* Remember pointer to module init function. */
1212 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001213 if (def == NULL) {
1214 Py_DECREF(name);
1215 return NULL;
1216 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001217 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001218 if (modules == NULL) {
1219 modules = PyImport_GetModuleDict();
1220 }
1221 if (_PyImport_FixupExtensionObject(mod, name, name,
1222 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001223 Py_DECREF(name);
1224 return NULL;
1225 }
1226 Py_DECREF(name);
1227 return mod;
1228 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 }
1230 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001231 Py_DECREF(name);
1232 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001233}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001234
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001235
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001236/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001237
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001238static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001239find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001240{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001241 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001242
Victor Stinner53dc7352011-03-20 01:50:21 +01001243 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 for (p = PyImport_FrozenModules; ; p++) {
1247 if (p->name == NULL)
1248 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001249 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 break;
1251 }
1252 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001253}
1254
Guido van Rossum79f25d91997-04-29 20:08:16 +00001255static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001256get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001257{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001258 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (p == NULL) {
1262 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001263 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 name);
1265 return NULL;
1266 }
1267 if (p->code == NULL) {
1268 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001269 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 name);
1271 return NULL;
1272 }
1273 size = p->size;
1274 if (size < 0)
1275 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001276 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001277}
1278
Brett Cannon8d110132009-03-15 02:20:16 +00001279static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001280is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001281{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001282 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (p == NULL) {
1286 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001287 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 name);
1289 return NULL;
1290 }
Brett Cannon8d110132009-03-15 02:20:16 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (size < 0)
1295 Py_RETURN_TRUE;
1296 else
1297 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001298}
1299
1300
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001301/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001302 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001303 an exception set if the initialization failed.
1304 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001305
1306int
Victor Stinner53dc7352011-03-20 01:50:21 +01001307PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001308{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001309 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001310 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 int ispackage;
1312 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001313
Victor Stinner53dc7352011-03-20 01:50:21 +01001314 p = find_frozen(name);
1315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (p == NULL)
1317 return 0;
1318 if (p->code == NULL) {
1319 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001320 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 name);
1322 return -1;
1323 }
1324 size = p->size;
1325 ispackage = (size < 0);
1326 if (ispackage)
1327 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001328 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (co == NULL)
1330 return -1;
1331 if (!PyCode_Check(co)) {
1332 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001333 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 name);
1335 goto err_return;
1336 }
1337 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001338 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001339 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001341 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (m == NULL)
1343 goto err_return;
1344 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001345 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 goto err_return;
1348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 err = PyDict_SetItemString(d, "__path__", l);
1350 Py_DECREF(l);
1351 if (err != 0)
1352 goto err_return;
1353 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001354 d = module_dict_for_exec(name);
1355 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001356 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001357 }
1358 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (m == NULL)
1360 goto err_return;
1361 Py_DECREF(co);
1362 Py_DECREF(m);
1363 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001364err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 Py_DECREF(co);
1366 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001367}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001368
Victor Stinner53dc7352011-03-20 01:50:21 +01001369int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001370PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001371{
1372 PyObject *nameobj;
1373 int ret;
1374 nameobj = PyUnicode_InternFromString(name);
1375 if (nameobj == NULL)
1376 return -1;
1377 ret = PyImport_ImportFrozenModuleObject(nameobj);
1378 Py_DECREF(nameobj);
1379 return ret;
1380}
1381
Guido van Rossum74e6a111994-08-29 12:54:38 +00001382
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001383/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001384 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001385
Guido van Rossum79f25d91997-04-29 20:08:16 +00001386PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001387PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyObject *pname;
1390 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 pname = PyUnicode_FromString(name);
1393 if (pname == NULL)
1394 return NULL;
1395 result = PyImport_Import(pname);
1396 Py_DECREF(pname);
1397 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001398}
1399
Christian Heimes072c0f12008-01-03 23:01:04 +00001400/* Import a module without blocking
1401 *
1402 * At first it tries to fetch the module from sys.modules. If the module was
1403 * never loaded before it loads it with PyImport_ImportModule() unless another
1404 * thread holds the import lock. In the latter case the function raises an
1405 * ImportError instead of blocking.
1406 *
1407 * Returns the module object with incremented ref count.
1408 */
1409PyObject *
1410PyImport_ImportModuleNoBlock(const char *name)
1411{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001412 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001413}
1414
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001415
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001416/* Remove importlib frames from the traceback,
1417 * except in Verbose mode. */
1418static void
1419remove_importlib_frames(void)
1420{
1421 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001422 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001423 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001424 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001425 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001426 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001427 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001428
1429 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001430 from the traceback. We always trim chunks
1431 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001432
1433 PyErr_Fetch(&exception, &value, &base_tb);
1434 if (!exception || Py_VerboseFlag)
1435 goto done;
1436 if (PyType_IsSubtype((PyTypeObject *) exception,
1437 (PyTypeObject *) PyExc_ImportError))
1438 always_trim = 1;
1439
1440 prev_link = &base_tb;
1441 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001442 while (tb != NULL) {
1443 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1444 PyObject *next = (PyObject *) traceback->tb_next;
1445 PyFrameObject *frame = traceback->tb_frame;
1446 PyCodeObject *code = frame->f_code;
1447 int now_in_importlib;
1448
1449 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001450 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1451 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001452 if (now_in_importlib && !in_importlib) {
1453 /* This is the link to this chunk of importlib tracebacks */
1454 outer_link = prev_link;
1455 }
1456 in_importlib = now_in_importlib;
1457
1458 if (in_importlib &&
1459 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001460 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001461 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001462 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001463 prev_link = outer_link;
1464 }
1465 else {
1466 prev_link = (PyObject **) &traceback->tb_next;
1467 }
1468 tb = next;
1469 }
1470done:
1471 PyErr_Restore(exception, value, base_tb);
1472}
1473
1474
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001475static PyObject *
1476resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001477{
Eric Snowb523f842013-11-22 09:05:39 -07001478 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001479 _Py_IDENTIFIER(__package__);
1480 _Py_IDENTIFIER(__path__);
1481 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001482 _Py_IDENTIFIER(parent);
1483 PyObject *abs_name;
1484 PyObject *package = NULL;
1485 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001486 Py_ssize_t last_dot;
1487 PyObject *base;
1488 int level_up;
1489
1490 if (globals == NULL) {
1491 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1492 goto error;
1493 }
1494 if (!PyDict_Check(globals)) {
1495 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1496 goto error;
1497 }
1498 package = _PyDict_GetItemId(globals, &PyId___package__);
1499 if (package == Py_None) {
1500 package = NULL;
1501 }
1502 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1503
1504 if (package != NULL) {
1505 Py_INCREF(package);
1506 if (!PyUnicode_Check(package)) {
1507 PyErr_SetString(PyExc_TypeError, "package must be a string");
1508 goto error;
1509 }
1510 else if (spec != NULL && spec != Py_None) {
1511 int equal;
1512 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1513 if (parent == NULL) {
1514 goto error;
1515 }
1516
1517 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1518 Py_DECREF(parent);
1519 if (equal < 0) {
1520 goto error;
1521 }
1522 else if (equal == 0) {
1523 if (PyErr_WarnEx(PyExc_ImportWarning,
1524 "__package__ != __spec__.parent", 1) < 0) {
1525 goto error;
1526 }
1527 }
1528 }
1529 }
1530 else if (spec != NULL && spec != Py_None) {
1531 package = _PyObject_GetAttrId(spec, &PyId_parent);
1532 if (package == NULL) {
1533 goto error;
1534 }
1535 else if (!PyUnicode_Check(package)) {
1536 PyErr_SetString(PyExc_TypeError,
1537 "__spec__.parent must be a string");
1538 goto error;
1539 }
1540 }
1541 else {
1542 if (PyErr_WarnEx(PyExc_ImportWarning,
1543 "can't resolve package from __spec__ or __package__, "
1544 "falling back on __name__ and __path__", 1) < 0) {
1545 goto error;
1546 }
1547
1548 package = _PyDict_GetItemId(globals, &PyId___name__);
1549 if (package == NULL) {
1550 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1551 goto error;
1552 }
1553
1554 Py_INCREF(package);
1555 if (!PyUnicode_Check(package)) {
1556 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1557 goto error;
1558 }
1559
1560 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1561 Py_ssize_t dot;
1562
1563 if (PyUnicode_READY(package) < 0) {
1564 goto error;
1565 }
1566
1567 dot = PyUnicode_FindChar(package, '.',
1568 0, PyUnicode_GET_LENGTH(package), -1);
1569 if (dot == -2) {
1570 goto error;
1571 }
1572
1573 if (dot >= 0) {
1574 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1575 if (substr == NULL) {
1576 goto error;
1577 }
1578 Py_SETREF(package, substr);
1579 }
1580 }
1581 }
1582
1583 last_dot = PyUnicode_GET_LENGTH(package);
1584 if (last_dot == 0) {
1585 PyErr_SetString(PyExc_ImportError,
1586 "attempted relative import with no known parent package");
1587 goto error;
1588 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001589
1590 for (level_up = 1; level_up < level; level_up += 1) {
1591 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1592 if (last_dot == -2) {
1593 goto error;
1594 }
1595 else if (last_dot == -1) {
1596 PyErr_SetString(PyExc_ValueError,
1597 "attempted relative import beyond top-level "
1598 "package");
1599 goto error;
1600 }
1601 }
1602
1603 base = PyUnicode_Substring(package, 0, last_dot);
1604 Py_DECREF(package);
1605 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1606 return base;
1607 }
1608
1609 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1610 Py_DECREF(base);
1611 return abs_name;
1612
1613 error:
1614 Py_XDECREF(package);
1615 return NULL;
1616}
1617
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001618static PyObject *
1619import_find_and_load(PyObject *abs_name)
1620{
1621 _Py_IDENTIFIER(_find_and_load);
1622 PyObject *mod = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001623 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001624 int import_time = interp->core_config.import_time;
1625 static int import_level;
1626 static _PyTime_t accumulated;
1627
1628 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1629
1630 /* XOptions is initialized after first some imports.
1631 * So we can't have negative cache before completed initialization.
1632 * Anyway, importlib._find_and_load is much slower than
1633 * _PyDict_GetItemIdWithError().
1634 */
1635 if (import_time) {
1636 static int header = 1;
1637 if (header) {
1638 fputs("import time: self [us] | cumulative | imported package\n",
1639 stderr);
1640 header = 0;
1641 }
1642
1643 import_level++;
1644 t1 = _PyTime_GetPerfCounter();
1645 accumulated = 0;
1646 }
1647
1648 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1649 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1650
1651 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1652 &PyId__find_and_load, abs_name,
1653 interp->import_func, NULL);
1654
1655 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1656 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1657 mod != NULL);
1658
1659 if (import_time) {
1660 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1661
1662 import_level--;
1663 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1664 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1665 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1666 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1667
1668 accumulated = accumulated_copy + cum;
1669 }
1670
1671 return mod;
1672}
1673
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001674PyObject *
1675PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1676 PyObject *locals, PyObject *fromlist,
1677 int level)
1678{
Brett Cannonfd074152012-04-14 14:10:13 -04001679 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001680 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001681 PyObject *final_mod = NULL;
1682 PyObject *mod = NULL;
1683 PyObject *package = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001684 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001685 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001686
Brett Cannonfd074152012-04-14 14:10:13 -04001687 if (name == NULL) {
1688 PyErr_SetString(PyExc_ValueError, "Empty module name");
1689 goto error;
1690 }
1691
1692 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1693 for added performance. */
1694
1695 if (!PyUnicode_Check(name)) {
1696 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1697 goto error;
1698 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001699 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001700 goto error;
1701 }
1702 if (level < 0) {
1703 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1704 goto error;
1705 }
Brett Cannon849113a2016-01-22 15:25:50 -08001706
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001707 if (level > 0) {
1708 abs_name = resolve_name(name, globals, level);
1709 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001710 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001711 }
1712 else { /* level == 0 */
1713 if (PyUnicode_GET_LENGTH(name) == 0) {
1714 PyErr_SetString(PyExc_ValueError, "Empty module name");
1715 goto error;
1716 }
Brett Cannonfd074152012-04-14 14:10:13 -04001717 abs_name = name;
1718 Py_INCREF(abs_name);
1719 }
1720
Eric Snow3f9eee62017-09-15 16:35:20 -06001721 mod = PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001722 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001723 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001724 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001725 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001726
Antoine Pitrou03989852012-08-28 00:24:52 +02001727 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001728 __spec__._initializing is true.
1729 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001730 stuffing the new module in sys.modules.
1731 */
Eric Snowb523f842013-11-22 09:05:39 -07001732 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001733 if (_PyModuleSpec_IsInitializing(spec)) {
1734 PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1735 &PyId__lock_unlock_module, abs_name,
1736 NULL);
1737 if (value == NULL) {
1738 Py_DECREF(spec);
1739 goto error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001740 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001741 Py_DECREF(value);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001742 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001743 Py_XDECREF(spec);
Brett Cannonfd074152012-04-14 14:10:13 -04001744 }
1745 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001746 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001747 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001748 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001749 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001750 }
1751 }
1752
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001753 has_from = 0;
1754 if (fromlist != NULL && fromlist != Py_None) {
1755 has_from = PyObject_IsTrue(fromlist);
1756 if (has_from < 0)
1757 goto error;
1758 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001759 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001760 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1761 if (level == 0 || len > 0) {
1762 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001763
Victor Stinner744c34e2016-05-20 11:36:13 +02001764 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1765 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001766 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001767 }
1768
Victor Stinner744c34e2016-05-20 11:36:13 +02001769 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001770 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001771 final_mod = mod;
1772 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001773 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001774 }
1775
Brett Cannonfd074152012-04-14 14:10:13 -04001776 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001777 PyObject *front = PyUnicode_Substring(name, 0, dot);
1778 if (front == NULL) {
1779 goto error;
1780 }
1781
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001782 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001783 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001784 }
1785 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001786 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001787 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001788 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001789 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001790 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001791 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001792 }
Brett Cannonfd074152012-04-14 14:10:13 -04001793
Eric Snow3f9eee62017-09-15 16:35:20 -06001794 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001795 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001796 if (final_mod == NULL) {
1797 PyErr_Format(PyExc_KeyError,
1798 "%R not in sys.modules as expected",
1799 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001800 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001801 }
Brett Cannonfd074152012-04-14 14:10:13 -04001802 }
1803 }
1804 else {
1805 final_mod = mod;
1806 Py_INCREF(mod);
1807 }
1808 }
1809 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001810 _Py_IDENTIFIER(__path__);
1811 PyObject *path;
1812 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1813 goto error;
1814 }
1815 if (path) {
1816 Py_DECREF(path);
1817 final_mod = _PyObject_CallMethodIdObjArgs(
1818 interp->importlib, &PyId__handle_fromlist,
1819 mod, fromlist, interp->import_func, NULL);
1820 }
1821 else {
1822 final_mod = mod;
1823 Py_INCREF(mod);
1824 }
Brett Cannonfd074152012-04-14 14:10:13 -04001825 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001826
Brett Cannonfd074152012-04-14 14:10:13 -04001827 error:
1828 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001829 Py_XDECREF(mod);
1830 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001831 if (final_mod == NULL)
1832 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001833 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001834}
1835
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001836PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001837PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001838 PyObject *fromlist, int level)
1839{
1840 PyObject *nameobj, *mod;
1841 nameobj = PyUnicode_FromString(name);
1842 if (nameobj == NULL)
1843 return NULL;
1844 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1845 fromlist, level);
1846 Py_DECREF(nameobj);
1847 return mod;
1848}
1849
1850
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001851/* Re-import a module of any kind and return its module object, WITH
1852 INCREMENTED REFERENCE COUNT */
1853
Guido van Rossum79f25d91997-04-29 20:08:16 +00001854PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001855PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001856{
Eric Snow3f9eee62017-09-15 16:35:20 -06001857 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001858 _Py_IDENTIFIER(reload);
1859 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001860 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001861 if (imp == NULL) {
1862 imp = PyImport_ImportModule("imp");
1863 if (imp == NULL) {
1864 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001867
Victor Stinner55ba38a2016-12-09 16:09:30 +01001868 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001869 Py_DECREF(imp);
1870 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001871}
1872
1873
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001874/* Higher-level import emulator which emulates the "import" statement
1875 more accurately -- it invokes the __import__() function from the
1876 builtins of the current globals. This means that the import is
1877 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001878 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001879 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001880 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001881 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001882
1883PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001884PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 static PyObject *silly_list = NULL;
1887 static PyObject *builtins_str = NULL;
1888 static PyObject *import_str = NULL;
1889 PyObject *globals = NULL;
1890 PyObject *import = NULL;
1891 PyObject *builtins = NULL;
1892 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* Initialize constant string objects */
1895 if (silly_list == NULL) {
1896 import_str = PyUnicode_InternFromString("__import__");
1897 if (import_str == NULL)
1898 return NULL;
1899 builtins_str = PyUnicode_InternFromString("__builtins__");
1900 if (builtins_str == NULL)
1901 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001902 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 if (silly_list == NULL)
1904 return NULL;
1905 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 /* Get the builtins from current globals */
1908 globals = PyEval_GetGlobals();
1909 if (globals != NULL) {
1910 Py_INCREF(globals);
1911 builtins = PyObject_GetItem(globals, builtins_str);
1912 if (builtins == NULL)
1913 goto err;
1914 }
1915 else {
1916 /* No globals -- use standard builtins, and fake globals */
1917 builtins = PyImport_ImportModuleLevel("builtins",
1918 NULL, NULL, NULL, 0);
1919 if (builtins == NULL)
1920 return NULL;
1921 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1922 if (globals == NULL)
1923 goto err;
1924 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 /* Get the __import__ function from the builtins */
1927 if (PyDict_Check(builtins)) {
1928 import = PyObject_GetItem(builtins, import_str);
1929 if (import == NULL)
1930 PyErr_SetObject(PyExc_KeyError, import_str);
1931 }
1932 else
1933 import = PyObject_GetAttr(builtins, import_str);
1934 if (import == NULL)
1935 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001938 Always use absolute import here.
1939 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1941 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001942 if (r == NULL)
1943 goto err;
1944 Py_DECREF(r);
1945
Eric Snow3f9eee62017-09-15 16:35:20 -06001946 r = PyImport_GetModule(module_name);
1947 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001948 PyErr_SetObject(PyExc_KeyError, module_name);
1949 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001950
1951 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 Py_XDECREF(globals);
1953 Py_XDECREF(builtins);
1954 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001957}
1958
Brett Cannon4caa61d2014-01-09 19:03:32 -05001959/*[clinic input]
1960_imp.extension_suffixes
1961
1962Returns the list of file suffixes used to identify extension modules.
1963[clinic start generated code]*/
1964
Brett Cannon4caa61d2014-01-09 19:03:32 -05001965static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001966_imp_extension_suffixes_impl(PyObject *module)
1967/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001970 const char *suffix;
1971 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 list = PyList_New(0);
1974 if (list == NULL)
1975 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001976#ifdef HAVE_DYNAMIC_LOADING
1977 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1978 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 if (item == NULL) {
1980 Py_DECREF(list);
1981 return NULL;
1982 }
1983 if (PyList_Append(list, item) < 0) {
1984 Py_DECREF(list);
1985 Py_DECREF(item);
1986 return NULL;
1987 }
1988 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001989 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 }
Brett Cannon2657df42012-05-04 15:20:40 -04001991#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001993}
1994
Brett Cannon4caa61d2014-01-09 19:03:32 -05001995/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001996_imp.init_frozen
1997
1998 name: unicode
1999 /
2000
2001Initializes a frozen module.
2002[clinic start generated code]*/
2003
Brett Cannon4caa61d2014-01-09 19:03:32 -05002004static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002005_imp_init_frozen_impl(PyObject *module, PyObject *name)
2006/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 int ret;
2009 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002010
Victor Stinner53dc7352011-03-20 01:50:21 +01002011 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (ret < 0)
2013 return NULL;
2014 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002015 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002017 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 Py_XINCREF(m);
2019 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002020}
2021
Brett Cannon4caa61d2014-01-09 19:03:32 -05002022/*[clinic input]
2023_imp.get_frozen_object
2024
2025 name: unicode
2026 /
2027
2028Create a code object for a frozen module.
2029[clinic start generated code]*/
2030
Brett Cannon4caa61d2014-01-09 19:03:32 -05002031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002032_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2033/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002036}
2037
Brett Cannon4caa61d2014-01-09 19:03:32 -05002038/*[clinic input]
2039_imp.is_frozen_package
2040
2041 name: unicode
2042 /
2043
2044Returns True if the module name is of a frozen package.
2045[clinic start generated code]*/
2046
Brett Cannon4caa61d2014-01-09 19:03:32 -05002047static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002048_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2049/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002052}
2053
Brett Cannon4caa61d2014-01-09 19:03:32 -05002054/*[clinic input]
2055_imp.is_builtin
2056
2057 name: unicode
2058 /
2059
2060Returns True if the module name corresponds to a built-in module.
2061[clinic start generated code]*/
2062
Guido van Rossum79f25d91997-04-29 20:08:16 +00002063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002064_imp_is_builtin_impl(PyObject *module, PyObject *name)
2065/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002066{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002067 return PyLong_FromLong(is_builtin(name));
2068}
2069
2070/*[clinic input]
2071_imp.is_frozen
2072
2073 name: unicode
2074 /
2075
2076Returns True if the module name corresponds to a frozen module.
2077[clinic start generated code]*/
2078
Brett Cannon4caa61d2014-01-09 19:03:32 -05002079static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002080_imp_is_frozen_impl(PyObject *module, PyObject *name)
2081/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002082{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002083 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 p = find_frozen(name);
2086 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002087}
2088
Larry Hastings1df0b352015-08-24 19:53:56 -07002089/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2090static int
2091exec_builtin_or_dynamic(PyObject *mod) {
2092 PyModuleDef *def;
2093 void *state;
2094
2095 if (!PyModule_Check(mod)) {
2096 return 0;
2097 }
2098
2099 def = PyModule_GetDef(mod);
2100 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002101 return 0;
2102 }
Brett Cannon52794db2016-09-07 17:00:43 -07002103
Larry Hastings1df0b352015-08-24 19:53:56 -07002104 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002105 if (state) {
2106 /* Already initialized; skip reload */
2107 return 0;
2108 }
Brett Cannon52794db2016-09-07 17:00:43 -07002109
Larry Hastings1df0b352015-08-24 19:53:56 -07002110 return PyModule_ExecDef(mod, def);
2111}
2112
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002113#ifdef HAVE_DYNAMIC_LOADING
2114
Brett Cannon4caa61d2014-01-09 19:03:32 -05002115/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002116_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002117
Nick Coghland5cacbb2015-05-23 22:24:10 +10002118 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002119 file: object = NULL
2120 /
2121
Nick Coghland5cacbb2015-05-23 22:24:10 +10002122Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002123[clinic start generated code]*/
2124
Brett Cannon4caa61d2014-01-09 19:03:32 -05002125static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002126_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2127/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002128{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002129 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002130 FILE *fp;
2131
Nick Coghland5cacbb2015-05-23 22:24:10 +10002132 name = PyObject_GetAttrString(spec, "name");
2133 if (name == NULL) {
2134 return NULL;
2135 }
2136
2137 path = PyObject_GetAttrString(spec, "origin");
2138 if (path == NULL) {
2139 Py_DECREF(name);
2140 return NULL;
2141 }
2142
2143 mod = _PyImport_FindExtensionObject(name, path);
2144 if (mod != NULL) {
2145 Py_DECREF(name);
2146 Py_DECREF(path);
2147 Py_INCREF(mod);
2148 return mod;
2149 }
2150
Brett Cannon4caa61d2014-01-09 19:03:32 -05002151 if (file != NULL) {
2152 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002153 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002154 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002155 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002157 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002159 else
2160 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002161
2162 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2163
2164 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002165 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (fp)
2167 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002168 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002169}
2170
Nick Coghland5cacbb2015-05-23 22:24:10 +10002171/*[clinic input]
2172_imp.exec_dynamic -> int
2173
2174 mod: object
2175 /
2176
2177Initialize an extension module.
2178[clinic start generated code]*/
2179
2180static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002181_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2182/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002183{
Larry Hastings1df0b352015-08-24 19:53:56 -07002184 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002185}
2186
2187
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002188#endif /* HAVE_DYNAMIC_LOADING */
2189
Larry Hastings7726ac92014-01-31 22:03:12 -08002190/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002191_imp.exec_builtin -> int
2192
2193 mod: object
2194 /
2195
2196Initialize a built-in module.
2197[clinic start generated code]*/
2198
2199static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002200_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2201/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002202{
2203 return exec_builtin_or_dynamic(mod);
2204}
2205
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002206/*[clinic input]
2207_imp.source_hash
2208
2209 key: long
2210 source: Py_buffer
2211[clinic start generated code]*/
2212
2213static PyObject *
2214_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2215/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2216{
Benjamin Peterson83620772017-12-09 12:18:56 -08002217 union {
2218 uint64_t x;
2219 char data[sizeof(uint64_t)];
2220 } hash;
2221 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002222#if !PY_LITTLE_ENDIAN
2223 // Force to little-endian. There really ought to be a succinct standard way
2224 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002225 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2226 char tmp = hash.data[i];
2227 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2228 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002229 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002230#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002231 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002232}
2233
Barry Warsaw28a691b2010-04-17 00:19:56 +00002234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002235PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002236"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002237
Guido van Rossum79f25d91997-04-29 20:08:16 +00002238static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002239 _IMP_EXTENSION_SUFFIXES_METHODDEF
2240 _IMP_LOCK_HELD_METHODDEF
2241 _IMP_ACQUIRE_LOCK_METHODDEF
2242 _IMP_RELEASE_LOCK_METHODDEF
2243 _IMP_GET_FROZEN_OBJECT_METHODDEF
2244 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002245 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002246 _IMP_INIT_FROZEN_METHODDEF
2247 _IMP_IS_BUILTIN_METHODDEF
2248 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002249 _IMP_CREATE_DYNAMIC_METHODDEF
2250 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002251 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002252 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002253 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002254 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002255};
2256
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002257
Martin v. Löwis1a214512008-06-11 05:26:20 +00002258static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002260 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 doc_imp,
2262 0,
2263 imp_methods,
2264 NULL,
2265 NULL,
2266 NULL,
2267 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002268};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002269
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002270PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002271PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 m = PyModule_Create(&impmodule);
2276 if (m == NULL)
2277 goto failure;
2278 d = PyModule_GetDict(m);
2279 if (d == NULL)
2280 goto failure;
Victor Stinnercaba55b2018-08-03 15:33:52 +02002281 _PyCoreConfig *config = &_PyInterpreterState_Get()->core_config;
Victor Stinner80b762f2018-08-01 18:18:07 +02002282 PyObject *pyc_mode = PyUnicode_FromString(config->_check_hash_pycs_mode);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002283 if (pyc_mode == NULL) {
2284 goto failure;
2285 }
2286 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2287 Py_DECREF(pyc_mode);
2288 goto failure;
2289 }
2290 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002293 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 Py_XDECREF(m);
2295 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002296}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002297
2298
Guido van Rossumb18618d2000-05-03 23:44:39 +00002299/* API for embedding applications that want to add their own entries
2300 to the table of built-in modules. This should normally be called
2301 *before* Py_Initialize(). When the table resize fails, -1 is
2302 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002303
2304 After a similar function by Just van Rossum. */
2305
2306int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002307PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002310 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002311 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Count the number of entries in both tables */
2314 for (n = 0; newtab[n].name != NULL; n++)
2315 ;
2316 if (n == 0)
2317 return 0; /* Nothing to do */
2318 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2319 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002320
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002321 /* Force default raw memory allocator to get a known allocator to be able
2322 to release the memory in _PyImport_Fini2() */
2323 PyMemAllocatorEx old_alloc;
2324 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002327 p = NULL;
2328 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002329 size_t size = sizeof(struct _inittab) * (i + n + 1);
2330 p = PyMem_RawRealloc(inittab_copy, size);
2331 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002332 if (p == NULL) {
2333 res = -1;
2334 goto done;
2335 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002336
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002337 /* Copy the tables into the new memory at the first call
2338 to PyImport_ExtendInittab(). */
2339 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002341 }
2342 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2343 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002344
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002345done:
2346 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2347 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002348}
2349
2350/* Shorthand to add a single entry given a name and a function */
2351
2352int
Brett Cannona826f322009-04-02 03:41:46 +00002353PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002358
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002359 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002363}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002364
2365#ifdef __cplusplus
2366}
2367#endif