blob: c4878c628bedcf3b4345e4da0d82782caeb285aa [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
Victor Stinner62230712020-11-18 23:18:29 +01005#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner61691d82019-10-02 23:51:20 +02006#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02007#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01008#include "pycore_pyhash.h"
9#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020010#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020011#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
12#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010013#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000015#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000017#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020018#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000019
Guido van Rossum55a83382000-09-20 20:31:38 +000020#ifdef HAVE_FCNTL_H
21#include <fcntl.h>
22#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000024extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000026
Barry Warsaw28a691b2010-04-17 00:19:56 +000027#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000028
Victor Stinner0a28f8d2019-06-19 02:54:39 +020029/* Forward references */
30static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
31
Victor Stinner95872862011-03-07 18:20:56 +010032/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000033static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000034
Guido van Rossum771c6c81997-10-31 18:37:24 +000035/* This table is defined in config.c: */
36extern struct _inittab _PyImport_Inittab[];
37
38struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010039static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000040
Hai Shi46874c22020-01-30 17:20:25 -060041_Py_IDENTIFIER(__path__);
42_Py_IDENTIFIER(__spec__);
43
Brett Cannon4caa61d2014-01-09 19:03:32 -050044/*[clinic input]
45module _imp
46[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030047/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040048
49#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050050
Guido van Rossum1ae940a1995-01-02 19:04:15 +000051/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052
Victor Stinner331a6a52019-05-27 16:39:22 +020053PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020054_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040055{
ukwksk5e6312c2018-05-15 04:10:52 +090056 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040057 int err = 0;
58
59 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020060 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020061 _PyErr_SetString(tstate, PyExc_RuntimeError,
62 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040063 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020064 }
Brett Cannonfd074152012-04-14 14:10:13 -040065
Victor Stinnerda7933e2020-04-13 03:04:28 +020066 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +020067 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -040068 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020069 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
ukwksk5e6312c2018-05-15 04:10:52 +090071 zipimport = PyImport_ImportModule("zipimport");
72 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020073 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020074 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 }
78 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020079 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090080 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020081 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090082 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020084 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020085 if (verbose) {
86 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
87 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 }
89 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -040090 /* sys.path_hooks.insert(0, zipimporter) */
91 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -040093 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -040095 }
Victor Stinner410b85a2019-05-13 17:12:45 +020096 if (verbose) {
97 PySys_WriteStderr("# installed zipimport hook\n");
98 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 }
100 }
Brett Cannonfd074152012-04-14 14:10:13 -0400101
Victor Stinner331a6a52019-05-27 16:39:22 +0200102 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400103
104 error:
105 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200106 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000107}
108
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000109/* Locking primitives to prevent parallel imports of the same module
110 in different threads to return with a partially loaded module.
111 These calls are serialized by the global interpreter lock. */
112
Victor Stinner26881c82020-06-02 15:51:37 +0200113static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200114static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000115static int import_lock_level = 0;
116
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000117void
118_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000119{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200120 unsigned long me = PyThread_get_thread_ident();
121 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 return; /* Too bad */
123 if (import_lock == NULL) {
124 import_lock = PyThread_allocate_lock();
125 if (import_lock == NULL)
126 return; /* Nothing much we can do. */
127 }
128 if (import_lock_thread == me) {
129 import_lock_level++;
130 return;
131 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200132 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
133 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 {
135 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200136 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 PyEval_RestoreThread(tstate);
138 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100139 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 import_lock_thread = me;
141 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000142}
143
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000144int
145_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000146{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200147 unsigned long me = PyThread_get_thread_ident();
148 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 return 0; /* Too bad */
150 if (import_lock_thread != me)
151 return -1;
152 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100153 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200155 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 PyThread_release_lock(import_lock);
157 }
158 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000159}
160
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900161#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200162/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000163 created child processes do not share locks with the parent.
164 We now acquire the import lock around fork() calls but on some platforms
165 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200166PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000167_PyImport_ReInitLock(void)
168{
Christian Heimes418fd742015-04-19 21:08:42 +0200169 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900170 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200171 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200172 }
173 }
Victor Stinner26881c82020-06-02 15:51:37 +0200174
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000175 if (import_lock_level > 1) {
176 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200177 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200178 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000179 import_lock_thread = me;
180 import_lock_level--;
181 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200182 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000183 import_lock_level = 0;
184 }
Victor Stinner26881c82020-06-02 15:51:37 +0200185 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000186}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900187#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000188
Brett Cannon4caa61d2014-01-09 19:03:32 -0500189/*[clinic input]
190_imp.lock_held
191
192Return True if the import lock is currently held, else False.
193
194On platforms without threads, return False.
195[clinic start generated code]*/
196
Brett Cannon4caa61d2014-01-09 19:03:32 -0500197static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300198_imp_lock_held_impl(PyObject *module)
199/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000200{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200201 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000202}
203
Brett Cannon4caa61d2014-01-09 19:03:32 -0500204/*[clinic input]
205_imp.acquire_lock
206
207Acquires the interpreter's import lock for the current thread.
208
209This lock should be used by import hooks to ensure thread-safety when importing
210modules. On platforms without threads, this function does nothing.
211[clinic start generated code]*/
212
Brett Cannon4caa61d2014-01-09 19:03:32 -0500213static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300214_imp_acquire_lock_impl(PyObject *module)
215/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200218 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000219}
220
Brett Cannon4caa61d2014-01-09 19:03:32 -0500221/*[clinic input]
222_imp.release_lock
223
224Release the interpreter's import lock.
225
226On platforms without threads, this function does nothing.
227[clinic start generated code]*/
228
Brett Cannon4caa61d2014-01-09 19:03:32 -0500229static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300230_imp_release_lock_impl(PyObject *module)
231/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (_PyImport_ReleaseLock() < 0) {
234 PyErr_SetString(PyExc_RuntimeError,
235 "not holding the import lock");
236 return NULL;
237 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200238 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000239}
240
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100241void
242_PyImport_Fini(void)
243{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200244 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100245 if (import_lock != NULL) {
246 PyThread_free_lock(import_lock);
247 import_lock = NULL;
248 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100249}
250
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100251void
252_PyImport_Fini2(void)
253{
254 /* Use the same memory allocator than PyImport_ExtendInittab(). */
255 PyMemAllocatorEx old_alloc;
256 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
257
258 /* Free memory allocated by PyImport_ExtendInittab() */
259 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700260 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100261
262 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
263}
264
Guido van Rossum25ce5661997-08-02 03:10:38 +0000265/* Helper for sys */
266
267PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000268PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000269{
Victor Stinner81a7be32020-04-14 15:14:01 +0200270 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600271 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100272 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600273 }
Eric Snow93c92f72017-09-13 23:46:04 -0700274 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275}
276
Eric Snowd393c1b2017-09-14 12:18:12 -0600277/* In some corner cases it is important to be sure that the import
278 machinery has been initialized (or not cleaned up yet). For
279 example, see issue #4236 and PyModule_Create2(). */
280
281int
282_PyImport_IsInitialized(PyInterpreterState *interp)
283{
284 if (interp->modules == NULL)
285 return 0;
286 return 1;
287}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000288
Eric Snow3f9eee62017-09-15 16:35:20 -0600289PyObject *
290_PyImport_GetModuleId(struct _Py_Identifier *nameid)
291{
292 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
293 if (name == NULL) {
294 return NULL;
295 }
296 return PyImport_GetModule(name);
297}
298
299int
300_PyImport_SetModule(PyObject *name, PyObject *m)
301{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100302 PyInterpreterState *interp = _PyInterpreterState_GET();
303 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600304 return PyObject_SetItem(modules, name, m);
305}
306
307int
308_PyImport_SetModuleString(const char *name, PyObject *m)
309{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100310 PyInterpreterState *interp = _PyInterpreterState_GET();
311 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600312 return PyMapping_SetItemString(modules, name, m);
313}
314
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200315static PyObject *
316import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600317{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200318 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600319 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200320 _PyErr_SetString(tstate, PyExc_RuntimeError,
321 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600322 return NULL;
323 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200324
325 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600326 Py_INCREF(modules);
327 if (PyDict_CheckExact(modules)) {
328 m = PyDict_GetItemWithError(modules, name); /* borrowed */
329 Py_XINCREF(m);
330 }
331 else {
332 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200333 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
334 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600335 }
336 }
337 Py_DECREF(modules);
338 return m;
339}
340
341
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100342static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100343import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200344{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100345 PyObject *spec;
346
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100347 _Py_IDENTIFIER(_lock_unlock_module);
348
349 /* Optimization: only call _bootstrap._lock_unlock_module() if
350 __spec__._initializing is true.
351 NOTE: because of this, initializing must be set *before*
352 stuffing the new module in sys.modules.
353 */
354 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
355 int busy = _PyModuleSpec_IsInitializing(spec);
356 Py_XDECREF(spec);
357 if (busy) {
358 /* Wait until module is done importing. */
359 PyObject *value = _PyObject_CallMethodIdOneArg(
360 interp->importlib, &PyId__lock_unlock_module, name);
361 if (value == NULL) {
362 return -1;
363 }
364 Py_DECREF(value);
365 }
366 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200367}
368
369
Barry Warsaw28a691b2010-04-17 00:19:56 +0000370/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000371
372long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000373PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000374{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200375 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200376 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600377 PyObject *external, *pyc_magic;
378
379 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
380 if (external == NULL)
381 return -1;
382 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
383 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400384 if (pyc_magic == NULL)
385 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200386 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700387 Py_DECREF(pyc_magic);
388 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000389}
390
391
Brett Cannon3adc7b72012-07-09 14:22:12 -0400392extern const char * _PySys_ImplCacheTag;
393
Barry Warsaw28a691b2010-04-17 00:19:56 +0000394const char *
395PyImport_GetMagicTag(void)
396{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400397 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000398}
399
Brett Cannon98979b82012-07-02 15:13:11 -0400400
Guido van Rossum25ce5661997-08-02 03:10:38 +0000401/* Magic for extension modules (built-in as well as dynamically
402 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200403 once, we keep a static dictionary 'extensions' keyed by the tuple
404 (module name, module name) (for built-in modules) or by
405 (filename, module name) (for dynamically loaded modules), containing these
406 modules. A copy of the module's dictionary is stored by calling
407 _PyImport_FixupExtensionObject() immediately after the module initialization
408 function succeeds. A copy can be retrieved from there by calling
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200409 import_find_extension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000410
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000411 Modules which do support multiple initialization set their m_size
412 field to a non-negative number (indicating the size of the
413 module-specific state). They are still recorded in the extensions
414 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000415*/
416
417int
Victor Stinner95872862011-03-07 18:20:56 +0100418_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200419 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (mod == NULL || !PyModule_Check(mod)) {
422 PyErr_BadInternalCall();
423 return -1;
424 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100425
426 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (!def) {
428 PyErr_BadInternalCall();
429 return -1;
430 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100431
432 PyThreadState *tstate = _PyThreadState_GET();
433 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100435 }
436 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600437 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 return -1;
439 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100440
Victor Stinner101bf692021-02-19 13:33:31 +0100441 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner82c83bd2019-11-22 18:52:27 +0100442 if (def->m_size == -1) {
443 if (def->m_base.m_copy) {
444 /* Somebody already imported the module,
445 likely under a different name.
446 XXX this should really not happen. */
447 Py_CLEAR(def->m_base.m_copy);
448 }
449 PyObject *dict = PyModule_GetDict(mod);
450 if (dict == NULL) {
451 return -1;
452 }
453 def->m_base.m_copy = PyDict_Copy(dict);
454 if (def->m_base.m_copy == NULL) {
455 return -1;
456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100458
459 if (extensions == NULL) {
460 extensions = PyDict_New();
461 if (extensions == NULL) {
462 return -1;
463 }
464 }
465
466 PyObject *key = PyTuple_Pack(2, filename, name);
467 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100469 }
470 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
471 Py_DECREF(key);
472 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100474 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000478}
479
Victor Stinner49d3f252010-10-17 01:24:53 +0000480int
Eric Snowd393c1b2017-09-14 12:18:12 -0600481_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000482{
483 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100484 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100485 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100486 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000487 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600488 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100489 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000490 return res;
491}
492
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200493static PyObject *
494import_find_extension(PyThreadState *tstate, PyObject *name,
495 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000496{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200497 if (extensions == NULL) {
498 return NULL;
499 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600500
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200501 PyObject *key = PyTuple_Pack(2, filename, name);
502 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200504 }
505 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500506 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200507 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200509 }
510
511 PyObject *mod, *mdict;
512 PyObject *modules = tstate->interp->modules;
513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (def->m_size == -1) {
515 /* Module does not support repeated initialization */
516 if (def->m_base.m_copy == NULL)
517 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200518 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (mod == NULL)
520 return NULL;
521 mdict = PyModule_GetDict(mod);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200522 if (mdict == NULL) {
523 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200525 }
526 if (PyDict_Update(mdict, def->m_base.m_copy)) {
527 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200529 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 }
531 else {
532 if (def->m_base.m_init == NULL)
533 return NULL;
534 mod = def->m_base.m_init();
535 if (mod == NULL)
536 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600537 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200538 Py_DECREF(mod);
539 return NULL;
540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100542 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600543 PyMapping_DelItem(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200544 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 return NULL;
546 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200547
Victor Stinnerda7933e2020-04-13 03:04:28 +0200548 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200549 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100550 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200551 name, filename);
552 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000554}
555
556
557/* Get the module object corresponding to a module name.
558 First check the modules dictionary if there's one there,
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200559 if not, create a new one and insert it in the modules dictionary. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000560
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200561static PyObject *
562import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000563{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200564 PyObject *modules = tstate->interp->modules;
565 if (modules == NULL) {
566 _PyErr_SetString(tstate, PyExc_RuntimeError,
567 "no import module dictionary");
568 return NULL;
569 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600570
Eric Snow86b7afd2017-09-04 17:54:09 -0600571 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600572 if (PyDict_CheckExact(modules)) {
573 m = PyDict_GetItemWithError(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200574 Py_XINCREF(m);
Eric Snow3f9eee62017-09-15 16:35:20 -0600575 }
576 else {
577 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000578 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600579 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200580 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
581 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600582 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200583 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200584 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200585 return NULL;
586 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600587 if (m != NULL && PyModule_Check(m)) {
588 return m;
589 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200590 Py_XDECREF(m);
Victor Stinner27ee0892011-03-04 12:57:09 +0000591 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (m == NULL)
593 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600594 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 Py_DECREF(m);
596 return NULL;
597 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000600}
601
Victor Stinner27ee0892011-03-04 12:57:09 +0000602PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200603PyImport_AddModuleObject(PyObject *name)
604{
605 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200606 PyObject *mod = import_add_module(tstate, name);
607 if (mod) {
608 PyObject *ref = PyWeakref_NewRef(mod, NULL);
609 Py_DECREF(mod);
610 if (ref == NULL) {
611 return NULL;
612 }
613 mod = PyWeakref_GetObject(ref);
614 Py_DECREF(ref);
615 }
616 return mod; /* borrowed reference */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200617}
618
619
620PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000621PyImport_AddModule(const char *name)
622{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200623 PyObject *nameobj = PyUnicode_FromString(name);
624 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000625 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200626 }
627 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000628 Py_DECREF(nameobj);
629 return module;
630}
631
632
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300633/* Remove name from sys.modules, if it's there.
634 * Can be called with an exception raised.
635 * If fail to remove name a new exception will be chained with the old
636 * exception, otherwise the old exception is preserved.
637 */
Tim Peters1cd70172004-08-02 03:52:12 +0000638static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200639remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000640{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600641 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200642 _PyErr_Fetch(tstate, &type, &value, &traceback);
643
644 PyObject *modules = tstate->interp->modules;
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300645 if (PyDict_CheckExact(modules)) {
646 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
647 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600648 }
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300649 else if (PyMapping_DelItem(modules, name) < 0) {
650 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
651 _PyErr_Clear(tstate);
652 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600653 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200654
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300655 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000656}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000657
Christian Heimes3b06e532008-01-07 20:12:44 +0000658
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000659/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000660 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
661 * removed from sys.modules, to avoid leaving damaged module objects
662 * in sys.modules. The caller may wish to restore the original
663 * module object (if any) in this case; PyImport_ReloadModule is an
664 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000665 *
666 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
667 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000668 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000669PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300670PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return PyImport_ExecCodeModuleWithPathnames(
673 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000674}
675
676PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300677PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return PyImport_ExecCodeModuleWithPathnames(
680 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000681}
682
683PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300684PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
685 const char *pathname,
686 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000687{
Victor Stinner27ee0892011-03-04 12:57:09 +0000688 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600689 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000690
691 nameobj = PyUnicode_FromString(name);
692 if (nameobj == NULL)
693 return NULL;
694
Victor Stinner27ee0892011-03-04 12:57:09 +0000695 if (cpathname != NULL) {
696 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
697 if (cpathobj == NULL)
698 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400699 }
700 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000701 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400702
703 if (pathname != NULL) {
704 pathobj = PyUnicode_DecodeFSDefault(pathname);
705 if (pathobj == NULL)
706 goto error;
707 }
708 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200709 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400710 _Py_IDENTIFIER(_get_sourcefile);
711
712 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100713 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400714 }
715
Eric Snow32439d62015-05-02 19:15:18 -0600716 external= PyObject_GetAttrString(interp->importlib,
717 "_bootstrap_external");
718 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200719 pathobj = _PyObject_CallMethodIdOneArg(
720 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600721 Py_DECREF(external);
722 }
Brett Cannona6473f92012-07-13 13:57:03 -0400723 if (pathobj == NULL)
724 PyErr_Clear();
725 }
726 else
727 pathobj = NULL;
728
Victor Stinner27ee0892011-03-04 12:57:09 +0000729 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
730error:
731 Py_DECREF(nameobj);
732 Py_XDECREF(pathobj);
733 Py_XDECREF(cpathobj);
734 return m;
735}
736
Brett Cannon18fc4e72014-04-04 10:01:46 -0400737static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200738module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000739{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200740 _Py_IDENTIFIER(__builtins__);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200741 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000742
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200743 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (m == NULL)
745 return NULL;
746 /* If the module is being reloaded, we get the old module back
747 and re-use its dict to exec the new code. */
748 d = PyModule_GetDict(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200749 int r = _PyDict_ContainsId(d, &PyId___builtins__);
750 if (r == 0) {
751 r = _PyDict_SetItemId(d, &PyId___builtins__,
752 PyEval_GetBuiltins());
753 }
754 if (r < 0) {
755 remove_module(tstate, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200756 Py_DECREF(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200757 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400759
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200760 Py_INCREF(d);
761 Py_DECREF(m);
762 return d;
Brett Cannon18fc4e72014-04-04 10:01:46 -0400763}
764
765static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200766exec_code_in_module(PyThreadState *tstate, PyObject *name,
767 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -0400768{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400769 PyObject *v, *m;
770
771 v = PyEval_EvalCode(code_object, module_dict, module_dict);
772 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200773 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400774 return NULL;
775 }
776 Py_DECREF(v);
777
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200778 m = import_get_module(tstate, name);
779 if (m == NULL && !_PyErr_Occurred(tstate)) {
780 _PyErr_Format(tstate, PyExc_ImportError,
781 "Loaded module %R not found in sys.modules",
782 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400783 }
784
Brett Cannon18fc4e72014-04-04 10:01:46 -0400785 return m;
786}
787
788PyObject*
789PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
790 PyObject *cpathname)
791{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200792 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600793 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600794 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400795
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200796 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400797 if (d == NULL) {
798 return NULL;
799 }
800
Eric Snow08197a42014-05-12 17:54:55 -0600801 if (pathname == NULL) {
802 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200804 external = PyObject_GetAttrString(tstate->interp->importlib,
805 "_bootstrap_external");
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200806 if (external == NULL) {
807 Py_DECREF(d);
Eric Snow32439d62015-05-02 19:15:18 -0600808 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200809 }
Eric Snow32439d62015-05-02 19:15:18 -0600810 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600811 &PyId__fix_up_module,
812 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600813 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600814 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600815 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200816 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200818 Py_DECREF(d);
Eric Snow08197a42014-05-12 17:54:55 -0600819 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000820}
821
822
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000823static void
824update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyObject *constants, *tmp;
827 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (PyUnicode_Compare(co->co_filename, oldname))
830 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000831
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200832 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300833 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 constants = co->co_consts;
836 n = PyTuple_GET_SIZE(constants);
837 for (i = 0; i < n; i++) {
838 tmp = PyTuple_GET_ITEM(constants, i);
839 if (PyCode_Check(tmp))
840 update_code_filenames((PyCodeObject *)tmp,
841 oldname, newname);
842 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000843}
844
Victor Stinner2f42ae52011-03-20 00:41:24 +0100845static void
846update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000847{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100848 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000849
Victor Stinner2f42ae52011-03-20 00:41:24 +0100850 if (PyUnicode_Compare(co->co_filename, newname) == 0)
851 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 oldname = co->co_filename;
854 Py_INCREF(oldname);
855 update_code_filenames(co, oldname, newname);
856 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000857}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000858
Brett Cannon4caa61d2014-01-09 19:03:32 -0500859/*[clinic input]
860_imp._fix_co_filename
861
862 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
863 Code object to change.
864
865 path: unicode
866 File path to use.
867 /
868
869Changes code.co_filename to specify the passed-in file path.
870[clinic start generated code]*/
871
Brett Cannon4caa61d2014-01-09 19:03:32 -0500872static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300873_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400874 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300875/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700876
Brett Cannon4caa61d2014-01-09 19:03:32 -0500877{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500878 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700879
880 Py_RETURN_NONE;
881}
882
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000884/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700885static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000886
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000887
888/* Helper to test for built-in module */
889
890static int
Victor Stinner95872862011-03-07 18:20:56 +0100891is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000892{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200893 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200895 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (PyImport_Inittab[i].initfunc == NULL)
897 return -1;
898 else
899 return 1;
900 }
901 }
902 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000903}
904
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000905
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700906/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000907 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000908 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000909 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700910 this tells our caller that the path based finder could not find
911 a finder for this path item. Cache the result in
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200912 path_importer_cache. */
Just van Rossum52e14d62002-12-30 22:08:05 +0000913
914static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200915get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
916 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyObject *importer;
919 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* These conditions are the caller's responsibility: */
922 assert(PyList_Check(path_hooks));
923 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 nhooks = PyList_Size(path_hooks);
926 if (nhooks < 0)
927 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000928
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200929 importer = PyDict_GetItemWithError(path_importer_cache, p);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200930 if (importer != NULL || _PyErr_Occurred(tstate)) {
931 Py_XINCREF(importer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 return importer;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200933 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* set path_importer_cache[p] to None to avoid recursion */
936 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
937 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 for (j = 0; j < nhooks; j++) {
940 PyObject *hook = PyList_GetItem(path_hooks, j);
941 if (hook == NULL)
942 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +0100943 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (importer != NULL)
945 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000946
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200947 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return NULL;
949 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200950 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 }
952 if (importer == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200953 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200955 if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 Py_DECREF(importer);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200957 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 }
959 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000960}
961
Benjamin Petersone5024512018-09-12 12:06:42 -0700962PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200963PyImport_GetImporter(PyObject *path)
964{
965 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200966 PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
967 PyObject *path_hooks = PySys_GetObject("path_hooks");
968 if (path_importer_cache == NULL || path_hooks == NULL) {
969 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200971 return get_path_importer(tstate, path_importer_cache, path_hooks, path);
Christian Heimes9cd17752007-11-18 19:35:23 +0000972}
973
Victor Stinner62230712020-11-18 23:18:29 +0100974static PyObject*
975create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
976{
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200977 PyObject *mod = import_find_extension(tstate, name, name);
Victor Stinner62230712020-11-18 23:18:29 +0100978 if (mod || _PyErr_Occurred(tstate)) {
Victor Stinner62230712020-11-18 23:18:29 +0100979 return mod;
980 }
981
982 PyObject *modules = tstate->interp->modules;
983 for (struct _inittab *p = PyImport_Inittab; p->name != NULL; p++) {
984 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
985 if (p->initfunc == NULL) {
986 /* Cannot re-init internal module ("sys" or "builtins") */
987 return PyImport_AddModuleObject(name);
988 }
989
990 mod = (*p->initfunc)();
991 if (mod == NULL) {
992 return NULL;
993 }
994
995 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
996 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
997 }
998 else {
999 /* Remember pointer to module init function. */
1000 PyModuleDef *def = PyModule_GetDef(mod);
1001 if (def == NULL) {
1002 return NULL;
1003 }
1004
1005 def->m_base.m_init = p->initfunc;
1006 if (_PyImport_FixupExtensionObject(mod, name, name,
1007 modules) < 0) {
1008 return NULL;
1009 }
1010 return mod;
1011 }
1012 }
1013 }
1014
1015 // not found
1016 Py_RETURN_NONE;
1017}
1018
1019
1020
Nick Coghland5cacbb2015-05-23 22:24:10 +10001021/*[clinic input]
1022_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001023
Nick Coghland5cacbb2015-05-23 22:24:10 +10001024 spec: object
1025 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001026
Nick Coghland5cacbb2015-05-23 22:24:10 +10001027Create an extension module.
1028[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001029
Nick Coghland5cacbb2015-05-23 22:24:10 +10001030static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001031_imp_create_builtin(PyObject *module, PyObject *spec)
1032/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001033{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001034 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001035
Victor Stinner62230712020-11-18 23:18:29 +01001036 PyObject *name = PyObject_GetAttrString(spec, "name");
Nick Coghland5cacbb2015-05-23 22:24:10 +10001037 if (name == NULL) {
1038 return NULL;
1039 }
1040
Victor Stinner62230712020-11-18 23:18:29 +01001041 PyObject *mod = create_builtin(tstate, name, spec);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001042 Py_DECREF(name);
Victor Stinner62230712020-11-18 23:18:29 +01001043 return mod;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001044}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001045
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001046
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001047/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001049static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001050find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001051{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001052 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001053
Victor Stinner53dc7352011-03-20 01:50:21 +01001054 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 for (p = PyImport_FrozenModules; ; p++) {
1058 if (p->name == NULL)
1059 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001060 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 break;
1062 }
1063 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001064}
1065
Guido van Rossum79f25d91997-04-29 20:08:16 +00001066static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001067get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001068{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001069 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (p == NULL) {
1073 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001074 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 name);
1076 return NULL;
1077 }
1078 if (p->code == NULL) {
1079 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001080 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 name);
1082 return NULL;
1083 }
1084 size = p->size;
1085 if (size < 0)
1086 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001087 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001088}
1089
Brett Cannon8d110132009-03-15 02:20:16 +00001090static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001091is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001092{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001093 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (p == NULL) {
1097 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001098 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 name);
1100 return NULL;
1101 }
Brett Cannon8d110132009-03-15 02:20:16 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (size < 0)
1106 Py_RETURN_TRUE;
1107 else
1108 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001109}
1110
1111
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001112/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001113 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001114 an exception set if the initialization failed.
1115 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001116
1117int
Victor Stinner53dc7352011-03-20 01:50:21 +01001118PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001119{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001120 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001121 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001122 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 int ispackage;
1124 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001125
Victor Stinner53dc7352011-03-20 01:50:21 +01001126 p = find_frozen(name);
1127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (p == NULL)
1129 return 0;
1130 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001131 _PyErr_Format(tstate, PyExc_ImportError,
1132 "Excluded frozen object named %R",
1133 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 return -1;
1135 }
1136 size = p->size;
1137 ispackage = (size < 0);
1138 if (ispackage)
1139 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001140 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (co == NULL)
1142 return -1;
1143 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001144 _PyErr_Format(tstate, PyExc_TypeError,
1145 "frozen object %R is not a code object",
1146 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 goto err_return;
1148 }
1149 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001150 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001151 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001153 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (m == NULL)
1155 goto err_return;
1156 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001157 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (l == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001159 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 goto err_return;
1161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 err = PyDict_SetItemString(d, "__path__", l);
1163 Py_DECREF(l);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001164 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (err != 0)
1166 goto err_return;
1167 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001168 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001169 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001170 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001171 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001172 m = exec_code_in_module(tstate, name, d, co);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001173 Py_DECREF(d);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001174 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001176 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 Py_DECREF(co);
1178 Py_DECREF(m);
1179 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001180
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001181err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_DECREF(co);
1183 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001184}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001185
Victor Stinner53dc7352011-03-20 01:50:21 +01001186int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001187PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001188{
1189 PyObject *nameobj;
1190 int ret;
1191 nameobj = PyUnicode_InternFromString(name);
1192 if (nameobj == NULL)
1193 return -1;
1194 ret = PyImport_ImportFrozenModuleObject(nameobj);
1195 Py_DECREF(nameobj);
1196 return ret;
1197}
1198
Guido van Rossum74e6a111994-08-29 12:54:38 +00001199
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001200/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001201 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001202
Guido van Rossum79f25d91997-04-29 20:08:16 +00001203PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001204PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 PyObject *pname;
1207 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 pname = PyUnicode_FromString(name);
1210 if (pname == NULL)
1211 return NULL;
1212 result = PyImport_Import(pname);
1213 Py_DECREF(pname);
1214 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001215}
1216
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001217
Christian Heimes072c0f12008-01-03 23:01:04 +00001218/* Import a module without blocking
1219 *
1220 * At first it tries to fetch the module from sys.modules. If the module was
1221 * never loaded before it loads it with PyImport_ImportModule() unless another
1222 * thread holds the import lock. In the latter case the function raises an
1223 * ImportError instead of blocking.
1224 *
1225 * Returns the module object with incremented ref count.
1226 */
1227PyObject *
1228PyImport_ImportModuleNoBlock(const char *name)
1229{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001230 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001231}
1232
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001233
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001234/* Remove importlib frames from the traceback,
1235 * except in Verbose mode. */
1236static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001237remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001238{
1239 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001240 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001241 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001242 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001243 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001244 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001245 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001246
1247 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001248 from the traceback. We always trim chunks
1249 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001250
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001251 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001252 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001253 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001254 }
1255
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001256 if (PyType_IsSubtype((PyTypeObject *) exception,
1257 (PyTypeObject *) PyExc_ImportError))
1258 always_trim = 1;
1259
1260 prev_link = &base_tb;
1261 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001262 while (tb != NULL) {
1263 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1264 PyObject *next = (PyObject *) traceback->tb_next;
1265 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001266 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001267 int now_in_importlib;
1268
1269 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001270 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1271 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001272 if (now_in_importlib && !in_importlib) {
1273 /* This is the link to this chunk of importlib tracebacks */
1274 outer_link = prev_link;
1275 }
1276 in_importlib = now_in_importlib;
1277
1278 if (in_importlib &&
1279 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001280 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001281 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001282 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001283 prev_link = outer_link;
1284 }
1285 else {
1286 prev_link = (PyObject **) &traceback->tb_next;
1287 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001288 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001289 tb = next;
1290 }
1291done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001292 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001293}
1294
1295
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001296static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001297resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001298{
Brett Cannonfd074152012-04-14 14:10:13 -04001299 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001300 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001301 _Py_IDENTIFIER(parent);
1302 PyObject *abs_name;
1303 PyObject *package = NULL;
1304 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001305 Py_ssize_t last_dot;
1306 PyObject *base;
1307 int level_up;
1308
1309 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001310 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001311 goto error;
1312 }
1313 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001314 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001315 goto error;
1316 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001317 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001318 if (package == Py_None) {
1319 package = NULL;
1320 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001321 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001322 goto error;
1323 }
1324 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001325 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001326 goto error;
1327 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001328
1329 if (package != NULL) {
1330 Py_INCREF(package);
1331 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001332 _PyErr_SetString(tstate, PyExc_TypeError,
1333 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001334 goto error;
1335 }
1336 else if (spec != NULL && spec != Py_None) {
1337 int equal;
1338 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1339 if (parent == NULL) {
1340 goto error;
1341 }
1342
1343 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1344 Py_DECREF(parent);
1345 if (equal < 0) {
1346 goto error;
1347 }
1348 else if (equal == 0) {
1349 if (PyErr_WarnEx(PyExc_ImportWarning,
1350 "__package__ != __spec__.parent", 1) < 0) {
1351 goto error;
1352 }
1353 }
1354 }
1355 }
1356 else if (spec != NULL && spec != Py_None) {
1357 package = _PyObject_GetAttrId(spec, &PyId_parent);
1358 if (package == NULL) {
1359 goto error;
1360 }
1361 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001362 _PyErr_SetString(tstate, PyExc_TypeError,
1363 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001364 goto error;
1365 }
1366 }
1367 else {
1368 if (PyErr_WarnEx(PyExc_ImportWarning,
1369 "can't resolve package from __spec__ or __package__, "
1370 "falling back on __name__ and __path__", 1) < 0) {
1371 goto error;
1372 }
1373
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001374 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001375 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001376 if (!_PyErr_Occurred(tstate)) {
1377 _PyErr_SetString(tstate, PyExc_KeyError,
1378 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001379 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001380 goto error;
1381 }
1382
1383 Py_INCREF(package);
1384 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001385 _PyErr_SetString(tstate, PyExc_TypeError,
1386 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001387 goto error;
1388 }
1389
Serhiy Storchakab510e102020-10-26 12:47:57 +02001390 int haspath = _PyDict_ContainsId(globals, &PyId___path__);
1391 if (haspath < 0) {
1392 goto error;
1393 }
1394 if (!haspath) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001395 Py_ssize_t dot;
1396
Serhiy Storchakab510e102020-10-26 12:47:57 +02001397 if (PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001398 goto error;
1399 }
1400
1401 dot = PyUnicode_FindChar(package, '.',
1402 0, PyUnicode_GET_LENGTH(package), -1);
1403 if (dot == -2) {
1404 goto error;
1405 }
Ben Lewis92420b32019-09-11 20:09:47 +10001406 else if (dot == -1) {
1407 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001408 }
Ben Lewis92420b32019-09-11 20:09:47 +10001409 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1410 if (substr == NULL) {
1411 goto error;
1412 }
1413 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001414 }
1415 }
1416
1417 last_dot = PyUnicode_GET_LENGTH(package);
1418 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001419 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001420 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001421
1422 for (level_up = 1; level_up < level; level_up += 1) {
1423 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1424 if (last_dot == -2) {
1425 goto error;
1426 }
1427 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001428 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001429 "attempted relative import beyond top-level "
1430 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001431 goto error;
1432 }
1433 }
1434
1435 base = PyUnicode_Substring(package, 0, last_dot);
1436 Py_DECREF(package);
1437 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1438 return base;
1439 }
1440
1441 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1442 Py_DECREF(base);
1443 return abs_name;
1444
Ben Lewis92420b32019-09-11 20:09:47 +10001445 no_parent_error:
1446 _PyErr_SetString(tstate, PyExc_ImportError,
1447 "attempted relative import "
1448 "with no known parent package");
1449
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001450 error:
1451 Py_XDECREF(package);
1452 return NULL;
1453}
1454
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001455static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001456import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001457{
1458 _Py_IDENTIFIER(_find_and_load);
1459 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001460 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001461 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001462 static int import_level;
1463 static _PyTime_t accumulated;
1464
1465 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1466
Steve Dowerb82e17e2019-05-23 08:45:22 -07001467 PyObject *sys_path = PySys_GetObject("path");
1468 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1469 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001470 if (_PySys_Audit(tstate, "import", "OOOOO",
1471 abs_name, Py_None, sys_path ? sys_path : Py_None,
1472 sys_meta_path ? sys_meta_path : Py_None,
1473 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001474 return NULL;
1475 }
1476
1477
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001478 /* XOptions is initialized after first some imports.
1479 * So we can't have negative cache before completed initialization.
1480 * Anyway, importlib._find_and_load is much slower than
1481 * _PyDict_GetItemIdWithError().
1482 */
1483 if (import_time) {
1484 static int header = 1;
1485 if (header) {
1486 fputs("import time: self [us] | cumulative | imported package\n",
1487 stderr);
1488 header = 0;
1489 }
1490
1491 import_level++;
1492 t1 = _PyTime_GetPerfCounter();
1493 accumulated = 0;
1494 }
1495
1496 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001497 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001498
1499 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1500 &PyId__find_and_load, abs_name,
1501 interp->import_func, NULL);
1502
1503 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001504 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001505 mod != NULL);
1506
1507 if (import_time) {
1508 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1509
1510 import_level--;
1511 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1512 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1513 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1514 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1515
1516 accumulated = accumulated_copy + cum;
1517 }
1518
1519 return mod;
1520}
1521
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001522PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001523PyImport_GetModule(PyObject *name)
1524{
1525 PyThreadState *tstate = _PyThreadState_GET();
1526 PyObject *mod;
1527
1528 mod = import_get_module(tstate, name);
1529 if (mod != NULL && mod != Py_None) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001530 if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001531 Py_DECREF(mod);
1532 remove_importlib_frames(tstate);
1533 return NULL;
1534 }
1535 }
1536 return mod;
1537}
1538
1539PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001540PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1541 PyObject *locals, PyObject *fromlist,
1542 int level)
1543{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001544 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001545 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001546 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001547 PyObject *final_mod = NULL;
1548 PyObject *mod = NULL;
1549 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001550 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001551 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001552
Brett Cannonfd074152012-04-14 14:10:13 -04001553 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001554 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001555 goto error;
1556 }
1557
1558 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1559 for added performance. */
1560
1561 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001562 _PyErr_SetString(tstate, PyExc_TypeError,
1563 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001564 goto error;
1565 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001566 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001567 goto error;
1568 }
1569 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001570 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001571 goto error;
1572 }
Brett Cannon849113a2016-01-22 15:25:50 -08001573
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001574 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001575 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001576 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001577 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001578 }
1579 else { /* level == 0 */
1580 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001581 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001582 goto error;
1583 }
Brett Cannonfd074152012-04-14 14:10:13 -04001584 abs_name = name;
1585 Py_INCREF(abs_name);
1586 }
1587
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001588 mod = import_get_module(tstate, abs_name);
1589 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001590 goto error;
1591 }
1592
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001593 if (mod != NULL && mod != Py_None) {
Antoine Pitrou2fd16ef2021-03-20 20:07:44 +01001594 if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001595 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001596 }
Brett Cannonfd074152012-04-14 14:10:13 -04001597 }
1598 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001599 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001600 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001601 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001602 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001603 }
1604 }
1605
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001606 has_from = 0;
1607 if (fromlist != NULL && fromlist != Py_None) {
1608 has_from = PyObject_IsTrue(fromlist);
1609 if (has_from < 0)
1610 goto error;
1611 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001612 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001613 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1614 if (level == 0 || len > 0) {
1615 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001616
Victor Stinner744c34e2016-05-20 11:36:13 +02001617 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1618 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001619 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001620 }
1621
Victor Stinner744c34e2016-05-20 11:36:13 +02001622 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001623 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001624 final_mod = mod;
1625 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001626 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001627 }
1628
Brett Cannonfd074152012-04-14 14:10:13 -04001629 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001630 PyObject *front = PyUnicode_Substring(name, 0, dot);
1631 if (front == NULL) {
1632 goto error;
1633 }
1634
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001635 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001636 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001637 }
1638 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001639 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001640 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001641 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001642 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001643 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001644 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001645 }
Brett Cannonfd074152012-04-14 14:10:13 -04001646
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001647 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001648 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001649 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001650 if (!_PyErr_Occurred(tstate)) {
1651 _PyErr_Format(tstate, PyExc_KeyError,
1652 "%R not in sys.modules as expected",
1653 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001654 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001655 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001656 }
Brett Cannonfd074152012-04-14 14:10:13 -04001657 }
1658 }
1659 else {
1660 final_mod = mod;
1661 Py_INCREF(mod);
1662 }
1663 }
1664 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001665 PyObject *path;
1666 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1667 goto error;
1668 }
1669 if (path) {
1670 Py_DECREF(path);
1671 final_mod = _PyObject_CallMethodIdObjArgs(
1672 interp->importlib, &PyId__handle_fromlist,
1673 mod, fromlist, interp->import_func, NULL);
1674 }
1675 else {
1676 final_mod = mod;
1677 Py_INCREF(mod);
1678 }
Brett Cannonfd074152012-04-14 14:10:13 -04001679 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001680
Brett Cannonfd074152012-04-14 14:10:13 -04001681 error:
1682 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001683 Py_XDECREF(mod);
1684 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001685 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001686 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001687 }
Brett Cannonfd074152012-04-14 14:10:13 -04001688 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001689}
1690
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001691PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001692PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001693 PyObject *fromlist, int level)
1694{
1695 PyObject *nameobj, *mod;
1696 nameobj = PyUnicode_FromString(name);
1697 if (nameobj == NULL)
1698 return NULL;
1699 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1700 fromlist, level);
1701 Py_DECREF(nameobj);
1702 return mod;
1703}
1704
1705
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001706/* Re-import a module of any kind and return its module object, WITH
1707 INCREMENTED REFERENCE COUNT */
1708
Guido van Rossum79f25d91997-04-29 20:08:16 +00001709PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001710PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001711{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001712 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001713 _Py_IDENTIFIER(reload);
1714 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001715 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1716 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001717 if (PyErr_Occurred()) {
1718 return NULL;
1719 }
1720
Robert Rouhanif40bd462020-05-01 16:28:06 -07001721 importlib = PyImport_ImportModule("importlib");
1722 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001723 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001726
Robert Rouhanif40bd462020-05-01 16:28:06 -07001727 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1728 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001729 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001730}
1731
1732
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001733/* Higher-level import emulator which emulates the "import" statement
1734 more accurately -- it invokes the __import__() function from the
1735 builtins of the current globals. This means that the import is
1736 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001737 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001738 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001739 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001740 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001741
1742PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001743PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001744{
junyixie88d99832021-03-22 17:47:10 +08001745 _Py_IDENTIFIER(__import__);
1746 _Py_IDENTIFIER(__builtins__);
1747
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001748 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 PyObject *globals = NULL;
1750 PyObject *import = NULL;
1751 PyObject *builtins = NULL;
1752 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* Initialize constant string objects */
junyixie88d99832021-03-22 17:47:10 +08001755 PyObject *import_str = _PyUnicode_FromId(&PyId___import__); // borrowed ref
1756 if (import_str == NULL) {
1757 return NULL;
1758 }
1759
1760 PyObject *builtins_str = _PyUnicode_FromId(&PyId___builtins__); // borrowed ref
1761 if (builtins_str == NULL) {
1762 return NULL;
1763 }
1764
1765 PyObject *from_list = PyList_New(0);
1766 if (from_list == NULL) {
1767 goto err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 /* Get the builtins from current globals */
1771 globals = PyEval_GetGlobals();
1772 if (globals != NULL) {
1773 Py_INCREF(globals);
1774 builtins = PyObject_GetItem(globals, builtins_str);
1775 if (builtins == NULL)
1776 goto err;
1777 }
1778 else {
1779 /* No globals -- use standard builtins, and fake globals */
1780 builtins = PyImport_ImportModuleLevel("builtins",
1781 NULL, NULL, NULL, 0);
junyixie88d99832021-03-22 17:47:10 +08001782 if (builtins == NULL) {
1783 goto err;
1784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1786 if (globals == NULL)
1787 goto err;
1788 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* Get the __import__ function from the builtins */
1791 if (PyDict_Check(builtins)) {
1792 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001793 if (import == NULL) {
1794 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
1795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 }
1797 else
1798 import = PyObject_GetAttr(builtins, import_str);
1799 if (import == NULL)
1800 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001803 Always use absolute import here.
1804 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
junyixie88d99832021-03-22 17:47:10 +08001806 globals, from_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001807 if (r == NULL)
1808 goto err;
1809 Py_DECREF(r);
1810
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001811 r = import_get_module(tstate, module_name);
1812 if (r == NULL && !_PyErr_Occurred(tstate)) {
1813 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001814 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001815
1816 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 Py_XDECREF(globals);
1818 Py_XDECREF(builtins);
1819 Py_XDECREF(import);
junyixie88d99832021-03-22 17:47:10 +08001820 Py_XDECREF(from_list);
Tim Peters50d8d372001-02-28 05:34:27 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001823}
1824
Brett Cannon4caa61d2014-01-09 19:03:32 -05001825/*[clinic input]
1826_imp.extension_suffixes
1827
1828Returns the list of file suffixes used to identify extension modules.
1829[clinic start generated code]*/
1830
Brett Cannon4caa61d2014-01-09 19:03:32 -05001831static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001832_imp_extension_suffixes_impl(PyObject *module)
1833/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 list = PyList_New(0);
1838 if (list == NULL)
1839 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001840#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01001841 const char *suffix;
1842 unsigned int index = 0;
1843
Brett Cannon2657df42012-05-04 15:20:40 -04001844 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1845 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (item == NULL) {
1847 Py_DECREF(list);
1848 return NULL;
1849 }
1850 if (PyList_Append(list, item) < 0) {
1851 Py_DECREF(list);
1852 Py_DECREF(item);
1853 return NULL;
1854 }
1855 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001856 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 }
Brett Cannon2657df42012-05-04 15:20:40 -04001858#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001860}
1861
Brett Cannon4caa61d2014-01-09 19:03:32 -05001862/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001863_imp.init_frozen
1864
1865 name: unicode
1866 /
1867
1868Initializes a frozen module.
1869[clinic start generated code]*/
1870
Brett Cannon4caa61d2014-01-09 19:03:32 -05001871static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001872_imp_init_frozen_impl(PyObject *module, PyObject *name)
1873/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001874{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001875 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 int ret;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001877
Victor Stinner53dc7352011-03-20 01:50:21 +01001878 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 if (ret < 0)
1880 return NULL;
1881 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001882 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001884 return import_add_module(tstate, name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001885}
1886
Brett Cannon4caa61d2014-01-09 19:03:32 -05001887/*[clinic input]
1888_imp.get_frozen_object
1889
1890 name: unicode
1891 /
1892
1893Create a code object for a frozen module.
1894[clinic start generated code]*/
1895
Brett Cannon4caa61d2014-01-09 19:03:32 -05001896static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001897_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1898/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001901}
1902
Brett Cannon4caa61d2014-01-09 19:03:32 -05001903/*[clinic input]
1904_imp.is_frozen_package
1905
1906 name: unicode
1907 /
1908
1909Returns True if the module name is of a frozen package.
1910[clinic start generated code]*/
1911
Brett Cannon4caa61d2014-01-09 19:03:32 -05001912static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001913_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1914/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001917}
1918
Brett Cannon4caa61d2014-01-09 19:03:32 -05001919/*[clinic input]
1920_imp.is_builtin
1921
1922 name: unicode
1923 /
1924
1925Returns True if the module name corresponds to a built-in module.
1926[clinic start generated code]*/
1927
Guido van Rossum79f25d91997-04-29 20:08:16 +00001928static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001929_imp_is_builtin_impl(PyObject *module, PyObject *name)
1930/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001931{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001932 return PyLong_FromLong(is_builtin(name));
1933}
1934
1935/*[clinic input]
1936_imp.is_frozen
1937
1938 name: unicode
1939 /
1940
1941Returns True if the module name corresponds to a frozen module.
1942[clinic start generated code]*/
1943
Brett Cannon4caa61d2014-01-09 19:03:32 -05001944static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001945_imp_is_frozen_impl(PyObject *module, PyObject *name)
1946/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001947{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001948 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 p = find_frozen(name);
1951 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001952}
1953
Larry Hastings1df0b352015-08-24 19:53:56 -07001954/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1955static int
1956exec_builtin_or_dynamic(PyObject *mod) {
1957 PyModuleDef *def;
1958 void *state;
1959
1960 if (!PyModule_Check(mod)) {
1961 return 0;
1962 }
1963
1964 def = PyModule_GetDef(mod);
1965 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001966 return 0;
1967 }
Brett Cannon52794db2016-09-07 17:00:43 -07001968
Larry Hastings1df0b352015-08-24 19:53:56 -07001969 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001970 if (state) {
1971 /* Already initialized; skip reload */
1972 return 0;
1973 }
Brett Cannon52794db2016-09-07 17:00:43 -07001974
Larry Hastings1df0b352015-08-24 19:53:56 -07001975 return PyModule_ExecDef(mod, def);
1976}
1977
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001978#ifdef HAVE_DYNAMIC_LOADING
1979
Brett Cannon4caa61d2014-01-09 19:03:32 -05001980/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10001981_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05001982
Nick Coghland5cacbb2015-05-23 22:24:10 +10001983 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05001984 file: object = NULL
1985 /
1986
Nick Coghland5cacbb2015-05-23 22:24:10 +10001987Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988[clinic start generated code]*/
1989
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001991_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
1992/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001993{
Nick Coghland5cacbb2015-05-23 22:24:10 +10001994 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001995 FILE *fp;
1996
Nick Coghland5cacbb2015-05-23 22:24:10 +10001997 name = PyObject_GetAttrString(spec, "name");
1998 if (name == NULL) {
1999 return NULL;
2000 }
2001
2002 path = PyObject_GetAttrString(spec, "origin");
2003 if (path == NULL) {
2004 Py_DECREF(name);
2005 return NULL;
2006 }
2007
Serhiy Storchaka4db89882021-01-12 16:43:32 +02002008 PyThreadState *tstate = _PyThreadState_GET();
2009 mod = import_find_extension(tstate, name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002010 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002011 Py_DECREF(name);
2012 Py_DECREF(path);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002013 return mod;
2014 }
2015
Brett Cannon4caa61d2014-01-09 19:03:32 -05002016 if (file != NULL) {
2017 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002018 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002019 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002020 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002024 else
2025 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002026
2027 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2028
2029 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002030 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (fp)
2032 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002033 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002034}
2035
Nick Coghland5cacbb2015-05-23 22:24:10 +10002036/*[clinic input]
2037_imp.exec_dynamic -> int
2038
2039 mod: object
2040 /
2041
2042Initialize an extension module.
2043[clinic start generated code]*/
2044
2045static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002046_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2047/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002048{
Larry Hastings1df0b352015-08-24 19:53:56 -07002049 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002050}
2051
2052
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002053#endif /* HAVE_DYNAMIC_LOADING */
2054
Larry Hastings7726ac92014-01-31 22:03:12 -08002055/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002056_imp.exec_builtin -> int
2057
2058 mod: object
2059 /
2060
2061Initialize a built-in module.
2062[clinic start generated code]*/
2063
2064static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002065_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2066/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002067{
2068 return exec_builtin_or_dynamic(mod);
2069}
2070
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002071/*[clinic input]
2072_imp.source_hash
2073
2074 key: long
2075 source: Py_buffer
2076[clinic start generated code]*/
2077
2078static PyObject *
2079_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2080/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2081{
Benjamin Peterson83620772017-12-09 12:18:56 -08002082 union {
2083 uint64_t x;
2084 char data[sizeof(uint64_t)];
2085 } hash;
2086 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002087#if !PY_LITTLE_ENDIAN
2088 // Force to little-endian. There really ought to be a succinct standard way
2089 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002090 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2091 char tmp = hash.data[i];
2092 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2093 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002094 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002095#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002096 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002097}
2098
Barry Warsaw28a691b2010-04-17 00:19:56 +00002099
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002100PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002101"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002102
Guido van Rossum79f25d91997-04-29 20:08:16 +00002103static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002104 _IMP_EXTENSION_SUFFIXES_METHODDEF
2105 _IMP_LOCK_HELD_METHODDEF
2106 _IMP_ACQUIRE_LOCK_METHODDEF
2107 _IMP_RELEASE_LOCK_METHODDEF
2108 _IMP_GET_FROZEN_OBJECT_METHODDEF
2109 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002110 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002111 _IMP_INIT_FROZEN_METHODDEF
2112 _IMP_IS_BUILTIN_METHODDEF
2113 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002114 _IMP_CREATE_DYNAMIC_METHODDEF
2115 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002116 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002117 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002118 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002119 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002120};
2121
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002122
Victor Stinner62230712020-11-18 23:18:29 +01002123static int
2124imp_module_exec(PyObject *module)
2125{
2126 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
2127 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
2128 if (pyc_mode == NULL) {
2129 return -1;
2130 }
2131 if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
2132 Py_DECREF(pyc_mode);
2133 return -1;
2134 }
2135 Py_DECREF(pyc_mode);
2136
2137 return 0;
2138}
2139
2140
2141static PyModuleDef_Slot imp_slots[] = {
2142 {Py_mod_exec, imp_module_exec},
2143 {0, NULL}
2144};
2145
2146static struct PyModuleDef imp_module = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyModuleDef_HEAD_INIT,
Victor Stinner62230712020-11-18 23:18:29 +01002148 .m_name = "_imp",
2149 .m_doc = doc_imp,
2150 .m_size = 0,
2151 .m_methods = imp_methods,
2152 .m_slots = imp_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00002153};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002154
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002155PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002156PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002157{
Victor Stinner62230712020-11-18 23:18:29 +01002158 return PyModuleDef_Init(&imp_module);
2159}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002160
Victor Stinner62230712020-11-18 23:18:29 +01002161
2162// Import the _imp extension by calling manually _imp.create_builtin() and
2163// _imp.exec_builtin() since importlib is not initialized yet. Initializing
2164// importlib requires the _imp module: this function fix the bootstrap issue.
2165PyObject*
2166_PyImport_BootstrapImp(PyThreadState *tstate)
2167{
2168 PyObject *name = PyUnicode_FromString("_imp");
2169 if (name == NULL) {
2170 return NULL;
Victor Stinner410b85a2019-05-13 17:12:45 +02002171 }
2172
Victor Stinner62230712020-11-18 23:18:29 +01002173 // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
2174 // an object with just a name attribute.
2175 //
2176 // _imp.__spec__ is overriden by importlib._bootstrap._instal() anyway.
2177 PyObject *attrs = Py_BuildValue("{sO}", "name", name);
2178 if (attrs == NULL) {
2179 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002180 }
Victor Stinner62230712020-11-18 23:18:29 +01002181 PyObject *spec = _PyNamespace_New(attrs);
2182 Py_DECREF(attrs);
2183 if (spec == NULL) {
2184 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002185 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002186
Victor Stinner62230712020-11-18 23:18:29 +01002187 // Create the _imp module from its definition.
2188 PyObject *mod = create_builtin(tstate, name, spec);
2189 Py_CLEAR(name);
2190 Py_DECREF(spec);
2191 if (mod == NULL) {
2192 goto error;
2193 }
2194 assert(mod != Py_None); // not found
2195
2196 // Execute the _imp module: call imp_module_exec().
2197 if (exec_builtin_or_dynamic(mod) < 0) {
2198 Py_DECREF(mod);
2199 goto error;
2200 }
2201 return mod;
2202
2203error:
2204 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002206}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002207
2208
Guido van Rossumb18618d2000-05-03 23:44:39 +00002209/* API for embedding applications that want to add their own entries
2210 to the table of built-in modules. This should normally be called
2211 *before* Py_Initialize(). When the table resize fails, -1 is
2212 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002213
2214 After a similar function by Just van Rossum. */
2215
2216int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002217PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002220 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002221 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Count the number of entries in both tables */
2224 for (n = 0; newtab[n].name != NULL; n++)
2225 ;
2226 if (n == 0)
2227 return 0; /* Nothing to do */
2228 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2229 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002230
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002231 /* Force default raw memory allocator to get a known allocator to be able
2232 to release the memory in _PyImport_Fini2() */
2233 PyMemAllocatorEx old_alloc;
2234 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002237 p = NULL;
2238 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002239 size_t size = sizeof(struct _inittab) * (i + n + 1);
2240 p = PyMem_RawRealloc(inittab_copy, size);
2241 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002242 if (p == NULL) {
2243 res = -1;
2244 goto done;
2245 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002246
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002247 /* Copy the tables into the new memory at the first call
2248 to PyImport_ExtendInittab(). */
2249 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002251 }
2252 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2253 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002254
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002255done:
2256 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2257 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002258}
2259
2260/* Shorthand to add a single entry given a name and a function */
2261
2262int
Brett Cannona826f322009-04-02 03:41:46 +00002263PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002268
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002269 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002273}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002274
2275#ifdef __cplusplus
2276}
2277#endif