blob: 505688400ef3e3a04dc72a46bc6a811b29f4f337 [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 Stinner61691d82019-10-02 23:51:20 +02007#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02008#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pyhash.h"
10#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020011#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020012#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
13#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010014#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000018#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020019#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000020
Guido van Rossum55a83382000-09-20 20:31:38 +000021#ifdef HAVE_FCNTL_H
22#include <fcntl.h>
23#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000025extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000027
Barry Warsaw28a691b2010-04-17 00:19:56 +000028#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000029
Victor Stinner0a28f8d2019-06-19 02:54:39 +020030/* Forward references */
31static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
32
Victor Stinner95872862011-03-07 18:20:56 +010033/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000034static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000035
Guido van Rossum771c6c81997-10-31 18:37:24 +000036/* This table is defined in config.c: */
37extern struct _inittab _PyImport_Inittab[];
38
39struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010040static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000041
Hai Shi46874c22020-01-30 17:20:25 -060042_Py_IDENTIFIER(__path__);
43_Py_IDENTIFIER(__spec__);
44
Brett Cannon4caa61d2014-01-09 19:03:32 -050045/*[clinic input]
46module _imp
47[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030048/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040049
50#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050051
Guido van Rossum1ae940a1995-01-02 19:04:15 +000052/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053
Victor Stinner331a6a52019-05-27 16:39:22 +020054PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020055_PyImportHooks_Init(PyThreadState *tstate)
Just van Rossum52e14d62002-12-30 22:08:05 +000056{
Brett Cannonfd074152012-04-14 14:10:13 -040057 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000059
Brett Cannonfd074152012-04-14 14:10:13 -040060 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 v = PyList_New(0);
62 if (v == NULL)
63 goto error;
64 err = PySys_SetObject("meta_path", v);
65 Py_DECREF(v);
66 if (err)
67 goto error;
68 v = PyDict_New();
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("path_importer_cache", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 path_hooks = PyList_New(0);
76 if (path_hooks == NULL)
77 goto error;
78 err = PySys_SetObject("path_hooks", path_hooks);
79 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 }
Brett Cannonfd074152012-04-14 14:10:13 -040082 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020083 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084
85 error:
Victor Stinnerb45d2592019-06-20 00:05:23 +020086 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020087 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080088 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040089}
90
Victor Stinner331a6a52019-05-27 16:39:22 +020091PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020092_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040093{
ukwksk5e6312c2018-05-15 04:10:52 +090094 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040095 int err = 0;
96
97 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020098 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020099 _PyErr_SetString(tstate, PyExc_RuntimeError,
100 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400101 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200102 }
Brett Cannonfd074152012-04-14 14:10:13 -0400103
Victor Stinnerda7933e2020-04-13 03:04:28 +0200104 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200105 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400106 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200107 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108
ukwksk5e6312c2018-05-15 04:10:52 +0900109 zipimport = PyImport_ImportModule("zipimport");
110 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200111 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200112 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 }
116 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200117 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900118 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200119 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900120 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200122 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200123 if (verbose) {
124 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
127 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400128 /* sys.path_hooks.insert(0, zipimporter) */
129 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400131 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400133 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200134 if (verbose) {
135 PySys_WriteStderr("# installed zipimport hook\n");
136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 }
138 }
Brett Cannonfd074152012-04-14 14:10:13 -0400139
Victor Stinner331a6a52019-05-27 16:39:22 +0200140 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400141
142 error:
143 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200144 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000145}
146
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147/* Locking primitives to prevent parallel imports of the same module
148 in different threads to return with a partially loaded module.
149 These calls are serialized by the global interpreter lock. */
150
Victor Stinner26881c82020-06-02 15:51:37 +0200151static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200152static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153static int import_lock_level = 0;
154
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000155void
156_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000157{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200158 unsigned long me = PyThread_get_thread_ident();
159 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 return; /* Too bad */
161 if (import_lock == NULL) {
162 import_lock = PyThread_allocate_lock();
163 if (import_lock == NULL)
164 return; /* Nothing much we can do. */
165 }
166 if (import_lock_thread == me) {
167 import_lock_level++;
168 return;
169 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200170 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
171 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 {
173 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200174 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyEval_RestoreThread(tstate);
176 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100177 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 import_lock_thread = me;
179 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000180}
181
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000182int
183_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000184{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200185 unsigned long me = PyThread_get_thread_ident();
186 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return 0; /* Too bad */
188 if (import_lock_thread != me)
189 return -1;
190 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100191 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200193 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyThread_release_lock(import_lock);
195 }
196 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000197}
198
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900199#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200200/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000201 created child processes do not share locks with the parent.
202 We now acquire the import lock around fork() calls but on some platforms
203 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200204PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000205_PyImport_ReInitLock(void)
206{
Christian Heimes418fd742015-04-19 21:08:42 +0200207 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900208 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200209 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200210 }
211 }
Victor Stinner26881c82020-06-02 15:51:37 +0200212
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000213 if (import_lock_level > 1) {
214 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200215 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200216 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000217 import_lock_thread = me;
218 import_lock_level--;
219 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200220 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000221 import_lock_level = 0;
222 }
Victor Stinner26881c82020-06-02 15:51:37 +0200223 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000224}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900225#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000226
Brett Cannon4caa61d2014-01-09 19:03:32 -0500227/*[clinic input]
228_imp.lock_held
229
230Return True if the import lock is currently held, else False.
231
232On platforms without threads, return False.
233[clinic start generated code]*/
234
Brett Cannon4caa61d2014-01-09 19:03:32 -0500235static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300236_imp_lock_held_impl(PyObject *module)
237/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000238{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200239 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000240}
241
Brett Cannon4caa61d2014-01-09 19:03:32 -0500242/*[clinic input]
243_imp.acquire_lock
244
245Acquires the interpreter's import lock for the current thread.
246
247This lock should be used by import hooks to ensure thread-safety when importing
248modules. On platforms without threads, this function does nothing.
249[clinic start generated code]*/
250
Brett Cannon4caa61d2014-01-09 19:03:32 -0500251static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300252_imp_acquire_lock_impl(PyObject *module)
253/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200256 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000257}
258
Brett Cannon4caa61d2014-01-09 19:03:32 -0500259/*[clinic input]
260_imp.release_lock
261
262Release the interpreter's import lock.
263
264On platforms without threads, this function does nothing.
265[clinic start generated code]*/
266
Brett Cannon4caa61d2014-01-09 19:03:32 -0500267static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300268_imp_release_lock_impl(PyObject *module)
269/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (_PyImport_ReleaseLock() < 0) {
272 PyErr_SetString(PyExc_RuntimeError,
273 "not holding the import lock");
274 return NULL;
275 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200276 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000277}
278
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100279void
280_PyImport_Fini(void)
281{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200282 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100283 if (import_lock != NULL) {
284 PyThread_free_lock(import_lock);
285 import_lock = NULL;
286 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100287}
288
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100289void
290_PyImport_Fini2(void)
291{
292 /* Use the same memory allocator than PyImport_ExtendInittab(). */
293 PyMemAllocatorEx old_alloc;
294 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
295
296 /* Free memory allocated by PyImport_ExtendInittab() */
297 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700298 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100299
300 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
301}
302
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303/* Helper for sys */
304
305PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000306PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307{
Victor Stinner81a7be32020-04-14 15:14:01 +0200308 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600309 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100310 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600311 }
Eric Snow93c92f72017-09-13 23:46:04 -0700312 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313}
314
Eric Snowd393c1b2017-09-14 12:18:12 -0600315/* In some corner cases it is important to be sure that the import
316 machinery has been initialized (or not cleaned up yet). For
317 example, see issue #4236 and PyModule_Create2(). */
318
319int
320_PyImport_IsInitialized(PyInterpreterState *interp)
321{
322 if (interp->modules == NULL)
323 return 0;
324 return 1;
325}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000326
Eric Snow3f9eee62017-09-15 16:35:20 -0600327PyObject *
328_PyImport_GetModuleId(struct _Py_Identifier *nameid)
329{
330 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
331 if (name == NULL) {
332 return NULL;
333 }
334 return PyImport_GetModule(name);
335}
336
337int
338_PyImport_SetModule(PyObject *name, PyObject *m)
339{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200340 PyThreadState *tstate = _PyThreadState_GET();
341 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600342 return PyObject_SetItem(modules, name, m);
343}
344
345int
346_PyImport_SetModuleString(const char *name, PyObject *m)
347{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200348 PyThreadState *tstate = _PyThreadState_GET();
349 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600350 return PyMapping_SetItemString(modules, name, m);
351}
352
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200353static PyObject *
354import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600355{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200356 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600357 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200358 _PyErr_SetString(tstate, PyExc_RuntimeError,
359 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600360 return NULL;
361 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200362
363 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600364 Py_INCREF(modules);
365 if (PyDict_CheckExact(modules)) {
366 m = PyDict_GetItemWithError(modules, name); /* borrowed */
367 Py_XINCREF(m);
368 }
369 else {
370 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200371 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
372 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600373 }
374 }
375 Py_DECREF(modules);
376 return m;
377}
378
379
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100380static int
381import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200382{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100383 PyInterpreterState *interp = tstate->interp;
384 PyObject *spec;
385
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100386 _Py_IDENTIFIER(_lock_unlock_module);
387
388 /* Optimization: only call _bootstrap._lock_unlock_module() if
389 __spec__._initializing is true.
390 NOTE: because of this, initializing must be set *before*
391 stuffing the new module in sys.modules.
392 */
393 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
394 int busy = _PyModuleSpec_IsInitializing(spec);
395 Py_XDECREF(spec);
396 if (busy) {
397 /* Wait until module is done importing. */
398 PyObject *value = _PyObject_CallMethodIdOneArg(
399 interp->importlib, &PyId__lock_unlock_module, name);
400 if (value == NULL) {
401 return -1;
402 }
403 Py_DECREF(value);
404 }
405 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200406}
407
408
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000409/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200410static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 "path", "argv", "ps1", "ps2",
412 "last_type", "last_value", "last_traceback",
413 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200414 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000416};
417
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200418static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 "stdin", "__stdin__",
420 "stdout", "__stdout__",
421 "stderr", "__stderr__",
422 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000423};
424
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000425/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000426
Guido van Rossum3f5da241990-12-20 15:06:42 +0000427void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200428_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000429{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200430 PyInterpreterState *interp = tstate->interp;
431 PyObject *modules = interp->modules;
432 if (modules == NULL) {
433 /* Already done */
434 return;
435 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 /* Delete some special variables first. These are common
438 places where user values hide and people complain when their
439 destructors fail. Since the modules containing them are
440 deleted *last* of all, they would come too late in the normal
441 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000442
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200443 /* XXX Perhaps these precautions are obsolete. Who knows? */
444
Victor Stinnerda7933e2020-04-13 03:04:28 +0200445 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200446 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200447 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200448 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300449 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300450 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300451 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200452
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200453 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200454 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200455 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200456 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200457 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300458 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300459 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300460 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200462 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200463 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200464 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200465 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200466 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
467 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200468 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200469 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200470 PyErr_WriteUnraisable(NULL);
471 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200472 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200473 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300474 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300475 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000478
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200479 /* We prepare a list which will receive (name, weakref) tuples of
480 modules when they are removed from sys.modules. The name is used
481 for diagnosis messages (in verbose mode), while the weakref helps
482 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200483 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300484 if (weaklist == NULL) {
485 PyErr_WriteUnraisable(NULL);
486 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200487
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200488#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200489 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200490 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300491 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200492 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300493 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300494 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300495 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200496 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300497 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200498 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300499 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300500 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300501 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600503#define CLEAR_MODULE(name, mod) \
504 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200505 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600506 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200507 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600508 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300509 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300510 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300511 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600512 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000513
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200514 /* Remove all modules from sys.modules, hoping that garbage collection
515 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600516 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200517 Py_ssize_t pos = 0;
518 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600519 while (PyDict_Next(modules, &pos, &key, &value)) {
520 CLEAR_MODULE(key, value);
521 }
522 }
523 else {
524 PyObject *iterator = PyObject_GetIter(modules);
525 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300526 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600527 }
528 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200529 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600530 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200531 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600532 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300533 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600534 continue;
535 }
536 CLEAR_MODULE(key, value);
537 Py_DECREF(value);
538 Py_DECREF(key);
539 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300540 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300541 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300542 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600543 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 }
545 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000546
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200547 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600548 if (PyDict_CheckExact(modules)) {
549 PyDict_Clear(modules);
550 }
551 else {
552 _Py_IDENTIFIER(clear);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200553 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300554 PyErr_WriteUnraisable(NULL);
555 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600556 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200557 /* Restore the original builtins dict, to ensure that any
558 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200559 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300560 if (dict == NULL) {
561 PyErr_WriteUnraisable(NULL);
562 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200563 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300564 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200565 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300566 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200567 Py_XDECREF(dict);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200568 /* Collect references */
569 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200570 /* Dump GC stats before it's too late, since it uses the warnings
571 machinery. */
Victor Stinner67e0de62019-11-20 11:48:18 +0100572 _PyGC_DumpShutdownStats(tstate);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200573
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200574 /* Now, if there are any modules left alive, clear their globals to
575 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200576 up here, since they are kept alive in the interpreter state.
577
578 The special treatment of "builtins" here is because even
579 when it's not referenced as a module, its dictionary is
580 referenced by almost every module's __builtins__. Since
581 deleting a module clears its dictionary (even if there are
582 references left to it), we need to delete the "builtins"
583 module last. Likewise, we don't delete sys until the very
584 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200585 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200586 Py_ssize_t i;
587 /* Since dict is ordered in CPython 3.6+, modules are saved in
588 importing order. First clear modules imported later. */
589 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200590 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200591 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200592 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
593 if (mod == Py_None)
594 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200595 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200596 dict = PyModule_GetDict(mod);
597 if (dict == interp->builtins || dict == interp->sysdict)
598 continue;
599 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200600 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200601 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200602 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200603 _PyModule_Clear(mod);
604 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200605 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200606 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000608
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200609 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200610 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200611 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200612 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200613 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200614 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200615 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200616 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200617 _PyModule_ClearDict(interp->builtins);
618
Eddie Elizondo4590f722020-02-04 02:29:25 -0800619 /* Clear module dict copies stored in the interpreter state */
620 _PyInterpreterState_ClearModules(interp);
621
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200622 /* Clear and delete the modules directory. Actual modules will
623 still be there only if imported during the execution of some
624 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700625 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200627
628 /* Once more */
629 _PyGC_CollectNoFail();
630
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300631#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200632#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000633}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000634
635
Barry Warsaw28a691b2010-04-17 00:19:56 +0000636/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000637
638long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000639PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000640{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200641 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200642 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600643 PyObject *external, *pyc_magic;
644
645 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
646 if (external == NULL)
647 return -1;
648 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
649 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400650 if (pyc_magic == NULL)
651 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200652 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700653 Py_DECREF(pyc_magic);
654 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000655}
656
657
Brett Cannon3adc7b72012-07-09 14:22:12 -0400658extern const char * _PySys_ImplCacheTag;
659
Barry Warsaw28a691b2010-04-17 00:19:56 +0000660const char *
661PyImport_GetMagicTag(void)
662{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400663 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000664}
665
Brett Cannon98979b82012-07-02 15:13:11 -0400666
Guido van Rossum25ce5661997-08-02 03:10:38 +0000667/* Magic for extension modules (built-in as well as dynamically
668 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200669 once, we keep a static dictionary 'extensions' keyed by the tuple
670 (module name, module name) (for built-in modules) or by
671 (filename, module name) (for dynamically loaded modules), containing these
672 modules. A copy of the module's dictionary is stored by calling
673 _PyImport_FixupExtensionObject() immediately after the module initialization
674 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100675 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000676
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000677 Modules which do support multiple initialization set their m_size
678 field to a non-negative number (indicating the size of the
679 module-specific state). They are still recorded in the extensions
680 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000681*/
682
683int
Victor Stinner95872862011-03-07 18:20:56 +0100684_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200685 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if (mod == NULL || !PyModule_Check(mod)) {
688 PyErr_BadInternalCall();
689 return -1;
690 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100691
692 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (!def) {
694 PyErr_BadInternalCall();
695 return -1;
696 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100697
698 PyThreadState *tstate = _PyThreadState_GET();
699 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100701 }
702 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600703 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 return -1;
705 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100706
707 if (_Py_IsMainInterpreter(tstate)) {
708 if (def->m_size == -1) {
709 if (def->m_base.m_copy) {
710 /* Somebody already imported the module,
711 likely under a different name.
712 XXX this should really not happen. */
713 Py_CLEAR(def->m_base.m_copy);
714 }
715 PyObject *dict = PyModule_GetDict(mod);
716 if (dict == NULL) {
717 return -1;
718 }
719 def->m_base.m_copy = PyDict_Copy(dict);
720 if (def->m_base.m_copy == NULL) {
721 return -1;
722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100724
725 if (extensions == NULL) {
726 extensions = PyDict_New();
727 if (extensions == NULL) {
728 return -1;
729 }
730 }
731
732 PyObject *key = PyTuple_Pack(2, filename, name);
733 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100735 }
736 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
737 Py_DECREF(key);
738 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000744}
745
Victor Stinner49d3f252010-10-17 01:24:53 +0000746int
Eric Snowd393c1b2017-09-14 12:18:12 -0600747_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000748{
749 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100750 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100751 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100752 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000753 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600754 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100755 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000756 return res;
757}
758
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200759static PyObject *
760import_find_extension(PyThreadState *tstate, PyObject *name,
761 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000762{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200763 if (extensions == NULL) {
764 return NULL;
765 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600766
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200767 PyObject *key = PyTuple_Pack(2, filename, name);
768 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200770 }
771 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500772 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200773 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200775 }
776
777 PyObject *mod, *mdict;
778 PyObject *modules = tstate->interp->modules;
779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (def->m_size == -1) {
781 /* Module does not support repeated initialization */
782 if (def->m_base.m_copy == NULL)
783 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200784 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (mod == NULL)
786 return NULL;
787 mdict = PyModule_GetDict(mod);
788 if (mdict == NULL)
789 return NULL;
790 if (PyDict_Update(mdict, def->m_base.m_copy))
791 return NULL;
792 }
793 else {
794 if (def->m_base.m_init == NULL)
795 return NULL;
796 mod = def->m_base.m_init();
797 if (mod == NULL)
798 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600799 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200800 Py_DECREF(mod);
801 return NULL;
802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_DECREF(mod);
804 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100805 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600806 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 return NULL;
808 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200809
Victor Stinnerda7933e2020-04-13 03:04:28 +0200810 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200811 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100812 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200813 name, filename);
814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000816}
817
Victor Stinner49d3f252010-10-17 01:24:53 +0000818PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200819_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
820{
821 PyThreadState *tstate = _PyThreadState_GET();
822 return import_find_extension(tstate, name, filename);
823}
824
825
826PyObject *
827_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000828{
Victor Stinner95872862011-03-07 18:20:56 +0100829 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100830 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100831 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000832 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200833 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100834 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000835 return res;
836}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000837
838/* Get the module object corresponding to a module name.
839 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000840 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000841 Because the former action is most common, THIS DOES NOT RETURN A
842 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000843
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200844static PyObject *
845import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000846{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200847 PyObject *modules = tstate->interp->modules;
848 if (modules == NULL) {
849 _PyErr_SetString(tstate, PyExc_RuntimeError,
850 "no import module dictionary");
851 return NULL;
852 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600853
Eric Snow86b7afd2017-09-04 17:54:09 -0600854 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600855 if (PyDict_CheckExact(modules)) {
856 m = PyDict_GetItemWithError(modules, name);
857 }
858 else {
859 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000860 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600861 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200862 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
863 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600864 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200865 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200866 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200867 return NULL;
868 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600869 if (m != NULL && PyModule_Check(m)) {
870 return m;
871 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000872 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (m == NULL)
874 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600875 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 Py_DECREF(m);
877 return NULL;
878 }
879 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882}
883
Victor Stinner27ee0892011-03-04 12:57:09 +0000884PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200885PyImport_AddModuleObject(PyObject *name)
886{
887 PyThreadState *tstate = _PyThreadState_GET();
888 return import_add_module(tstate, name);
889}
890
891
892PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000893PyImport_AddModule(const char *name)
894{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200895 PyObject *nameobj = PyUnicode_FromString(name);
896 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000897 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200898 }
899 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000900 Py_DECREF(nameobj);
901 return module;
902}
903
904
Tim Peters1cd70172004-08-02 03:52:12 +0000905/* Remove name from sys.modules, if it's there. */
906static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200907remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000908{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600909 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200910 _PyErr_Fetch(tstate, &type, &value, &traceback);
911
912 PyObject *modules = tstate->interp->modules;
Zackery Spytz94a64e92019-05-08 10:31:23 -0600913 if (!PyMapping_HasKey(modules, name)) {
914 goto out;
915 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600916 if (PyMapping_DelItem(modules, name) < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200917 _PyErr_SetString(tstate, PyExc_RuntimeError,
918 "deleting key in sys.modules failed");
919 _PyErr_ChainExceptions(type, value, traceback);
920 return;
Eric Snow3f9eee62017-09-15 16:35:20 -0600921 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200922
Zackery Spytz94a64e92019-05-08 10:31:23 -0600923out:
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200924 _PyErr_Restore(tstate, type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000925}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000926
Christian Heimes3b06e532008-01-07 20:12:44 +0000927
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000928/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000929 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
930 * removed from sys.modules, to avoid leaving damaged module objects
931 * in sys.modules. The caller may wish to restore the original
932 * module object (if any) in this case; PyImport_ReloadModule is an
933 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000934 *
935 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
936 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000937 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000938PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300939PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 return PyImport_ExecCodeModuleWithPathnames(
942 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000943}
944
945PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300946PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return PyImport_ExecCodeModuleWithPathnames(
949 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000950}
951
952PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300953PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
954 const char *pathname,
955 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000956{
Victor Stinner27ee0892011-03-04 12:57:09 +0000957 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600958 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000959
960 nameobj = PyUnicode_FromString(name);
961 if (nameobj == NULL)
962 return NULL;
963
Victor Stinner27ee0892011-03-04 12:57:09 +0000964 if (cpathname != NULL) {
965 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
966 if (cpathobj == NULL)
967 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400968 }
969 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000970 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400971
972 if (pathname != NULL) {
973 pathobj = PyUnicode_DecodeFSDefault(pathname);
974 if (pathobj == NULL)
975 goto error;
976 }
977 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200978 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400979 _Py_IDENTIFIER(_get_sourcefile);
980
981 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100982 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400983 }
984
Eric Snow32439d62015-05-02 19:15:18 -0600985 external= PyObject_GetAttrString(interp->importlib,
986 "_bootstrap_external");
987 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200988 pathobj = _PyObject_CallMethodIdOneArg(
989 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600990 Py_DECREF(external);
991 }
Brett Cannona6473f92012-07-13 13:57:03 -0400992 if (pathobj == NULL)
993 PyErr_Clear();
994 }
995 else
996 pathobj = NULL;
997
Victor Stinner27ee0892011-03-04 12:57:09 +0000998 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
999error:
1000 Py_DECREF(nameobj);
1001 Py_XDECREF(pathobj);
1002 Py_XDECREF(cpathobj);
1003 return m;
1004}
1005
Brett Cannon18fc4e72014-04-04 10:01:46 -04001006static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001007module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +00001008{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001009 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001010 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001011
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001012 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (m == NULL)
1014 return NULL;
1015 /* If the module is being reloaded, we get the old module back
1016 and re-use its dict to exec the new code. */
1017 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001018 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001019 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001020 _PyDict_SetItemId(d, &PyId___builtins__,
1021 PyEval_GetBuiltins()) != 0)
1022 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001023 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001024 return NULL;
1025 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001027
Eric Snow08197a42014-05-12 17:54:55 -06001028 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001029}
1030
1031static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001032exec_code_in_module(PyThreadState *tstate, PyObject *name,
1033 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001034{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001035 PyObject *v, *m;
1036
1037 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1038 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001039 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001040 return NULL;
1041 }
1042 Py_DECREF(v);
1043
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001044 m = import_get_module(tstate, name);
1045 if (m == NULL && !_PyErr_Occurred(tstate)) {
1046 _PyErr_Format(tstate, PyExc_ImportError,
1047 "Loaded module %R not found in sys.modules",
1048 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001049 }
1050
Brett Cannon18fc4e72014-04-04 10:01:46 -04001051 return m;
1052}
1053
1054PyObject*
1055PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1056 PyObject *cpathname)
1057{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001058 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001059 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001060 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001061
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001062 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001063 if (d == NULL) {
1064 return NULL;
1065 }
1066
Eric Snow08197a42014-05-12 17:54:55 -06001067 if (pathname == NULL) {
1068 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001070 external = PyObject_GetAttrString(tstate->interp->importlib,
1071 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001072 if (external == NULL)
1073 return NULL;
1074 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001075 &PyId__fix_up_module,
1076 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001077 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001078 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001079 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001080 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 }
Eric Snow08197a42014-05-12 17:54:55 -06001082 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001083}
1084
1085
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001086static void
1087update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyObject *constants, *tmp;
1090 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (PyUnicode_Compare(co->co_filename, oldname))
1093 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001094
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001095 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001096 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 constants = co->co_consts;
1099 n = PyTuple_GET_SIZE(constants);
1100 for (i = 0; i < n; i++) {
1101 tmp = PyTuple_GET_ITEM(constants, i);
1102 if (PyCode_Check(tmp))
1103 update_code_filenames((PyCodeObject *)tmp,
1104 oldname, newname);
1105 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001106}
1107
Victor Stinner2f42ae52011-03-20 00:41:24 +01001108static void
1109update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001110{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001111 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001112
Victor Stinner2f42ae52011-03-20 00:41:24 +01001113 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1114 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 oldname = co->co_filename;
1117 Py_INCREF(oldname);
1118 update_code_filenames(co, oldname, newname);
1119 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001120}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001121
Brett Cannon4caa61d2014-01-09 19:03:32 -05001122/*[clinic input]
1123_imp._fix_co_filename
1124
1125 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1126 Code object to change.
1127
1128 path: unicode
1129 File path to use.
1130 /
1131
1132Changes code.co_filename to specify the passed-in file path.
1133[clinic start generated code]*/
1134
Brett Cannon4caa61d2014-01-09 19:03:32 -05001135static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001136_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001137 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001138/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001139
Brett Cannon4caa61d2014-01-09 19:03:32 -05001140{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001141 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001142
1143 Py_RETURN_NONE;
1144}
1145
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001146
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001147/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001148static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001149
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001150
1151/* Helper to test for built-in module */
1152
1153static int
Victor Stinner95872862011-03-07 18:20:56 +01001154is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001155{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001156 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001158 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (PyImport_Inittab[i].initfunc == NULL)
1160 return -1;
1161 else
1162 return 1;
1163 }
1164 }
1165 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001166}
1167
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001168
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001169/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001170 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001171 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001172 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001173 this tells our caller that the path based finder could not find
1174 a finder for this path item. Cache the result in
1175 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001176 Returns a borrowed reference. */
1177
1178static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001179get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1180 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 PyObject *importer;
1183 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 /* These conditions are the caller's responsibility: */
1186 assert(PyList_Check(path_hooks));
1187 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 nhooks = PyList_Size(path_hooks);
1190 if (nhooks < 0)
1191 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001192
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001193 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001194 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 /* set path_importer_cache[p] to None to avoid recursion */
1198 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1199 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 for (j = 0; j < nhooks; j++) {
1202 PyObject *hook = PyList_GetItem(path_hooks, j);
1203 if (hook == NULL)
1204 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +01001205 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (importer != NULL)
1207 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001208
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001209 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 return NULL;
1211 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001212 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
1214 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001215 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 }
1217 if (importer != NULL) {
1218 int err = PyDict_SetItem(path_importer_cache, p, importer);
1219 Py_DECREF(importer);
1220 if (err != 0)
1221 return NULL;
1222 }
1223 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001224}
1225
Benjamin Petersone5024512018-09-12 12:06:42 -07001226PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001227PyImport_GetImporter(PyObject *path)
1228{
1229 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001231
Victor Stinner1e53bba2013-07-16 22:26:05 +02001232 path_importer_cache = PySys_GetObject("path_importer_cache");
1233 path_hooks = PySys_GetObject("path_hooks");
1234 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001235 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001236 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 }
1238 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1239 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001240}
1241
Nick Coghland5cacbb2015-05-23 22:24:10 +10001242/*[clinic input]
1243_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001244
Nick Coghland5cacbb2015-05-23 22:24:10 +10001245 spec: object
1246 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001247
Nick Coghland5cacbb2015-05-23 22:24:10 +10001248Create an extension module.
1249[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001250
Nick Coghland5cacbb2015-05-23 22:24:10 +10001251static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001252_imp_create_builtin(PyObject *module, PyObject *spec)
1253/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001254{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001255 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001257 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001258 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001259 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001260
Nick Coghland5cacbb2015-05-23 22:24:10 +10001261 name = PyObject_GetAttrString(spec, "name");
1262 if (name == NULL) {
1263 return NULL;
1264 }
1265
Victor Stinner5eb4f592013-11-14 22:38:52 +01001266 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001267 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001268 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001269 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001270 return mod;
1271 }
1272
1273 namestr = PyUnicode_AsUTF8(name);
1274 if (namestr == NULL) {
1275 Py_DECREF(name);
1276 return NULL;
1277 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001278
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001279 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001281 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001282 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001284 /* Cannot re-init internal module ("sys" or "builtins") */
1285 mod = PyImport_AddModule(namestr);
1286 Py_DECREF(name);
1287 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001290 if (mod == NULL) {
1291 Py_DECREF(name);
1292 return NULL;
1293 }
1294 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1295 Py_DECREF(name);
1296 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1297 } else {
1298 /* Remember pointer to module init function. */
1299 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001300 if (def == NULL) {
1301 Py_DECREF(name);
1302 return NULL;
1303 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001304 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001305 if (_PyImport_FixupExtensionObject(mod, name, name,
1306 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001307 Py_DECREF(name);
1308 return NULL;
1309 }
1310 Py_DECREF(name);
1311 return mod;
1312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 }
1314 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001315 Py_DECREF(name);
1316 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001317}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001318
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001319
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001320/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001321
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001322static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001323find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001324{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001325 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001326
Victor Stinner53dc7352011-03-20 01:50:21 +01001327 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 for (p = PyImport_FrozenModules; ; p++) {
1331 if (p->name == NULL)
1332 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001333 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 break;
1335 }
1336 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001337}
1338
Guido van Rossum79f25d91997-04-29 20:08:16 +00001339static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001340get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001341{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001342 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (p == NULL) {
1346 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001347 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 name);
1349 return NULL;
1350 }
1351 if (p->code == NULL) {
1352 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001353 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 name);
1355 return NULL;
1356 }
1357 size = p->size;
1358 if (size < 0)
1359 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001360 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001361}
1362
Brett Cannon8d110132009-03-15 02:20:16 +00001363static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001364is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001365{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001366 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (p == NULL) {
1370 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001371 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 name);
1373 return NULL;
1374 }
Brett Cannon8d110132009-03-15 02:20:16 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (size < 0)
1379 Py_RETURN_TRUE;
1380 else
1381 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001382}
1383
1384
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001385/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001386 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001387 an exception set if the initialization failed.
1388 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001389
1390int
Victor Stinner53dc7352011-03-20 01:50:21 +01001391PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001392{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001393 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001394 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001395 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 int ispackage;
1397 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001398
Victor Stinner53dc7352011-03-20 01:50:21 +01001399 p = find_frozen(name);
1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 if (p == NULL)
1402 return 0;
1403 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001404 _PyErr_Format(tstate, PyExc_ImportError,
1405 "Excluded frozen object named %R",
1406 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 return -1;
1408 }
1409 size = p->size;
1410 ispackage = (size < 0);
1411 if (ispackage)
1412 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001413 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (co == NULL)
1415 return -1;
1416 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001417 _PyErr_Format(tstate, PyExc_TypeError,
1418 "frozen object %R is not a code object",
1419 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 goto err_return;
1421 }
1422 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001423 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001424 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001426 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (m == NULL)
1428 goto err_return;
1429 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001430 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 goto err_return;
1433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 err = PyDict_SetItemString(d, "__path__", l);
1435 Py_DECREF(l);
1436 if (err != 0)
1437 goto err_return;
1438 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001439 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001440 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001441 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001442 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001443 m = exec_code_in_module(tstate, name, d, co);
1444 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 Py_DECREF(co);
1448 Py_DECREF(m);
1449 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001450
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001451err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_DECREF(co);
1453 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001454}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001455
Victor Stinner53dc7352011-03-20 01:50:21 +01001456int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001457PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001458{
1459 PyObject *nameobj;
1460 int ret;
1461 nameobj = PyUnicode_InternFromString(name);
1462 if (nameobj == NULL)
1463 return -1;
1464 ret = PyImport_ImportFrozenModuleObject(nameobj);
1465 Py_DECREF(nameobj);
1466 return ret;
1467}
1468
Guido van Rossum74e6a111994-08-29 12:54:38 +00001469
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001470/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001471 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001472
Guido van Rossum79f25d91997-04-29 20:08:16 +00001473PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001474PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 PyObject *pname;
1477 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 pname = PyUnicode_FromString(name);
1480 if (pname == NULL)
1481 return NULL;
1482 result = PyImport_Import(pname);
1483 Py_DECREF(pname);
1484 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001485}
1486
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001487
Christian Heimes072c0f12008-01-03 23:01:04 +00001488/* Import a module without blocking
1489 *
1490 * At first it tries to fetch the module from sys.modules. If the module was
1491 * never loaded before it loads it with PyImport_ImportModule() unless another
1492 * thread holds the import lock. In the latter case the function raises an
1493 * ImportError instead of blocking.
1494 *
1495 * Returns the module object with incremented ref count.
1496 */
1497PyObject *
1498PyImport_ImportModuleNoBlock(const char *name)
1499{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001500 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001501}
1502
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001503
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001504/* Remove importlib frames from the traceback,
1505 * except in Verbose mode. */
1506static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001507remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001508{
1509 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001510 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001511 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001512 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001513 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001514 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001515 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001516
1517 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001518 from the traceback. We always trim chunks
1519 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001520
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001521 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001522 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001523 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001524 }
1525
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001526 if (PyType_IsSubtype((PyTypeObject *) exception,
1527 (PyTypeObject *) PyExc_ImportError))
1528 always_trim = 1;
1529
1530 prev_link = &base_tb;
1531 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001532 while (tb != NULL) {
1533 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1534 PyObject *next = (PyObject *) traceback->tb_next;
1535 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001536 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001537 int now_in_importlib;
1538
1539 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001540 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1541 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001542 if (now_in_importlib && !in_importlib) {
1543 /* This is the link to this chunk of importlib tracebacks */
1544 outer_link = prev_link;
1545 }
1546 in_importlib = now_in_importlib;
1547
1548 if (in_importlib &&
1549 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001550 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001551 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001552 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001553 prev_link = outer_link;
1554 }
1555 else {
1556 prev_link = (PyObject **) &traceback->tb_next;
1557 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001558 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001559 tb = next;
1560 }
1561done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001562 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001563}
1564
1565
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001566static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001567resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001568{
Brett Cannonfd074152012-04-14 14:10:13 -04001569 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001570 _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 Stinnerda7933e2020-04-13 03:04:28 +02001727 int import_time = _PyInterpreterState_GetConfig(interp)->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");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001736 if (_PySys_Audit(tstate, "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) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001740 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())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001763 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001764
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())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001770 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001771 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 PyObject *path;
1932 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1933 goto error;
1934 }
1935 if (path) {
1936 Py_DECREF(path);
1937 final_mod = _PyObject_CallMethodIdObjArgs(
1938 interp->importlib, &PyId__handle_fromlist,
1939 mod, fromlist, interp->import_func, NULL);
1940 }
1941 else {
1942 final_mod = mod;
1943 Py_INCREF(mod);
1944 }
Brett Cannonfd074152012-04-14 14:10:13 -04001945 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001946
Brett Cannonfd074152012-04-14 14:10:13 -04001947 error:
1948 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001949 Py_XDECREF(mod);
1950 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001951 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001952 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001953 }
Brett Cannonfd074152012-04-14 14:10:13 -04001954 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001955}
1956
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001957PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001958PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001959 PyObject *fromlist, int level)
1960{
1961 PyObject *nameobj, *mod;
1962 nameobj = PyUnicode_FromString(name);
1963 if (nameobj == NULL)
1964 return NULL;
1965 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1966 fromlist, level);
1967 Py_DECREF(nameobj);
1968 return mod;
1969}
1970
1971
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001972/* Re-import a module of any kind and return its module object, WITH
1973 INCREMENTED REFERENCE COUNT */
1974
Guido van Rossum79f25d91997-04-29 20:08:16 +00001975PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001976PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001977{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001978 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001979 _Py_IDENTIFIER(reload);
1980 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001981 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1982 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001983 if (PyErr_Occurred()) {
1984 return NULL;
1985 }
1986
Robert Rouhanif40bd462020-05-01 16:28:06 -07001987 importlib = PyImport_ImportModule("importlib");
1988 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001989 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001992
Robert Rouhanif40bd462020-05-01 16:28:06 -07001993 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1994 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001995 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001996}
1997
1998
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001999/* Higher-level import emulator which emulates the "import" statement
2000 more accurately -- it invokes the __import__() function from the
2001 builtins of the current globals. This means that the import is
2002 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002003 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002004 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002005 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002006 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002007
2008PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002009PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002010{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002011 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 static PyObject *silly_list = NULL;
2013 static PyObject *builtins_str = NULL;
2014 static PyObject *import_str = NULL;
2015 PyObject *globals = NULL;
2016 PyObject *import = NULL;
2017 PyObject *builtins = NULL;
2018 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Initialize constant string objects */
2021 if (silly_list == NULL) {
2022 import_str = PyUnicode_InternFromString("__import__");
2023 if (import_str == NULL)
2024 return NULL;
2025 builtins_str = PyUnicode_InternFromString("__builtins__");
2026 if (builtins_str == NULL)
2027 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002028 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (silly_list == NULL)
2030 return NULL;
2031 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 /* Get the builtins from current globals */
2034 globals = PyEval_GetGlobals();
2035 if (globals != NULL) {
2036 Py_INCREF(globals);
2037 builtins = PyObject_GetItem(globals, builtins_str);
2038 if (builtins == NULL)
2039 goto err;
2040 }
2041 else {
2042 /* No globals -- use standard builtins, and fake globals */
2043 builtins = PyImport_ImportModuleLevel("builtins",
2044 NULL, NULL, NULL, 0);
2045 if (builtins == NULL)
2046 return NULL;
2047 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2048 if (globals == NULL)
2049 goto err;
2050 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* Get the __import__ function from the builtins */
2053 if (PyDict_Check(builtins)) {
2054 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002055 if (import == NULL) {
2056 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 }
2059 else
2060 import = PyObject_GetAttr(builtins, import_str);
2061 if (import == NULL)
2062 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002065 Always use absolute import here.
2066 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2068 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002069 if (r == NULL)
2070 goto err;
2071 Py_DECREF(r);
2072
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002073 r = import_get_module(tstate, module_name);
2074 if (r == NULL && !_PyErr_Occurred(tstate)) {
2075 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002076 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002077
2078 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 Py_XDECREF(globals);
2080 Py_XDECREF(builtins);
2081 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002084}
2085
Brett Cannon4caa61d2014-01-09 19:03:32 -05002086/*[clinic input]
2087_imp.extension_suffixes
2088
2089Returns the list of file suffixes used to identify extension modules.
2090[clinic start generated code]*/
2091
Brett Cannon4caa61d2014-01-09 19:03:32 -05002092static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002093_imp_extension_suffixes_impl(PyObject *module)
2094/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 list = PyList_New(0);
2099 if (list == NULL)
2100 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002101#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002102 const char *suffix;
2103 unsigned int index = 0;
2104
Brett Cannon2657df42012-05-04 15:20:40 -04002105 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2106 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (item == NULL) {
2108 Py_DECREF(list);
2109 return NULL;
2110 }
2111 if (PyList_Append(list, item) < 0) {
2112 Py_DECREF(list);
2113 Py_DECREF(item);
2114 return NULL;
2115 }
2116 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002117 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 }
Brett Cannon2657df42012-05-04 15:20:40 -04002119#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002121}
2122
Brett Cannon4caa61d2014-01-09 19:03:32 -05002123/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002124_imp.init_frozen
2125
2126 name: unicode
2127 /
2128
2129Initializes a frozen module.
2130[clinic start generated code]*/
2131
Brett Cannon4caa61d2014-01-09 19:03:32 -05002132static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002133_imp_init_frozen_impl(PyObject *module, PyObject *name)
2134/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002135{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002136 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 int ret;
2138 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002139
Victor Stinner53dc7352011-03-20 01:50:21 +01002140 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (ret < 0)
2142 return NULL;
2143 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002144 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002146 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 Py_XINCREF(m);
2148 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002149}
2150
Brett Cannon4caa61d2014-01-09 19:03:32 -05002151/*[clinic input]
2152_imp.get_frozen_object
2153
2154 name: unicode
2155 /
2156
2157Create a code object for a frozen module.
2158[clinic start generated code]*/
2159
Brett Cannon4caa61d2014-01-09 19:03:32 -05002160static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002161_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2162/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002165}
2166
Brett Cannon4caa61d2014-01-09 19:03:32 -05002167/*[clinic input]
2168_imp.is_frozen_package
2169
2170 name: unicode
2171 /
2172
2173Returns True if the module name is of a frozen package.
2174[clinic start generated code]*/
2175
Brett Cannon4caa61d2014-01-09 19:03:32 -05002176static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002177_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2178/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002181}
2182
Brett Cannon4caa61d2014-01-09 19:03:32 -05002183/*[clinic input]
2184_imp.is_builtin
2185
2186 name: unicode
2187 /
2188
2189Returns True if the module name corresponds to a built-in module.
2190[clinic start generated code]*/
2191
Guido van Rossum79f25d91997-04-29 20:08:16 +00002192static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002193_imp_is_builtin_impl(PyObject *module, PyObject *name)
2194/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002195{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002196 return PyLong_FromLong(is_builtin(name));
2197}
2198
2199/*[clinic input]
2200_imp.is_frozen
2201
2202 name: unicode
2203 /
2204
2205Returns True if the module name corresponds to a frozen module.
2206[clinic start generated code]*/
2207
Brett Cannon4caa61d2014-01-09 19:03:32 -05002208static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002209_imp_is_frozen_impl(PyObject *module, PyObject *name)
2210/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002211{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002212 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 p = find_frozen(name);
2215 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002216}
2217
Larry Hastings1df0b352015-08-24 19:53:56 -07002218/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2219static int
2220exec_builtin_or_dynamic(PyObject *mod) {
2221 PyModuleDef *def;
2222 void *state;
2223
2224 if (!PyModule_Check(mod)) {
2225 return 0;
2226 }
2227
2228 def = PyModule_GetDef(mod);
2229 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002230 return 0;
2231 }
Brett Cannon52794db2016-09-07 17:00:43 -07002232
Larry Hastings1df0b352015-08-24 19:53:56 -07002233 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002234 if (state) {
2235 /* Already initialized; skip reload */
2236 return 0;
2237 }
Brett Cannon52794db2016-09-07 17:00:43 -07002238
Larry Hastings1df0b352015-08-24 19:53:56 -07002239 return PyModule_ExecDef(mod, def);
2240}
2241
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002242#ifdef HAVE_DYNAMIC_LOADING
2243
Brett Cannon4caa61d2014-01-09 19:03:32 -05002244/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002245_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002246
Nick Coghland5cacbb2015-05-23 22:24:10 +10002247 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002248 file: object = NULL
2249 /
2250
Nick Coghland5cacbb2015-05-23 22:24:10 +10002251Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002252[clinic start generated code]*/
2253
Brett Cannon4caa61d2014-01-09 19:03:32 -05002254static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002255_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2256/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002257{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002258 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002259 FILE *fp;
2260
Nick Coghland5cacbb2015-05-23 22:24:10 +10002261 name = PyObject_GetAttrString(spec, "name");
2262 if (name == NULL) {
2263 return NULL;
2264 }
2265
2266 path = PyObject_GetAttrString(spec, "origin");
2267 if (path == NULL) {
2268 Py_DECREF(name);
2269 return NULL;
2270 }
2271
2272 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002273 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002274 Py_DECREF(name);
2275 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002276 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002277 return mod;
2278 }
2279
Brett Cannon4caa61d2014-01-09 19:03:32 -05002280 if (file != NULL) {
2281 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002282 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002283 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002284 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002288 else
2289 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002290
2291 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2292
2293 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002294 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (fp)
2296 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002297 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002298}
2299
Nick Coghland5cacbb2015-05-23 22:24:10 +10002300/*[clinic input]
2301_imp.exec_dynamic -> int
2302
2303 mod: object
2304 /
2305
2306Initialize an extension module.
2307[clinic start generated code]*/
2308
2309static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002310_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2311/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002312{
Larry Hastings1df0b352015-08-24 19:53:56 -07002313 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002314}
2315
2316
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002317#endif /* HAVE_DYNAMIC_LOADING */
2318
Larry Hastings7726ac92014-01-31 22:03:12 -08002319/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002320_imp.exec_builtin -> int
2321
2322 mod: object
2323 /
2324
2325Initialize a built-in module.
2326[clinic start generated code]*/
2327
2328static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002329_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2330/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002331{
2332 return exec_builtin_or_dynamic(mod);
2333}
2334
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002335/*[clinic input]
2336_imp.source_hash
2337
2338 key: long
2339 source: Py_buffer
2340[clinic start generated code]*/
2341
2342static PyObject *
2343_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2344/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2345{
Benjamin Peterson83620772017-12-09 12:18:56 -08002346 union {
2347 uint64_t x;
2348 char data[sizeof(uint64_t)];
2349 } hash;
2350 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002351#if !PY_LITTLE_ENDIAN
2352 // Force to little-endian. There really ought to be a succinct standard way
2353 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002354 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2355 char tmp = hash.data[i];
2356 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2357 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002358 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002359#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002360 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002361}
2362
Barry Warsaw28a691b2010-04-17 00:19:56 +00002363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002364PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002365"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002366
Guido van Rossum79f25d91997-04-29 20:08:16 +00002367static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002368 _IMP_EXTENSION_SUFFIXES_METHODDEF
2369 _IMP_LOCK_HELD_METHODDEF
2370 _IMP_ACQUIRE_LOCK_METHODDEF
2371 _IMP_RELEASE_LOCK_METHODDEF
2372 _IMP_GET_FROZEN_OBJECT_METHODDEF
2373 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002374 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002375 _IMP_INIT_FROZEN_METHODDEF
2376 _IMP_IS_BUILTIN_METHODDEF
2377 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002378 _IMP_CREATE_DYNAMIC_METHODDEF
2379 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002380 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002381 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002382 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002383 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002384};
2385
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002386
Martin v. Löwis1a214512008-06-11 05:26:20 +00002387static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002389 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 doc_imp,
2391 0,
2392 imp_methods,
2393 NULL,
2394 NULL,
2395 NULL,
2396 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002397};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002398
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002399PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002400PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002405 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002407 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002409 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002411 }
2412
Victor Stinnerda7933e2020-04-13 03:04:28 +02002413 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002414 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002415 if (pyc_mode == NULL) {
2416 goto failure;
2417 }
2418 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2419 Py_DECREF(pyc_mode);
2420 goto failure;
2421 }
2422 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002425 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 Py_XDECREF(m);
2427 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002428}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002429
2430
Guido van Rossumb18618d2000-05-03 23:44:39 +00002431/* API for embedding applications that want to add their own entries
2432 to the table of built-in modules. This should normally be called
2433 *before* Py_Initialize(). When the table resize fails, -1 is
2434 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002435
2436 After a similar function by Just van Rossum. */
2437
2438int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002439PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002442 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002443 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 /* Count the number of entries in both tables */
2446 for (n = 0; newtab[n].name != NULL; n++)
2447 ;
2448 if (n == 0)
2449 return 0; /* Nothing to do */
2450 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2451 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002452
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002453 /* Force default raw memory allocator to get a known allocator to be able
2454 to release the memory in _PyImport_Fini2() */
2455 PyMemAllocatorEx old_alloc;
2456 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002459 p = NULL;
2460 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002461 size_t size = sizeof(struct _inittab) * (i + n + 1);
2462 p = PyMem_RawRealloc(inittab_copy, size);
2463 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002464 if (p == NULL) {
2465 res = -1;
2466 goto done;
2467 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002468
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002469 /* Copy the tables into the new memory at the first call
2470 to PyImport_ExtendInittab(). */
2471 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002473 }
2474 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2475 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002476
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002477done:
2478 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2479 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002480}
2481
2482/* Shorthand to add a single entry given a name and a function */
2483
2484int
Brett Cannona826f322009-04-02 03:41:46 +00002485PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002490
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002491 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002495}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002496
2497#ifdef __cplusplus
2498}
2499#endif