blob: 6eb079d2a4715469e66c680b8619f436eefff60b [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"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner0a28f8d2019-06-19 02:54:39 +02007#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01008#include "pycore_pyhash.h"
9#include "pycore_pylifecycle.h"
10#include "pycore_pymem.h"
11#include "pycore_pystate.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020015#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000016#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000017#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020018#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000019
Guido van Rossum55a83382000-09-20 20:31:38 +000020#ifdef HAVE_FCNTL_H
21#include <fcntl.h>
22#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000024extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000026
Barry Warsaw28a691b2010-04-17 00:19:56 +000027#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000028
Victor Stinner0a28f8d2019-06-19 02:54:39 +020029/* Forward references */
30static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
31
Victor Stinner95872862011-03-07 18:20:56 +010032/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000033static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000034
Guido van Rossum771c6c81997-10-31 18:37:24 +000035/* This table is defined in config.c: */
36extern struct _inittab _PyImport_Inittab[];
37
38struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010039static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000040
Brett Cannon4caa61d2014-01-09 19:03:32 -050041/*[clinic input]
42module _imp
43[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030044/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040045
46#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050047
Guido van Rossum1ae940a1995-01-02 19:04:15 +000048/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049
Victor Stinner331a6a52019-05-27 16:39:22 +020050PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020051_PyImport_Init(PyThreadState *tstate)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Victor Stinnerb45d2592019-06-20 00:05:23 +020053 PyInterpreterState *interp = tstate->interp;
Serhiy Storchaka013bb912014-02-10 18:21:34 +020054 interp->builtins_copy = PyDict_Copy(interp->builtins);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080055 if (interp->builtins_copy == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020056 return _PyStatus_ERR("Can't backup builtins dict");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080057 }
Victor Stinner331a6a52019-05-27 16:39:22 +020058 return _PyStatus_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059}
60
Victor Stinner331a6a52019-05-27 16:39:22 +020061PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020062_PyImportHooks_Init(PyThreadState *tstate)
Just van Rossum52e14d62002-12-30 22:08:05 +000063{
Brett Cannonfd074152012-04-14 14:10:13 -040064 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000066
Brett Cannonfd074152012-04-14 14:10:13 -040067 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 v = PyList_New(0);
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("meta_path", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 v = PyDict_New();
76 if (v == NULL)
77 goto error;
78 err = PySys_SetObject("path_importer_cache", v);
79 Py_DECREF(v);
80 if (err)
81 goto error;
82 path_hooks = PyList_New(0);
83 if (path_hooks == NULL)
84 goto error;
85 err = PySys_SetObject("path_hooks", path_hooks);
86 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 }
Brett Cannonfd074152012-04-14 14:10:13 -040089 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020090 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091
92 error:
Victor Stinnerb45d2592019-06-20 00:05:23 +020093 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020094 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040096}
97
Victor Stinner331a6a52019-05-27 16:39:22 +020098PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020099_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -0400100{
ukwksk5e6312c2018-05-15 04:10:52 +0900101 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -0400102 int err = 0;
103
104 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200105 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200106 _PyErr_SetString(tstate, PyExc_RuntimeError,
107 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400108 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200109 }
Brett Cannonfd074152012-04-14 14:10:13 -0400110
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200111 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200112 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400113 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200114 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000115
ukwksk5e6312c2018-05-15 04:10:52 +0900116 zipimport = PyImport_ImportModule("zipimport");
117 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200118 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200119 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 }
123 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200124 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900125 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200126 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900127 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200129 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200130 if (verbose) {
131 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
132 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 }
134 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400135 /* sys.path_hooks.insert(0, zipimporter) */
136 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400138 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400140 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200141 if (verbose) {
142 PySys_WriteStderr("# installed zipimport hook\n");
143 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 }
145 }
Brett Cannonfd074152012-04-14 14:10:13 -0400146
Victor Stinner331a6a52019-05-27 16:39:22 +0200147 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400148
149 error:
150 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200151 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000152}
153
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154/* Locking primitives to prevent parallel imports of the same module
155 in different threads to return with a partially loaded module.
156 These calls are serialized by the global interpreter lock. */
157
Guido van Rossum49b56061998-10-01 20:42:43 +0000158#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000159
Guido van Rossum65d5b571998-12-21 19:32:43 +0000160static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200161static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000162static int import_lock_level = 0;
163
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000164void
165_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000166{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200167 unsigned long me = PyThread_get_thread_ident();
168 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 return; /* Too bad */
170 if (import_lock == NULL) {
171 import_lock = PyThread_allocate_lock();
172 if (import_lock == NULL)
173 return; /* Nothing much we can do. */
174 }
175 if (import_lock_thread == me) {
176 import_lock_level++;
177 return;
178 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200179 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
180 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 {
182 PyThreadState *tstate = PyEval_SaveThread();
183 PyThread_acquire_lock(import_lock, 1);
184 PyEval_RestoreThread(tstate);
185 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100186 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 import_lock_thread = me;
188 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000189}
190
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000191int
192_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000193{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200194 unsigned long me = PyThread_get_thread_ident();
195 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 return 0; /* Too bad */
197 if (import_lock_thread != me)
198 return -1;
199 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100200 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200202 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 PyThread_release_lock(import_lock);
204 }
205 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000206}
207
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200208/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000209 created child processes do not share locks with the parent.
210 We now acquire the import lock around fork() calls but on some platforms
211 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000212
213void
214_PyImport_ReInitLock(void)
215{
Christian Heimes418fd742015-04-19 21:08:42 +0200216 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200218 if (import_lock == NULL) {
219 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
220 }
221 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000222 if (import_lock_level > 1) {
223 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200224 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500225 /* The following could fail if the lock is already held, but forking as
226 a side-effect of an import is a) rare, b) nuts, and c) difficult to
227 do thanks to the lock only being held when doing individual module
228 locks per import. */
229 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000230 import_lock_thread = me;
231 import_lock_level--;
232 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200233 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000234 import_lock_level = 0;
235 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000236}
237
Brett Cannon4caa61d2014-01-09 19:03:32 -0500238/*[clinic input]
239_imp.lock_held
240
241Return True if the import lock is currently held, else False.
242
243On platforms without threads, return False.
244[clinic start generated code]*/
245
Brett Cannon4caa61d2014-01-09 19:03:32 -0500246static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300247_imp_lock_held_impl(PyObject *module)
248/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000249{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200250 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000251}
252
Brett Cannon4caa61d2014-01-09 19:03:32 -0500253/*[clinic input]
254_imp.acquire_lock
255
256Acquires the interpreter's import lock for the current thread.
257
258This lock should be used by import hooks to ensure thread-safety when importing
259modules. On platforms without threads, this function does nothing.
260[clinic start generated code]*/
261
Brett Cannon4caa61d2014-01-09 19:03:32 -0500262static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300263_imp_acquire_lock_impl(PyObject *module)
264/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200267 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000268}
269
Brett Cannon4caa61d2014-01-09 19:03:32 -0500270/*[clinic input]
271_imp.release_lock
272
273Release the interpreter's import lock.
274
275On platforms without threads, this function does nothing.
276[clinic start generated code]*/
277
Brett Cannon4caa61d2014-01-09 19:03:32 -0500278static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300279_imp_release_lock_impl(PyObject *module)
280/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 if (_PyImport_ReleaseLock() < 0) {
283 PyErr_SetString(PyExc_RuntimeError,
284 "not holding the import lock");
285 return NULL;
286 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200287 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000288}
289
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100290void
291_PyImport_Fini(void)
292{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200293 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100294 if (import_lock != NULL) {
295 PyThread_free_lock(import_lock);
296 import_lock = NULL;
297 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100298}
299
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100300void
301_PyImport_Fini2(void)
302{
303 /* Use the same memory allocator than PyImport_ExtendInittab(). */
304 PyMemAllocatorEx old_alloc;
305 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
306
307 /* Free memory allocated by PyImport_ExtendInittab() */
308 PyMem_RawFree(inittab_copy);
309
310 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
311}
312
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313/* Helper for sys */
314
315PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000316PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200318 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow3f9eee62017-09-15 16:35:20 -0600319 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700320 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600321 }
Eric Snow93c92f72017-09-13 23:46:04 -0700322 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323}
324
Eric Snowd393c1b2017-09-14 12:18:12 -0600325/* In some corner cases it is important to be sure that the import
326 machinery has been initialized (or not cleaned up yet). For
327 example, see issue #4236 and PyModule_Create2(). */
328
329int
330_PyImport_IsInitialized(PyInterpreterState *interp)
331{
332 if (interp->modules == NULL)
333 return 0;
334 return 1;
335}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000336
Eric Snow3f9eee62017-09-15 16:35:20 -0600337PyObject *
338_PyImport_GetModuleId(struct _Py_Identifier *nameid)
339{
340 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
341 if (name == NULL) {
342 return NULL;
343 }
344 return PyImport_GetModule(name);
345}
346
347int
348_PyImport_SetModule(PyObject *name, PyObject *m)
349{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200350 PyThreadState *tstate = _PyThreadState_GET();
351 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600352 return PyObject_SetItem(modules, name, m);
353}
354
355int
356_PyImport_SetModuleString(const char *name, PyObject *m)
357{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200358 PyThreadState *tstate = _PyThreadState_GET();
359 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600360 return PyMapping_SetItemString(modules, name, m);
361}
362
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200363static PyObject *
364import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600365{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200366 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600367 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200368 _PyErr_SetString(tstate, PyExc_RuntimeError,
369 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600370 return NULL;
371 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200372
373 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600374 Py_INCREF(modules);
375 if (PyDict_CheckExact(modules)) {
376 m = PyDict_GetItemWithError(modules, name); /* borrowed */
377 Py_XINCREF(m);
378 }
379 else {
380 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200381 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
382 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600383 }
384 }
385 Py_DECREF(modules);
386 return m;
387}
388
389
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100390static int
391import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200392{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100393 PyInterpreterState *interp = tstate->interp;
394 PyObject *spec;
395
396 _Py_IDENTIFIER(__spec__);
397 _Py_IDENTIFIER(_lock_unlock_module);
398
399 /* Optimization: only call _bootstrap._lock_unlock_module() if
400 __spec__._initializing is true.
401 NOTE: because of this, initializing must be set *before*
402 stuffing the new module in sys.modules.
403 */
404 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
405 int busy = _PyModuleSpec_IsInitializing(spec);
406 Py_XDECREF(spec);
407 if (busy) {
408 /* Wait until module is done importing. */
409 PyObject *value = _PyObject_CallMethodIdOneArg(
410 interp->importlib, &PyId__lock_unlock_module, name);
411 if (value == NULL) {
412 return -1;
413 }
414 Py_DECREF(value);
415 }
416 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200417}
418
419
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000420/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200421static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 "path", "argv", "ps1", "ps2",
423 "last_type", "last_value", "last_traceback",
424 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200425 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000427};
428
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200429static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 "stdin", "__stdin__",
431 "stdout", "__stdout__",
432 "stderr", "__stderr__",
433 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000434};
435
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000436/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000437
Guido van Rossum3f5da241990-12-20 15:06:42 +0000438void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200439_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000440{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200441 PyInterpreterState *interp = tstate->interp;
442 PyObject *modules = interp->modules;
443 if (modules == NULL) {
444 /* Already done */
445 return;
446 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 /* Delete some special variables first. These are common
449 places where user values hide and people complain when their
450 destructors fail. Since the modules containing them are
451 deleted *last* of all, they would come too late in the normal
452 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000453
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200454 /* XXX Perhaps these precautions are obsolete. Who knows? */
455
Victor Stinner331a6a52019-05-27 16:39:22 +0200456 int verbose = interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200457 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200458 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200459 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300460 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300461 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300462 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200463
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200464 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200465 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200466 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200467 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200468 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300469 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300470 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300471 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200473 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200474 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200475 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200476 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200477 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
478 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200479 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200480 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200481 PyErr_WriteUnraisable(NULL);
482 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200483 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200484 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300485 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300486 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300487 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000489
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200490 /* We prepare a list which will receive (name, weakref) tuples of
491 modules when they are removed from sys.modules. The name is used
492 for diagnosis messages (in verbose mode), while the weakref helps
493 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200494 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300495 if (weaklist == NULL) {
496 PyErr_WriteUnraisable(NULL);
497 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200498
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200499#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200500 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200501 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300502 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200503 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300504 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300505 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300506 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200507 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300508 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200509 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300510 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300511 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300512 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600514#define CLEAR_MODULE(name, mod) \
515 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200516 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600517 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200518 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600519 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300520 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300521 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300522 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600523 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000524
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200525 /* Remove all modules from sys.modules, hoping that garbage collection
526 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600527 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200528 Py_ssize_t pos = 0;
529 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600530 while (PyDict_Next(modules, &pos, &key, &value)) {
531 CLEAR_MODULE(key, value);
532 }
533 }
534 else {
535 PyObject *iterator = PyObject_GetIter(modules);
536 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300537 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600538 }
539 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200540 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600541 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200542 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600543 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300544 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600545 continue;
546 }
547 CLEAR_MODULE(key, value);
548 Py_DECREF(value);
549 Py_DECREF(key);
550 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300551 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300552 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300553 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600554 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 }
556 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000557
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200558 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600559 if (PyDict_CheckExact(modules)) {
560 PyDict_Clear(modules);
561 }
562 else {
563 _Py_IDENTIFIER(clear);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200564 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300565 PyErr_WriteUnraisable(NULL);
566 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600567 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200568 /* Restore the original builtins dict, to ensure that any
569 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200570 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300571 if (dict == NULL) {
572 PyErr_WriteUnraisable(NULL);
573 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200574 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300575 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200576 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300577 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200578 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200579 /* Clear module dict copies stored in the interpreter state */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200580 _PyInterpreterState_ClearModules(interp);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200581 /* Collect references */
582 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200583 /* Dump GC stats before it's too late, since it uses the warnings
584 machinery. */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200585 _PyGC_DumpShutdownStats(&_PyRuntime);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200586
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200587 /* Now, if there are any modules left alive, clear their globals to
588 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200589 up here, since they are kept alive in the interpreter state.
590
591 The special treatment of "builtins" here is because even
592 when it's not referenced as a module, its dictionary is
593 referenced by almost every module's __builtins__. Since
594 deleting a module clears its dictionary (even if there are
595 references left to it), we need to delete the "builtins"
596 module last. Likewise, we don't delete sys until the very
597 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200598 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200599 Py_ssize_t i;
600 /* Since dict is ordered in CPython 3.6+, modules are saved in
601 importing order. First clear modules imported later. */
602 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200603 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200604 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200605 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
606 if (mod == Py_None)
607 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200608 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200609 dict = PyModule_GetDict(mod);
610 if (dict == interp->builtins || dict == interp->sysdict)
611 continue;
612 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200613 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200614 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200615 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200616 _PyModule_Clear(mod);
617 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200618 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200619 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000621
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200622 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200623 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200624 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200625 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200626 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200627 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200628 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200629 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200630 _PyModule_ClearDict(interp->builtins);
631
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200632 /* Clear and delete the modules directory. Actual modules will
633 still be there only if imported during the execution of some
634 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700635 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200637
638 /* Once more */
639 _PyGC_CollectNoFail();
640
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300641#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200642#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000643}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000644
645
Barry Warsaw28a691b2010-04-17 00:19:56 +0000646/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000647
648long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000649PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000650{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200651 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200652 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600653 PyObject *external, *pyc_magic;
654
655 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
656 if (external == NULL)
657 return -1;
658 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
659 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400660 if (pyc_magic == NULL)
661 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200662 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700663 Py_DECREF(pyc_magic);
664 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000665}
666
667
Brett Cannon3adc7b72012-07-09 14:22:12 -0400668extern const char * _PySys_ImplCacheTag;
669
Barry Warsaw28a691b2010-04-17 00:19:56 +0000670const char *
671PyImport_GetMagicTag(void)
672{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400673 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000674}
675
Brett Cannon98979b82012-07-02 15:13:11 -0400676
Guido van Rossum25ce5661997-08-02 03:10:38 +0000677/* Magic for extension modules (built-in as well as dynamically
678 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200679 once, we keep a static dictionary 'extensions' keyed by the tuple
680 (module name, module name) (for built-in modules) or by
681 (filename, module name) (for dynamically loaded modules), containing these
682 modules. A copy of the module's dictionary is stored by calling
683 _PyImport_FixupExtensionObject() immediately after the module initialization
684 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100685 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000686
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000687 Modules which do support multiple initialization set their m_size
688 field to a non-negative number (indicating the size of the
689 module-specific state). They are still recorded in the extensions
690 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000691*/
692
693int
Victor Stinner95872862011-03-07 18:20:56 +0100694_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200695 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696{
Eric Snowd393c1b2017-09-14 12:18:12 -0600697 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500699 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (extensions == NULL) {
701 extensions = PyDict_New();
702 if (extensions == NULL)
703 return -1;
704 }
705 if (mod == NULL || !PyModule_Check(mod)) {
706 PyErr_BadInternalCall();
707 return -1;
708 }
709 def = PyModule_GetDef(mod);
710 if (!def) {
711 PyErr_BadInternalCall();
712 return -1;
713 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600714 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return -1;
716 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600717 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return -1;
719 }
720 if (def->m_size == -1) {
721 if (def->m_base.m_copy) {
722 /* Somebody already imported the module,
723 likely under a different name.
724 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200725 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 }
727 dict = PyModule_GetDict(mod);
728 if (dict == NULL)
729 return -1;
730 def->m_base.m_copy = PyDict_Copy(dict);
731 if (def->m_base.m_copy == NULL)
732 return -1;
733 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500734 key = PyTuple_Pack(2, filename, name);
735 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200736 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500737 res = PyDict_SetItem(extensions, key, (PyObject *)def);
738 Py_DECREF(key);
739 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200740 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000742}
743
Victor Stinner49d3f252010-10-17 01:24:53 +0000744int
Eric Snowd393c1b2017-09-14 12:18:12 -0600745_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000746{
747 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100748 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100749 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100750 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000751 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600752 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100753 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000754 return res;
755}
756
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200757static PyObject *
758import_find_extension(PyThreadState *tstate, PyObject *name,
759 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000760{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200761 if (extensions == NULL) {
762 return NULL;
763 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600764
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200765 PyObject *key = PyTuple_Pack(2, filename, name);
766 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200768 }
769 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500770 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200771 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200773 }
774
775 PyObject *mod, *mdict;
776 PyObject *modules = tstate->interp->modules;
777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (def->m_size == -1) {
779 /* Module does not support repeated initialization */
780 if (def->m_base.m_copy == NULL)
781 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200782 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (mod == NULL)
784 return NULL;
785 mdict = PyModule_GetDict(mod);
786 if (mdict == NULL)
787 return NULL;
788 if (PyDict_Update(mdict, def->m_base.m_copy))
789 return NULL;
790 }
791 else {
792 if (def->m_base.m_init == NULL)
793 return NULL;
794 mod = def->m_base.m_init();
795 if (mod == NULL)
796 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600797 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200798 Py_DECREF(mod);
799 return NULL;
800 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 Py_DECREF(mod);
802 }
803 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600804 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 return NULL;
806 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200807
808 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200809 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100810 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200811 name, filename);
812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000814}
815
Victor Stinner49d3f252010-10-17 01:24:53 +0000816PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200817_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
818{
819 PyThreadState *tstate = _PyThreadState_GET();
820 return import_find_extension(tstate, name, filename);
821}
822
823
824PyObject *
825_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000826{
Victor Stinner95872862011-03-07 18:20:56 +0100827 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100828 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100829 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000830 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200831 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100832 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000833 return res;
834}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835
836/* Get the module object corresponding to a module name.
837 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000838 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000839 Because the former action is most common, THIS DOES NOT RETURN A
840 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000841
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200842static PyObject *
843import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000844{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200845 PyObject *modules = tstate->interp->modules;
846 if (modules == NULL) {
847 _PyErr_SetString(tstate, PyExc_RuntimeError,
848 "no import module dictionary");
849 return NULL;
850 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600851
Eric Snow86b7afd2017-09-04 17:54:09 -0600852 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600853 if (PyDict_CheckExact(modules)) {
854 m = PyDict_GetItemWithError(modules, name);
855 }
856 else {
857 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000858 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600859 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200860 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
861 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600862 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200863 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200864 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200865 return NULL;
866 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600867 if (m != NULL && PyModule_Check(m)) {
868 return m;
869 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000870 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (m == NULL)
872 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600873 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 Py_DECREF(m);
875 return NULL;
876 }
877 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000880}
881
Victor Stinner27ee0892011-03-04 12:57:09 +0000882PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200883PyImport_AddModuleObject(PyObject *name)
884{
885 PyThreadState *tstate = _PyThreadState_GET();
886 return import_add_module(tstate, name);
887}
888
889
890PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000891PyImport_AddModule(const char *name)
892{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200893 PyObject *nameobj = PyUnicode_FromString(name);
894 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000895 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200896 }
897 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000898 Py_DECREF(nameobj);
899 return module;
900}
901
902
Tim Peters1cd70172004-08-02 03:52:12 +0000903/* Remove name from sys.modules, if it's there. */
904static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200905remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000906{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600907 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200908 _PyErr_Fetch(tstate, &type, &value, &traceback);
909
910 PyObject *modules = tstate->interp->modules;
Zackery Spytz94a64e92019-05-08 10:31:23 -0600911 if (!PyMapping_HasKey(modules, name)) {
912 goto out;
913 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600914 if (PyMapping_DelItem(modules, name) < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200915 _PyErr_SetString(tstate, PyExc_RuntimeError,
916 "deleting key in sys.modules failed");
917 _PyErr_ChainExceptions(type, value, traceback);
918 return;
Eric Snow3f9eee62017-09-15 16:35:20 -0600919 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200920
Zackery Spytz94a64e92019-05-08 10:31:23 -0600921out:
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200922 _PyErr_Restore(tstate, type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000923}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000924
Christian Heimes3b06e532008-01-07 20:12:44 +0000925
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000926/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000927 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
928 * removed from sys.modules, to avoid leaving damaged module objects
929 * in sys.modules. The caller may wish to restore the original
930 * module object (if any) in this case; PyImport_ReloadModule is an
931 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000932 *
933 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
934 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000935 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000936PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300937PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 return PyImport_ExecCodeModuleWithPathnames(
940 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000941}
942
943PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300944PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 return PyImport_ExecCodeModuleWithPathnames(
947 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000948}
949
950PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300951PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
952 const char *pathname,
953 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000954{
Victor Stinner27ee0892011-03-04 12:57:09 +0000955 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600956 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000957
958 nameobj = PyUnicode_FromString(name);
959 if (nameobj == NULL)
960 return NULL;
961
Victor Stinner27ee0892011-03-04 12:57:09 +0000962 if (cpathname != NULL) {
963 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
964 if (cpathobj == NULL)
965 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400966 }
967 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000968 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400969
970 if (pathname != NULL) {
971 pathobj = PyUnicode_DecodeFSDefault(pathname);
972 if (pathobj == NULL)
973 goto error;
974 }
975 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200976 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400977 _Py_IDENTIFIER(_get_sourcefile);
978
979 if (interp == NULL) {
980 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
981 "no interpreter!");
982 }
983
Eric Snow32439d62015-05-02 19:15:18 -0600984 external= PyObject_GetAttrString(interp->importlib,
985 "_bootstrap_external");
986 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200987 pathobj = _PyObject_CallMethodIdOneArg(
988 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600989 Py_DECREF(external);
990 }
Brett Cannona6473f92012-07-13 13:57:03 -0400991 if (pathobj == NULL)
992 PyErr_Clear();
993 }
994 else
995 pathobj = NULL;
996
Victor Stinner27ee0892011-03-04 12:57:09 +0000997 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
998error:
999 Py_DECREF(nameobj);
1000 Py_XDECREF(pathobj);
1001 Py_XDECREF(cpathobj);
1002 return m;
1003}
1004
Brett Cannon18fc4e72014-04-04 10:01:46 -04001005static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001006module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +00001007{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001008 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001009 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001010
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001011 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (m == NULL)
1013 return NULL;
1014 /* If the module is being reloaded, we get the old module back
1015 and re-use its dict to exec the new code. */
1016 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001017 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001018 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001019 _PyDict_SetItemId(d, &PyId___builtins__,
1020 PyEval_GetBuiltins()) != 0)
1021 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001022 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001023 return NULL;
1024 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001026
Eric Snow08197a42014-05-12 17:54:55 -06001027 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001028}
1029
1030static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001031exec_code_in_module(PyThreadState *tstate, PyObject *name,
1032 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001033{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001034 PyObject *v, *m;
1035
1036 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1037 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001038 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001039 return NULL;
1040 }
1041 Py_DECREF(v);
1042
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001043 m = import_get_module(tstate, name);
1044 if (m == NULL && !_PyErr_Occurred(tstate)) {
1045 _PyErr_Format(tstate, PyExc_ImportError,
1046 "Loaded module %R not found in sys.modules",
1047 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001048 }
1049
Brett Cannon18fc4e72014-04-04 10:01:46 -04001050 return m;
1051}
1052
1053PyObject*
1054PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1055 PyObject *cpathname)
1056{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001057 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001058 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001059 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001060
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001061 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001062 if (d == NULL) {
1063 return NULL;
1064 }
1065
Eric Snow08197a42014-05-12 17:54:55 -06001066 if (pathname == NULL) {
1067 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001069 external = PyObject_GetAttrString(tstate->interp->importlib,
1070 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001071 if (external == NULL)
1072 return NULL;
1073 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001074 &PyId__fix_up_module,
1075 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001076 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001077 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001078 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001079 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
Eric Snow08197a42014-05-12 17:54:55 -06001081 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001082}
1083
1084
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001085static void
1086update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyObject *constants, *tmp;
1089 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (PyUnicode_Compare(co->co_filename, oldname))
1092 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001093
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001094 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001095 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 constants = co->co_consts;
1098 n = PyTuple_GET_SIZE(constants);
1099 for (i = 0; i < n; i++) {
1100 tmp = PyTuple_GET_ITEM(constants, i);
1101 if (PyCode_Check(tmp))
1102 update_code_filenames((PyCodeObject *)tmp,
1103 oldname, newname);
1104 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001105}
1106
Victor Stinner2f42ae52011-03-20 00:41:24 +01001107static void
1108update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001109{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001110 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001111
Victor Stinner2f42ae52011-03-20 00:41:24 +01001112 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1113 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 oldname = co->co_filename;
1116 Py_INCREF(oldname);
1117 update_code_filenames(co, oldname, newname);
1118 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001119}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001120
Brett Cannon4caa61d2014-01-09 19:03:32 -05001121/*[clinic input]
1122_imp._fix_co_filename
1123
1124 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1125 Code object to change.
1126
1127 path: unicode
1128 File path to use.
1129 /
1130
1131Changes code.co_filename to specify the passed-in file path.
1132[clinic start generated code]*/
1133
Brett Cannon4caa61d2014-01-09 19:03:32 -05001134static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001135_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001136 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001137/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001138
Brett Cannon4caa61d2014-01-09 19:03:32 -05001139{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001140 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001141
1142 Py_RETURN_NONE;
1143}
1144
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001145
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001146/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001147static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001148
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001149
1150/* Helper to test for built-in module */
1151
1152static int
Victor Stinner95872862011-03-07 18:20:56 +01001153is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001154{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001155 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001157 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (PyImport_Inittab[i].initfunc == NULL)
1159 return -1;
1160 else
1161 return 1;
1162 }
1163 }
1164 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001165}
1166
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001167
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001168/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001169 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001170 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001171 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001172 this tells our caller that the path based finder could not find
1173 a finder for this path item. Cache the result in
1174 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001175 Returns a borrowed reference. */
1176
1177static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001178get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1179 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyObject *importer;
1182 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /* These conditions are the caller's responsibility: */
1185 assert(PyList_Check(path_hooks));
1186 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 nhooks = PyList_Size(path_hooks);
1189 if (nhooks < 0)
1190 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001191
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001192 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001193 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 /* set path_importer_cache[p] to None to avoid recursion */
1197 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1198 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 for (j = 0; j < nhooks; j++) {
1201 PyObject *hook = PyList_GetItem(path_hooks, j);
1202 if (hook == NULL)
1203 return NULL;
Jeroen Demeyer196a5302019-07-04 12:31:34 +02001204 importer = _PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (importer != NULL)
1206 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001207
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001208 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return NULL;
1210 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001211 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 }
1213 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001214 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
1216 if (importer != NULL) {
1217 int err = PyDict_SetItem(path_importer_cache, p, importer);
1218 Py_DECREF(importer);
1219 if (err != 0)
1220 return NULL;
1221 }
1222 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001223}
1224
Benjamin Petersone5024512018-09-12 12:06:42 -07001225PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001226PyImport_GetImporter(PyObject *path)
1227{
1228 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001230
Victor Stinner1e53bba2013-07-16 22:26:05 +02001231 path_importer_cache = PySys_GetObject("path_importer_cache");
1232 path_hooks = PySys_GetObject("path_hooks");
1233 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001234 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001235 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 }
1237 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1238 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001239}
1240
Nick Coghland5cacbb2015-05-23 22:24:10 +10001241/*[clinic input]
1242_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001243
Nick Coghland5cacbb2015-05-23 22:24:10 +10001244 spec: object
1245 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001246
Nick Coghland5cacbb2015-05-23 22:24:10 +10001247Create an extension module.
1248[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001249
Nick Coghland5cacbb2015-05-23 22:24:10 +10001250static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001251_imp_create_builtin(PyObject *module, PyObject *spec)
1252/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001253{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001254 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001256 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001257 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001258 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001259
Nick Coghland5cacbb2015-05-23 22:24:10 +10001260 name = PyObject_GetAttrString(spec, "name");
1261 if (name == NULL) {
1262 return NULL;
1263 }
1264
Victor Stinner5eb4f592013-11-14 22:38:52 +01001265 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001266 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001267 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001268 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001269 return mod;
1270 }
1271
1272 namestr = PyUnicode_AsUTF8(name);
1273 if (namestr == NULL) {
1274 Py_DECREF(name);
1275 return NULL;
1276 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001277
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001278 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001280 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001281 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001283 /* Cannot re-init internal module ("sys" or "builtins") */
1284 mod = PyImport_AddModule(namestr);
1285 Py_DECREF(name);
1286 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001289 if (mod == NULL) {
1290 Py_DECREF(name);
1291 return NULL;
1292 }
1293 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1294 Py_DECREF(name);
1295 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1296 } else {
1297 /* Remember pointer to module init function. */
1298 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001299 if (def == NULL) {
1300 Py_DECREF(name);
1301 return NULL;
1302 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001303 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001304 if (_PyImport_FixupExtensionObject(mod, name, name,
1305 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001306 Py_DECREF(name);
1307 return NULL;
1308 }
1309 Py_DECREF(name);
1310 return mod;
1311 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 }
1313 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001314 Py_DECREF(name);
1315 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001316}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001317
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001318
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001319/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001320
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001321static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001322find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001323{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001324 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001325
Victor Stinner53dc7352011-03-20 01:50:21 +01001326 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 for (p = PyImport_FrozenModules; ; p++) {
1330 if (p->name == NULL)
1331 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001332 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 break;
1334 }
1335 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001336}
1337
Guido van Rossum79f25d91997-04-29 20:08:16 +00001338static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001339get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001340{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001341 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (p == NULL) {
1345 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001346 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 name);
1348 return NULL;
1349 }
1350 if (p->code == NULL) {
1351 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001352 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 name);
1354 return NULL;
1355 }
1356 size = p->size;
1357 if (size < 0)
1358 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001359 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001360}
1361
Brett Cannon8d110132009-03-15 02:20:16 +00001362static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001363is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001364{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001365 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (p == NULL) {
1369 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001370 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 name);
1372 return NULL;
1373 }
Brett Cannon8d110132009-03-15 02:20:16 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 if (size < 0)
1378 Py_RETURN_TRUE;
1379 else
1380 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001381}
1382
1383
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001384/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001385 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001386 an exception set if the initialization failed.
1387 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001388
1389int
Victor Stinner53dc7352011-03-20 01:50:21 +01001390PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001391{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001392 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001393 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001394 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 int ispackage;
1396 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001397
Victor Stinner53dc7352011-03-20 01:50:21 +01001398 p = find_frozen(name);
1399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (p == NULL)
1401 return 0;
1402 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001403 _PyErr_Format(tstate, PyExc_ImportError,
1404 "Excluded frozen object named %R",
1405 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 return -1;
1407 }
1408 size = p->size;
1409 ispackage = (size < 0);
1410 if (ispackage)
1411 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001412 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (co == NULL)
1414 return -1;
1415 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001416 _PyErr_Format(tstate, PyExc_TypeError,
1417 "frozen object %R is not a code object",
1418 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 goto err_return;
1420 }
1421 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001422 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001423 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001425 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (m == NULL)
1427 goto err_return;
1428 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001429 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 goto err_return;
1432 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 err = PyDict_SetItemString(d, "__path__", l);
1434 Py_DECREF(l);
1435 if (err != 0)
1436 goto err_return;
1437 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001438 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001439 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001440 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001441 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001442 m = exec_code_in_module(tstate, name, d, co);
1443 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 Py_DECREF(co);
1447 Py_DECREF(m);
1448 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001449
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001450err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 Py_DECREF(co);
1452 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001453}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001454
Victor Stinner53dc7352011-03-20 01:50:21 +01001455int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001456PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001457{
1458 PyObject *nameobj;
1459 int ret;
1460 nameobj = PyUnicode_InternFromString(name);
1461 if (nameobj == NULL)
1462 return -1;
1463 ret = PyImport_ImportFrozenModuleObject(nameobj);
1464 Py_DECREF(nameobj);
1465 return ret;
1466}
1467
Guido van Rossum74e6a111994-08-29 12:54:38 +00001468
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001469/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001470 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001471
Guido van Rossum79f25d91997-04-29 20:08:16 +00001472PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001473PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 PyObject *pname;
1476 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 pname = PyUnicode_FromString(name);
1479 if (pname == NULL)
1480 return NULL;
1481 result = PyImport_Import(pname);
1482 Py_DECREF(pname);
1483 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001484}
1485
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001486
Christian Heimes072c0f12008-01-03 23:01:04 +00001487/* Import a module without blocking
1488 *
1489 * At first it tries to fetch the module from sys.modules. If the module was
1490 * never loaded before it loads it with PyImport_ImportModule() unless another
1491 * thread holds the import lock. In the latter case the function raises an
1492 * ImportError instead of blocking.
1493 *
1494 * Returns the module object with incremented ref count.
1495 */
1496PyObject *
1497PyImport_ImportModuleNoBlock(const char *name)
1498{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001499 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001500}
1501
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001502
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001503/* Remove importlib frames from the traceback,
1504 * except in Verbose mode. */
1505static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001506remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001507{
1508 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001509 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001510 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001511 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001512 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001513 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001514 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001515
1516 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001517 from the traceback. We always trim chunks
1518 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001519
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001520 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
1521 if (!exception || tstate->interp->config.verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001522 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001523 }
1524
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001525 if (PyType_IsSubtype((PyTypeObject *) exception,
1526 (PyTypeObject *) PyExc_ImportError))
1527 always_trim = 1;
1528
1529 prev_link = &base_tb;
1530 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001531 while (tb != NULL) {
1532 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1533 PyObject *next = (PyObject *) traceback->tb_next;
1534 PyFrameObject *frame = traceback->tb_frame;
1535 PyCodeObject *code = frame->f_code;
1536 int now_in_importlib;
1537
1538 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001539 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1540 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001541 if (now_in_importlib && !in_importlib) {
1542 /* This is the link to this chunk of importlib tracebacks */
1543 outer_link = prev_link;
1544 }
1545 in_importlib = now_in_importlib;
1546
1547 if (in_importlib &&
1548 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001549 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001550 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001551 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001552 prev_link = outer_link;
1553 }
1554 else {
1555 prev_link = (PyObject **) &traceback->tb_next;
1556 }
1557 tb = next;
1558 }
1559done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001560 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001561}
1562
1563
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001564static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001565resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001566{
Eric Snowb523f842013-11-22 09:05:39 -07001567 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001568 _Py_IDENTIFIER(__package__);
1569 _Py_IDENTIFIER(__path__);
1570 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001571 _Py_IDENTIFIER(parent);
1572 PyObject *abs_name;
1573 PyObject *package = NULL;
1574 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001575 Py_ssize_t last_dot;
1576 PyObject *base;
1577 int level_up;
1578
1579 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001580 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001581 goto error;
1582 }
1583 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001584 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001585 goto error;
1586 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001587 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001588 if (package == Py_None) {
1589 package = NULL;
1590 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001591 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001592 goto error;
1593 }
1594 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001595 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001596 goto error;
1597 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001598
1599 if (package != NULL) {
1600 Py_INCREF(package);
1601 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001602 _PyErr_SetString(tstate, PyExc_TypeError,
1603 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001604 goto error;
1605 }
1606 else if (spec != NULL && spec != Py_None) {
1607 int equal;
1608 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1609 if (parent == NULL) {
1610 goto error;
1611 }
1612
1613 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1614 Py_DECREF(parent);
1615 if (equal < 0) {
1616 goto error;
1617 }
1618 else if (equal == 0) {
1619 if (PyErr_WarnEx(PyExc_ImportWarning,
1620 "__package__ != __spec__.parent", 1) < 0) {
1621 goto error;
1622 }
1623 }
1624 }
1625 }
1626 else if (spec != NULL && spec != Py_None) {
1627 package = _PyObject_GetAttrId(spec, &PyId_parent);
1628 if (package == NULL) {
1629 goto error;
1630 }
1631 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001632 _PyErr_SetString(tstate, PyExc_TypeError,
1633 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001634 goto error;
1635 }
1636 }
1637 else {
1638 if (PyErr_WarnEx(PyExc_ImportWarning,
1639 "can't resolve package from __spec__ or __package__, "
1640 "falling back on __name__ and __path__", 1) < 0) {
1641 goto error;
1642 }
1643
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001644 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001645 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001646 if (!_PyErr_Occurred(tstate)) {
1647 _PyErr_SetString(tstate, PyExc_KeyError,
1648 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001649 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001650 goto error;
1651 }
1652
1653 Py_INCREF(package);
1654 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001655 _PyErr_SetString(tstate, PyExc_TypeError,
1656 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001657 goto error;
1658 }
1659
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001660 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001661 Py_ssize_t dot;
1662
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001663 if (_PyErr_Occurred(tstate) || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001664 goto error;
1665 }
1666
1667 dot = PyUnicode_FindChar(package, '.',
1668 0, PyUnicode_GET_LENGTH(package), -1);
1669 if (dot == -2) {
1670 goto error;
1671 }
Ben Lewis92420b32019-09-11 20:09:47 +10001672 else if (dot == -1) {
1673 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001674 }
Ben Lewis92420b32019-09-11 20:09:47 +10001675 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1676 if (substr == NULL) {
1677 goto error;
1678 }
1679 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001680 }
1681 }
1682
1683 last_dot = PyUnicode_GET_LENGTH(package);
1684 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001685 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001686 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001687
1688 for (level_up = 1; level_up < level; level_up += 1) {
1689 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1690 if (last_dot == -2) {
1691 goto error;
1692 }
1693 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001694 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001695 "attempted relative import beyond top-level "
1696 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001697 goto error;
1698 }
1699 }
1700
1701 base = PyUnicode_Substring(package, 0, last_dot);
1702 Py_DECREF(package);
1703 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1704 return base;
1705 }
1706
1707 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1708 Py_DECREF(base);
1709 return abs_name;
1710
Ben Lewis92420b32019-09-11 20:09:47 +10001711 no_parent_error:
1712 _PyErr_SetString(tstate, PyExc_ImportError,
1713 "attempted relative import "
1714 "with no known parent package");
1715
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001716 error:
1717 Py_XDECREF(package);
1718 return NULL;
1719}
1720
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001721static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001722import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001723{
1724 _Py_IDENTIFIER(_find_and_load);
1725 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001726 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +02001727 int import_time = interp->config.import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001728 static int import_level;
1729 static _PyTime_t accumulated;
1730
1731 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1732
Steve Dowerb82e17e2019-05-23 08:45:22 -07001733 PyObject *sys_path = PySys_GetObject("path");
1734 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1735 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1736 if (PySys_Audit("import", "OOOOO",
1737 abs_name, Py_None, sys_path ? sys_path : Py_None,
1738 sys_meta_path ? sys_meta_path : Py_None,
1739 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1740 return NULL;
1741 }
1742
1743
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001744 /* XOptions is initialized after first some imports.
1745 * So we can't have negative cache before completed initialization.
1746 * Anyway, importlib._find_and_load is much slower than
1747 * _PyDict_GetItemIdWithError().
1748 */
1749 if (import_time) {
1750 static int header = 1;
1751 if (header) {
1752 fputs("import time: self [us] | cumulative | imported package\n",
1753 stderr);
1754 header = 0;
1755 }
1756
1757 import_level++;
1758 t1 = _PyTime_GetPerfCounter();
1759 accumulated = 0;
1760 }
1761
1762 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1763 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1764
1765 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1766 &PyId__find_and_load, abs_name,
1767 interp->import_func, NULL);
1768
1769 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1770 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1771 mod != NULL);
1772
1773 if (import_time) {
1774 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1775
1776 import_level--;
1777 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1778 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1779 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1780 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1781
1782 accumulated = accumulated_copy + cum;
1783 }
1784
1785 return mod;
1786}
1787
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001788PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001789PyImport_GetModule(PyObject *name)
1790{
1791 PyThreadState *tstate = _PyThreadState_GET();
1792 PyObject *mod;
1793
1794 mod = import_get_module(tstate, name);
1795 if (mod != NULL && mod != Py_None) {
1796 if (import_ensure_initialized(tstate, mod, name) < 0) {
1797 Py_DECREF(mod);
1798 remove_importlib_frames(tstate);
1799 return NULL;
1800 }
1801 }
1802 return mod;
1803}
1804
1805PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001806PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1807 PyObject *locals, PyObject *fromlist,
1808 int level)
1809{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001810 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001811 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001812 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001813 PyObject *final_mod = NULL;
1814 PyObject *mod = NULL;
1815 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001816 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001817 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001818
Brett Cannonfd074152012-04-14 14:10:13 -04001819 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001820 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001821 goto error;
1822 }
1823
1824 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1825 for added performance. */
1826
1827 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001828 _PyErr_SetString(tstate, PyExc_TypeError,
1829 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001830 goto error;
1831 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001832 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001833 goto error;
1834 }
1835 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001836 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001837 goto error;
1838 }
Brett Cannon849113a2016-01-22 15:25:50 -08001839
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001840 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001841 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001842 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001843 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001844 }
1845 else { /* level == 0 */
1846 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001847 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001848 goto error;
1849 }
Brett Cannonfd074152012-04-14 14:10:13 -04001850 abs_name = name;
1851 Py_INCREF(abs_name);
1852 }
1853
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001854 mod = import_get_module(tstate, abs_name);
1855 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001856 goto error;
1857 }
1858
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001859 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001860 if (import_ensure_initialized(tstate, mod, name) < 0) {
1861 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001862 }
Brett Cannonfd074152012-04-14 14:10:13 -04001863 }
1864 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001865 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001866 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001867 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001868 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001869 }
1870 }
1871
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001872 has_from = 0;
1873 if (fromlist != NULL && fromlist != Py_None) {
1874 has_from = PyObject_IsTrue(fromlist);
1875 if (has_from < 0)
1876 goto error;
1877 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001878 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001879 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1880 if (level == 0 || len > 0) {
1881 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001882
Victor Stinner744c34e2016-05-20 11:36:13 +02001883 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1884 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001885 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001886 }
1887
Victor Stinner744c34e2016-05-20 11:36:13 +02001888 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001889 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001890 final_mod = mod;
1891 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001892 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001893 }
1894
Brett Cannonfd074152012-04-14 14:10:13 -04001895 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001896 PyObject *front = PyUnicode_Substring(name, 0, dot);
1897 if (front == NULL) {
1898 goto error;
1899 }
1900
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001901 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001902 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001903 }
1904 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001905 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001906 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001907 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001908 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001909 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001910 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001911 }
Brett Cannonfd074152012-04-14 14:10:13 -04001912
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001913 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001914 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001915 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001916 if (!_PyErr_Occurred(tstate)) {
1917 _PyErr_Format(tstate, PyExc_KeyError,
1918 "%R not in sys.modules as expected",
1919 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001920 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001921 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001922 }
Brett Cannonfd074152012-04-14 14:10:13 -04001923 }
1924 }
1925 else {
1926 final_mod = mod;
1927 Py_INCREF(mod);
1928 }
1929 }
1930 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001931 _Py_IDENTIFIER(__path__);
1932 PyObject *path;
1933 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1934 goto error;
1935 }
1936 if (path) {
1937 Py_DECREF(path);
1938 final_mod = _PyObject_CallMethodIdObjArgs(
1939 interp->importlib, &PyId__handle_fromlist,
1940 mod, fromlist, interp->import_func, NULL);
1941 }
1942 else {
1943 final_mod = mod;
1944 Py_INCREF(mod);
1945 }
Brett Cannonfd074152012-04-14 14:10:13 -04001946 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001947
Brett Cannonfd074152012-04-14 14:10:13 -04001948 error:
1949 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001950 Py_XDECREF(mod);
1951 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001952 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001953 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001954 }
Brett Cannonfd074152012-04-14 14:10:13 -04001955 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001956}
1957
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001958PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001959PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001960 PyObject *fromlist, int level)
1961{
1962 PyObject *nameobj, *mod;
1963 nameobj = PyUnicode_FromString(name);
1964 if (nameobj == NULL)
1965 return NULL;
1966 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1967 fromlist, level);
1968 Py_DECREF(nameobj);
1969 return mod;
1970}
1971
1972
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001973/* Re-import a module of any kind and return its module object, WITH
1974 INCREMENTED REFERENCE COUNT */
1975
Guido van Rossum79f25d91997-04-29 20:08:16 +00001976PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001977PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001978{
Eric Snow3f9eee62017-09-15 16:35:20 -06001979 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001980 _Py_IDENTIFIER(reload);
1981 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001982 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001983 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001984 if (PyErr_Occurred()) {
1985 return NULL;
1986 }
1987
Brett Cannon62228db2012-04-29 14:38:11 -04001988 imp = PyImport_ImportModule("imp");
1989 if (imp == NULL) {
1990 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001993
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001994 reloaded_module = _PyObject_CallMethodIdOneArg(imp, &PyId_reload, m);
Brett Cannon62228db2012-04-29 14:38:11 -04001995 Py_DECREF(imp);
1996 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001997}
1998
1999
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002000/* Higher-level import emulator which emulates the "import" statement
2001 more accurately -- it invokes the __import__() function from the
2002 builtins of the current globals. This means that the import is
2003 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002004 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002005 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002006 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002007 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002008
2009PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002010PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002011{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002012 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 static PyObject *silly_list = NULL;
2014 static PyObject *builtins_str = NULL;
2015 static PyObject *import_str = NULL;
2016 PyObject *globals = NULL;
2017 PyObject *import = NULL;
2018 PyObject *builtins = NULL;
2019 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Initialize constant string objects */
2022 if (silly_list == NULL) {
2023 import_str = PyUnicode_InternFromString("__import__");
2024 if (import_str == NULL)
2025 return NULL;
2026 builtins_str = PyUnicode_InternFromString("__builtins__");
2027 if (builtins_str == NULL)
2028 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002029 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (silly_list == NULL)
2031 return NULL;
2032 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 /* Get the builtins from current globals */
2035 globals = PyEval_GetGlobals();
2036 if (globals != NULL) {
2037 Py_INCREF(globals);
2038 builtins = PyObject_GetItem(globals, builtins_str);
2039 if (builtins == NULL)
2040 goto err;
2041 }
2042 else {
2043 /* No globals -- use standard builtins, and fake globals */
2044 builtins = PyImport_ImportModuleLevel("builtins",
2045 NULL, NULL, NULL, 0);
2046 if (builtins == NULL)
2047 return NULL;
2048 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2049 if (globals == NULL)
2050 goto err;
2051 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 /* Get the __import__ function from the builtins */
2054 if (PyDict_Check(builtins)) {
2055 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002056 if (import == NULL) {
2057 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2058 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
2060 else
2061 import = PyObject_GetAttr(builtins, import_str);
2062 if (import == NULL)
2063 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002066 Always use absolute import here.
2067 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2069 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002070 if (r == NULL)
2071 goto err;
2072 Py_DECREF(r);
2073
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002074 r = import_get_module(tstate, module_name);
2075 if (r == NULL && !_PyErr_Occurred(tstate)) {
2076 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002077 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002078
2079 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 Py_XDECREF(globals);
2081 Py_XDECREF(builtins);
2082 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002085}
2086
Brett Cannon4caa61d2014-01-09 19:03:32 -05002087/*[clinic input]
2088_imp.extension_suffixes
2089
2090Returns the list of file suffixes used to identify extension modules.
2091[clinic start generated code]*/
2092
Brett Cannon4caa61d2014-01-09 19:03:32 -05002093static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002094_imp_extension_suffixes_impl(PyObject *module)
2095/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 list = PyList_New(0);
2100 if (list == NULL)
2101 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002102#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002103 const char *suffix;
2104 unsigned int index = 0;
2105
Brett Cannon2657df42012-05-04 15:20:40 -04002106 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2107 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (item == NULL) {
2109 Py_DECREF(list);
2110 return NULL;
2111 }
2112 if (PyList_Append(list, item) < 0) {
2113 Py_DECREF(list);
2114 Py_DECREF(item);
2115 return NULL;
2116 }
2117 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002118 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
Brett Cannon2657df42012-05-04 15:20:40 -04002120#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002122}
2123
Brett Cannon4caa61d2014-01-09 19:03:32 -05002124/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002125_imp.init_frozen
2126
2127 name: unicode
2128 /
2129
2130Initializes a frozen module.
2131[clinic start generated code]*/
2132
Brett Cannon4caa61d2014-01-09 19:03:32 -05002133static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002134_imp_init_frozen_impl(PyObject *module, PyObject *name)
2135/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002136{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002137 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 int ret;
2139 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002140
Victor Stinner53dc7352011-03-20 01:50:21 +01002141 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (ret < 0)
2143 return NULL;
2144 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002145 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002147 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 Py_XINCREF(m);
2149 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002150}
2151
Brett Cannon4caa61d2014-01-09 19:03:32 -05002152/*[clinic input]
2153_imp.get_frozen_object
2154
2155 name: unicode
2156 /
2157
2158Create a code object for a frozen module.
2159[clinic start generated code]*/
2160
Brett Cannon4caa61d2014-01-09 19:03:32 -05002161static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002162_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2163/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002166}
2167
Brett Cannon4caa61d2014-01-09 19:03:32 -05002168/*[clinic input]
2169_imp.is_frozen_package
2170
2171 name: unicode
2172 /
2173
2174Returns True if the module name is of a frozen package.
2175[clinic start generated code]*/
2176
Brett Cannon4caa61d2014-01-09 19:03:32 -05002177static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002178_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2179/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002182}
2183
Brett Cannon4caa61d2014-01-09 19:03:32 -05002184/*[clinic input]
2185_imp.is_builtin
2186
2187 name: unicode
2188 /
2189
2190Returns True if the module name corresponds to a built-in module.
2191[clinic start generated code]*/
2192
Guido van Rossum79f25d91997-04-29 20:08:16 +00002193static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002194_imp_is_builtin_impl(PyObject *module, PyObject *name)
2195/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002196{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002197 return PyLong_FromLong(is_builtin(name));
2198}
2199
2200/*[clinic input]
2201_imp.is_frozen
2202
2203 name: unicode
2204 /
2205
2206Returns True if the module name corresponds to a frozen module.
2207[clinic start generated code]*/
2208
Brett Cannon4caa61d2014-01-09 19:03:32 -05002209static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002210_imp_is_frozen_impl(PyObject *module, PyObject *name)
2211/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002212{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002213 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 p = find_frozen(name);
2216 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002217}
2218
Larry Hastings1df0b352015-08-24 19:53:56 -07002219/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2220static int
2221exec_builtin_or_dynamic(PyObject *mod) {
2222 PyModuleDef *def;
2223 void *state;
2224
2225 if (!PyModule_Check(mod)) {
2226 return 0;
2227 }
2228
2229 def = PyModule_GetDef(mod);
2230 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002231 return 0;
2232 }
Brett Cannon52794db2016-09-07 17:00:43 -07002233
Larry Hastings1df0b352015-08-24 19:53:56 -07002234 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002235 if (state) {
2236 /* Already initialized; skip reload */
2237 return 0;
2238 }
Brett Cannon52794db2016-09-07 17:00:43 -07002239
Larry Hastings1df0b352015-08-24 19:53:56 -07002240 return PyModule_ExecDef(mod, def);
2241}
2242
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002243#ifdef HAVE_DYNAMIC_LOADING
2244
Brett Cannon4caa61d2014-01-09 19:03:32 -05002245/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002246_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002247
Nick Coghland5cacbb2015-05-23 22:24:10 +10002248 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002249 file: object = NULL
2250 /
2251
Nick Coghland5cacbb2015-05-23 22:24:10 +10002252Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002253[clinic start generated code]*/
2254
Brett Cannon4caa61d2014-01-09 19:03:32 -05002255static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002256_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2257/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002258{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002259 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002260 FILE *fp;
2261
Nick Coghland5cacbb2015-05-23 22:24:10 +10002262 name = PyObject_GetAttrString(spec, "name");
2263 if (name == NULL) {
2264 return NULL;
2265 }
2266
2267 path = PyObject_GetAttrString(spec, "origin");
2268 if (path == NULL) {
2269 Py_DECREF(name);
2270 return NULL;
2271 }
2272
2273 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002274 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002275 Py_DECREF(name);
2276 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002277 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002278 return mod;
2279 }
2280
Brett Cannon4caa61d2014-01-09 19:03:32 -05002281 if (file != NULL) {
2282 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002283 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002284 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002285 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002287 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002289 else
2290 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002291
2292 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2293
2294 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002295 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 if (fp)
2297 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002298 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002299}
2300
Nick Coghland5cacbb2015-05-23 22:24:10 +10002301/*[clinic input]
2302_imp.exec_dynamic -> int
2303
2304 mod: object
2305 /
2306
2307Initialize an extension module.
2308[clinic start generated code]*/
2309
2310static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002311_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2312/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002313{
Larry Hastings1df0b352015-08-24 19:53:56 -07002314 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002315}
2316
2317
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002318#endif /* HAVE_DYNAMIC_LOADING */
2319
Larry Hastings7726ac92014-01-31 22:03:12 -08002320/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002321_imp.exec_builtin -> int
2322
2323 mod: object
2324 /
2325
2326Initialize a built-in module.
2327[clinic start generated code]*/
2328
2329static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002330_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2331/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002332{
2333 return exec_builtin_or_dynamic(mod);
2334}
2335
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002336/*[clinic input]
2337_imp.source_hash
2338
2339 key: long
2340 source: Py_buffer
2341[clinic start generated code]*/
2342
2343static PyObject *
2344_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2345/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2346{
Benjamin Peterson83620772017-12-09 12:18:56 -08002347 union {
2348 uint64_t x;
2349 char data[sizeof(uint64_t)];
2350 } hash;
2351 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002352#if !PY_LITTLE_ENDIAN
2353 // Force to little-endian. There really ought to be a succinct standard way
2354 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002355 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2356 char tmp = hash.data[i];
2357 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2358 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002359 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002360#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002361 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002362}
2363
Barry Warsaw28a691b2010-04-17 00:19:56 +00002364
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002365PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002366"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002367
Guido van Rossum79f25d91997-04-29 20:08:16 +00002368static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002369 _IMP_EXTENSION_SUFFIXES_METHODDEF
2370 _IMP_LOCK_HELD_METHODDEF
2371 _IMP_ACQUIRE_LOCK_METHODDEF
2372 _IMP_RELEASE_LOCK_METHODDEF
2373 _IMP_GET_FROZEN_OBJECT_METHODDEF
2374 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002375 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002376 _IMP_INIT_FROZEN_METHODDEF
2377 _IMP_IS_BUILTIN_METHODDEF
2378 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002379 _IMP_CREATE_DYNAMIC_METHODDEF
2380 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002381 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002382 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002383 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002384 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002385};
2386
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002387
Martin v. Löwis1a214512008-06-11 05:26:20 +00002388static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002390 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 doc_imp,
2392 0,
2393 imp_methods,
2394 NULL,
2395 NULL,
2396 NULL,
2397 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002398};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002399
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002400PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002401PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002406 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002410 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002412 }
2413
Victor Stinner331a6a52019-05-27 16:39:22 +02002414 const wchar_t *mode = _PyInterpreterState_Get()->config.check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002415 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002416 if (pyc_mode == NULL) {
2417 goto failure;
2418 }
2419 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2420 Py_DECREF(pyc_mode);
2421 goto failure;
2422 }
2423 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002426 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 Py_XDECREF(m);
2428 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002429}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002430
2431
Guido van Rossumb18618d2000-05-03 23:44:39 +00002432/* API for embedding applications that want to add their own entries
2433 to the table of built-in modules. This should normally be called
2434 *before* Py_Initialize(). When the table resize fails, -1 is
2435 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002436
2437 After a similar function by Just van Rossum. */
2438
2439int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002440PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002443 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002444 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* Count the number of entries in both tables */
2447 for (n = 0; newtab[n].name != NULL; n++)
2448 ;
2449 if (n == 0)
2450 return 0; /* Nothing to do */
2451 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2452 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002453
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002454 /* Force default raw memory allocator to get a known allocator to be able
2455 to release the memory in _PyImport_Fini2() */
2456 PyMemAllocatorEx old_alloc;
2457 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002460 p = NULL;
2461 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002462 size_t size = sizeof(struct _inittab) * (i + n + 1);
2463 p = PyMem_RawRealloc(inittab_copy, size);
2464 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002465 if (p == NULL) {
2466 res = -1;
2467 goto done;
2468 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002469
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002470 /* Copy the tables into the new memory at the first call
2471 to PyImport_ExtendInittab(). */
2472 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002474 }
2475 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2476 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002477
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002478done:
2479 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2480 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002481}
2482
2483/* Shorthand to add a single entry given a name and a function */
2484
2485int
Brett Cannona826f322009-04-02 03:41:46 +00002486PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002491
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002492 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002496}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002497
2498#ifdef __cplusplus
2499}
2500#endif