blob: 6fba057baddeb4fe7cddc89c1fa02832f2de5ce9 [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 Stinner3bb183d2018-11-22 18:38:38 +01005#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner62230712020-11-18 23:18:29 +01006#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner61691d82019-10-02 23:51:20 +02007#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02008#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pyhash.h"
10#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020011#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020012#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
13#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010014#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000018#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020019#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000020
Guido van Rossum55a83382000-09-20 20:31:38 +000021#ifdef HAVE_FCNTL_H
22#include <fcntl.h>
23#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000025extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000027
Barry Warsaw28a691b2010-04-17 00:19:56 +000028#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000029
Victor Stinner0a28f8d2019-06-19 02:54:39 +020030/* Forward references */
31static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
32
Victor Stinner95872862011-03-07 18:20:56 +010033/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000034static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000035
Guido van Rossum771c6c81997-10-31 18:37:24 +000036/* This table is defined in config.c: */
37extern struct _inittab _PyImport_Inittab[];
38
39struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010040static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000041
Hai Shi46874c22020-01-30 17:20:25 -060042_Py_IDENTIFIER(__path__);
43_Py_IDENTIFIER(__spec__);
44
Brett Cannon4caa61d2014-01-09 19:03:32 -050045/*[clinic input]
46module _imp
47[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030048/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040049
50#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050051
Guido van Rossum1ae940a1995-01-02 19:04:15 +000052/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053
Victor Stinner331a6a52019-05-27 16:39:22 +020054PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020055_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040056{
ukwksk5e6312c2018-05-15 04:10:52 +090057 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040058 int err = 0;
59
60 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020061 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020062 _PyErr_SetString(tstate, PyExc_RuntimeError,
63 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040064 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020065 }
Brett Cannonfd074152012-04-14 14:10:13 -040066
Victor Stinnerda7933e2020-04-13 03:04:28 +020067 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +020068 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -040069 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020070 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071
ukwksk5e6312c2018-05-15 04:10:52 +090072 zipimport = PyImport_ImportModule("zipimport");
73 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020074 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020075 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 }
79 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020080 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090081 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020082 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090083 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020085 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020086 if (verbose) {
87 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
88 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 }
90 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -040091 /* sys.path_hooks.insert(0, zipimporter) */
92 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -040094 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -040096 }
Victor Stinner410b85a2019-05-13 17:12:45 +020097 if (verbose) {
98 PySys_WriteStderr("# installed zipimport hook\n");
99 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 }
101 }
Brett Cannonfd074152012-04-14 14:10:13 -0400102
Victor Stinner331a6a52019-05-27 16:39:22 +0200103 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400104
105 error:
106 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200107 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000108}
109
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000110/* Locking primitives to prevent parallel imports of the same module
111 in different threads to return with a partially loaded module.
112 These calls are serialized by the global interpreter lock. */
113
Victor Stinner26881c82020-06-02 15:51:37 +0200114static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200115static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000116static int import_lock_level = 0;
117
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000118void
119_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000120{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200121 unsigned long me = PyThread_get_thread_ident();
122 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 return; /* Too bad */
124 if (import_lock == NULL) {
125 import_lock = PyThread_allocate_lock();
126 if (import_lock == NULL)
127 return; /* Nothing much we can do. */
128 }
129 if (import_lock_thread == me) {
130 import_lock_level++;
131 return;
132 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200133 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
134 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {
136 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200137 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 PyEval_RestoreThread(tstate);
139 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100140 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 import_lock_thread = me;
142 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000143}
144
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000145int
146_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200148 unsigned long me = PyThread_get_thread_ident();
149 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 return 0; /* Too bad */
151 if (import_lock_thread != me)
152 return -1;
153 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100154 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200156 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyThread_release_lock(import_lock);
158 }
159 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000160}
161
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900162#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200163/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000164 created child processes do not share locks with the parent.
165 We now acquire the import lock around fork() calls but on some platforms
166 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200167PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000168_PyImport_ReInitLock(void)
169{
Christian Heimes418fd742015-04-19 21:08:42 +0200170 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900171 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200172 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200173 }
174 }
Victor Stinner26881c82020-06-02 15:51:37 +0200175
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000176 if (import_lock_level > 1) {
177 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200178 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200179 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000180 import_lock_thread = me;
181 import_lock_level--;
182 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200183 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000184 import_lock_level = 0;
185 }
Victor Stinner26881c82020-06-02 15:51:37 +0200186 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000187}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900188#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000189
Brett Cannon4caa61d2014-01-09 19:03:32 -0500190/*[clinic input]
191_imp.lock_held
192
193Return True if the import lock is currently held, else False.
194
195On platforms without threads, return False.
196[clinic start generated code]*/
197
Brett Cannon4caa61d2014-01-09 19:03:32 -0500198static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300199_imp_lock_held_impl(PyObject *module)
200/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000201{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200202 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000203}
204
Brett Cannon4caa61d2014-01-09 19:03:32 -0500205/*[clinic input]
206_imp.acquire_lock
207
208Acquires the interpreter's import lock for the current thread.
209
210This lock should be used by import hooks to ensure thread-safety when importing
211modules. On platforms without threads, this function does nothing.
212[clinic start generated code]*/
213
Brett Cannon4caa61d2014-01-09 19:03:32 -0500214static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300215_imp_acquire_lock_impl(PyObject *module)
216/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200219 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000220}
221
Brett Cannon4caa61d2014-01-09 19:03:32 -0500222/*[clinic input]
223_imp.release_lock
224
225Release the interpreter's import lock.
226
227On platforms without threads, this function does nothing.
228[clinic start generated code]*/
229
Brett Cannon4caa61d2014-01-09 19:03:32 -0500230static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300231_imp_release_lock_impl(PyObject *module)
232/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (_PyImport_ReleaseLock() < 0) {
235 PyErr_SetString(PyExc_RuntimeError,
236 "not holding the import lock");
237 return NULL;
238 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200239 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000240}
241
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100242void
243_PyImport_Fini(void)
244{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200245 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100246 if (import_lock != NULL) {
247 PyThread_free_lock(import_lock);
248 import_lock = NULL;
249 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100250}
251
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100252void
253_PyImport_Fini2(void)
254{
255 /* Use the same memory allocator than PyImport_ExtendInittab(). */
256 PyMemAllocatorEx old_alloc;
257 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
258
259 /* Free memory allocated by PyImport_ExtendInittab() */
260 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700261 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100262
263 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
264}
265
Guido van Rossum25ce5661997-08-02 03:10:38 +0000266/* Helper for sys */
267
268PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000269PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000270{
Victor Stinner81a7be32020-04-14 15:14:01 +0200271 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600272 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100273 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600274 }
Eric Snow93c92f72017-09-13 23:46:04 -0700275 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000276}
277
Eric Snowd393c1b2017-09-14 12:18:12 -0600278/* In some corner cases it is important to be sure that the import
279 machinery has been initialized (or not cleaned up yet). For
280 example, see issue #4236 and PyModule_Create2(). */
281
282int
283_PyImport_IsInitialized(PyInterpreterState *interp)
284{
285 if (interp->modules == NULL)
286 return 0;
287 return 1;
288}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000289
Eric Snow3f9eee62017-09-15 16:35:20 -0600290PyObject *
291_PyImport_GetModuleId(struct _Py_Identifier *nameid)
292{
293 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
294 if (name == NULL) {
295 return NULL;
296 }
297 return PyImport_GetModule(name);
298}
299
300int
301_PyImport_SetModule(PyObject *name, PyObject *m)
302{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100303 PyInterpreterState *interp = _PyInterpreterState_GET();
304 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600305 return PyObject_SetItem(modules, name, m);
306}
307
308int
309_PyImport_SetModuleString(const char *name, PyObject *m)
310{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100311 PyInterpreterState *interp = _PyInterpreterState_GET();
312 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600313 return PyMapping_SetItemString(modules, name, m);
314}
315
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200316static PyObject *
317import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600318{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200319 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600320 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200321 _PyErr_SetString(tstate, PyExc_RuntimeError,
322 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600323 return NULL;
324 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200325
326 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600327 Py_INCREF(modules);
328 if (PyDict_CheckExact(modules)) {
329 m = PyDict_GetItemWithError(modules, name); /* borrowed */
330 Py_XINCREF(m);
331 }
332 else {
333 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200334 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
335 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600336 }
337 }
338 Py_DECREF(modules);
339 return m;
340}
341
342
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100343static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100344import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200345{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100346 PyObject *spec;
347
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100348 _Py_IDENTIFIER(_lock_unlock_module);
349
350 /* Optimization: only call _bootstrap._lock_unlock_module() if
351 __spec__._initializing is true.
352 NOTE: because of this, initializing must be set *before*
353 stuffing the new module in sys.modules.
354 */
355 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
356 int busy = _PyModuleSpec_IsInitializing(spec);
357 Py_XDECREF(spec);
358 if (busy) {
359 /* Wait until module is done importing. */
360 PyObject *value = _PyObject_CallMethodIdOneArg(
361 interp->importlib, &PyId__lock_unlock_module, name);
362 if (value == NULL) {
363 return -1;
364 }
365 Py_DECREF(value);
366 }
367 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200368}
369
370
Barry Warsaw28a691b2010-04-17 00:19:56 +0000371/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000372
373long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000375{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200376 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200377 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600378 PyObject *external, *pyc_magic;
379
380 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
381 if (external == NULL)
382 return -1;
383 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
384 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400385 if (pyc_magic == NULL)
386 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200387 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700388 Py_DECREF(pyc_magic);
389 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000390}
391
392
Brett Cannon3adc7b72012-07-09 14:22:12 -0400393extern const char * _PySys_ImplCacheTag;
394
Barry Warsaw28a691b2010-04-17 00:19:56 +0000395const char *
396PyImport_GetMagicTag(void)
397{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400398 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000399}
400
Brett Cannon98979b82012-07-02 15:13:11 -0400401
Guido van Rossum25ce5661997-08-02 03:10:38 +0000402/* Magic for extension modules (built-in as well as dynamically
403 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200404 once, we keep a static dictionary 'extensions' keyed by the tuple
405 (module name, module name) (for built-in modules) or by
406 (filename, module name) (for dynamically loaded modules), containing these
407 modules. A copy of the module's dictionary is stored by calling
408 _PyImport_FixupExtensionObject() immediately after the module initialization
409 function succeeds. A copy can be retrieved from there by calling
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200410 import_find_extension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000411
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000412 Modules which do support multiple initialization set their m_size
413 field to a non-negative number (indicating the size of the
414 module-specific state). They are still recorded in the extensions
415 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000416*/
417
418int
Victor Stinner95872862011-03-07 18:20:56 +0100419_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200420 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (mod == NULL || !PyModule_Check(mod)) {
423 PyErr_BadInternalCall();
424 return -1;
425 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100426
427 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (!def) {
429 PyErr_BadInternalCall();
430 return -1;
431 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100432
433 PyThreadState *tstate = _PyThreadState_GET();
434 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100436 }
437 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600438 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 return -1;
440 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100441
Victor Stinner101bf692021-02-19 13:33:31 +0100442 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner82c83bd2019-11-22 18:52:27 +0100443 if (def->m_size == -1) {
444 if (def->m_base.m_copy) {
445 /* Somebody already imported the module,
446 likely under a different name.
447 XXX this should really not happen. */
448 Py_CLEAR(def->m_base.m_copy);
449 }
450 PyObject *dict = PyModule_GetDict(mod);
451 if (dict == NULL) {
452 return -1;
453 }
454 def->m_base.m_copy = PyDict_Copy(dict);
455 if (def->m_base.m_copy == NULL) {
456 return -1;
457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100459
460 if (extensions == NULL) {
461 extensions = PyDict_New();
462 if (extensions == NULL) {
463 return -1;
464 }
465 }
466
467 PyObject *key = PyTuple_Pack(2, filename, name);
468 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100470 }
471 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
472 Py_DECREF(key);
473 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000479}
480
Victor Stinner49d3f252010-10-17 01:24:53 +0000481int
Eric Snowd393c1b2017-09-14 12:18:12 -0600482_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000483{
484 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100485 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100486 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100487 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000488 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600489 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100490 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000491 return res;
492}
493
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200494static PyObject *
495import_find_extension(PyThreadState *tstate, PyObject *name,
496 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000497{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200498 if (extensions == NULL) {
499 return NULL;
500 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600501
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200502 PyObject *key = PyTuple_Pack(2, filename, name);
503 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200505 }
506 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500507 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200508 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200510 }
511
512 PyObject *mod, *mdict;
513 PyObject *modules = tstate->interp->modules;
514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (def->m_size == -1) {
516 /* Module does not support repeated initialization */
517 if (def->m_base.m_copy == NULL)
518 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200519 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (mod == NULL)
521 return NULL;
522 mdict = PyModule_GetDict(mod);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200523 if (mdict == NULL) {
524 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200526 }
527 if (PyDict_Update(mdict, def->m_base.m_copy)) {
528 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200530 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 }
532 else {
533 if (def->m_base.m_init == NULL)
534 return NULL;
535 mod = def->m_base.m_init();
536 if (mod == NULL)
537 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600538 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200539 Py_DECREF(mod);
540 return NULL;
541 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100543 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600544 PyMapping_DelItem(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200545 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 return NULL;
547 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200548
Victor Stinnerda7933e2020-04-13 03:04:28 +0200549 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200550 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100551 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200552 name, filename);
553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000555}
556
557
558/* Get the module object corresponding to a module name.
559 First check the modules dictionary if there's one there,
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200560 if not, create a new one and insert it in the modules dictionary. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000561
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200562static PyObject *
563import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000564{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200565 PyObject *modules = tstate->interp->modules;
566 if (modules == NULL) {
567 _PyErr_SetString(tstate, PyExc_RuntimeError,
568 "no import module dictionary");
569 return NULL;
570 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600571
Eric Snow86b7afd2017-09-04 17:54:09 -0600572 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600573 if (PyDict_CheckExact(modules)) {
574 m = PyDict_GetItemWithError(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200575 Py_XINCREF(m);
Eric Snow3f9eee62017-09-15 16:35:20 -0600576 }
577 else {
578 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000579 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600580 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200581 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
582 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600583 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200584 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200585 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200586 return NULL;
587 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600588 if (m != NULL && PyModule_Check(m)) {
589 return m;
590 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200591 Py_XDECREF(m);
Victor Stinner27ee0892011-03-04 12:57:09 +0000592 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (m == NULL)
594 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600595 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 Py_DECREF(m);
597 return NULL;
598 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000601}
602
Victor Stinner27ee0892011-03-04 12:57:09 +0000603PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200604PyImport_AddModuleObject(PyObject *name)
605{
606 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200607 PyObject *mod = import_add_module(tstate, name);
608 if (mod) {
609 PyObject *ref = PyWeakref_NewRef(mod, NULL);
610 Py_DECREF(mod);
611 if (ref == NULL) {
612 return NULL;
613 }
614 mod = PyWeakref_GetObject(ref);
615 Py_DECREF(ref);
616 }
617 return mod; /* borrowed reference */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200618}
619
620
621PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000622PyImport_AddModule(const char *name)
623{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200624 PyObject *nameobj = PyUnicode_FromString(name);
625 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000626 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200627 }
628 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000629 Py_DECREF(nameobj);
630 return module;
631}
632
633
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300634/* Remove name from sys.modules, if it's there.
635 * Can be called with an exception raised.
636 * If fail to remove name a new exception will be chained with the old
637 * exception, otherwise the old exception is preserved.
638 */
Tim Peters1cd70172004-08-02 03:52:12 +0000639static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200640remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000641{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600642 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200643 _PyErr_Fetch(tstate, &type, &value, &traceback);
644
645 PyObject *modules = tstate->interp->modules;
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300646 if (PyDict_CheckExact(modules)) {
647 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
648 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600649 }
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300650 else if (PyMapping_DelItem(modules, name) < 0) {
651 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
652 _PyErr_Clear(tstate);
653 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600654 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200655
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300656 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000657}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658
Christian Heimes3b06e532008-01-07 20:12:44 +0000659
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000660/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000661 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
662 * removed from sys.modules, to avoid leaving damaged module objects
663 * in sys.modules. The caller may wish to restore the original
664 * module object (if any) in this case; PyImport_ReloadModule is an
665 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000666 *
667 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
668 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000669 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000670PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300671PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return PyImport_ExecCodeModuleWithPathnames(
674 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000675}
676
677PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300678PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return PyImport_ExecCodeModuleWithPathnames(
681 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000682}
683
684PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300685PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
686 const char *pathname,
687 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000688{
Victor Stinner27ee0892011-03-04 12:57:09 +0000689 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600690 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000691
692 nameobj = PyUnicode_FromString(name);
693 if (nameobj == NULL)
694 return NULL;
695
Victor Stinner27ee0892011-03-04 12:57:09 +0000696 if (cpathname != NULL) {
697 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
698 if (cpathobj == NULL)
699 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400700 }
701 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000702 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400703
704 if (pathname != NULL) {
705 pathobj = PyUnicode_DecodeFSDefault(pathname);
706 if (pathobj == NULL)
707 goto error;
708 }
709 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200710 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400711 _Py_IDENTIFIER(_get_sourcefile);
712
713 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100714 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400715 }
716
Eric Snow32439d62015-05-02 19:15:18 -0600717 external= PyObject_GetAttrString(interp->importlib,
718 "_bootstrap_external");
719 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200720 pathobj = _PyObject_CallMethodIdOneArg(
721 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600722 Py_DECREF(external);
723 }
Brett Cannona6473f92012-07-13 13:57:03 -0400724 if (pathobj == NULL)
725 PyErr_Clear();
726 }
727 else
728 pathobj = NULL;
729
Victor Stinner27ee0892011-03-04 12:57:09 +0000730 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
731error:
732 Py_DECREF(nameobj);
733 Py_XDECREF(pathobj);
734 Py_XDECREF(cpathobj);
735 return m;
736}
737
Brett Cannon18fc4e72014-04-04 10:01:46 -0400738static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200739module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000740{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200741 _Py_IDENTIFIER(__builtins__);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200742 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200744 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (m == NULL)
746 return NULL;
747 /* If the module is being reloaded, we get the old module back
748 and re-use its dict to exec the new code. */
749 d = PyModule_GetDict(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200750 int r = _PyDict_ContainsId(d, &PyId___builtins__);
751 if (r == 0) {
752 r = _PyDict_SetItemId(d, &PyId___builtins__,
753 PyEval_GetBuiltins());
754 }
755 if (r < 0) {
756 remove_module(tstate, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200757 Py_DECREF(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200758 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400760
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200761 Py_INCREF(d);
762 Py_DECREF(m);
763 return d;
Brett Cannon18fc4e72014-04-04 10:01:46 -0400764}
765
766static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200767exec_code_in_module(PyThreadState *tstate, PyObject *name,
768 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -0400769{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400770 PyObject *v, *m;
771
772 v = PyEval_EvalCode(code_object, module_dict, module_dict);
773 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200774 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400775 return NULL;
776 }
777 Py_DECREF(v);
778
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200779 m = import_get_module(tstate, name);
780 if (m == NULL && !_PyErr_Occurred(tstate)) {
781 _PyErr_Format(tstate, PyExc_ImportError,
782 "Loaded module %R not found in sys.modules",
783 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400784 }
785
Brett Cannon18fc4e72014-04-04 10:01:46 -0400786 return m;
787}
788
789PyObject*
790PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
791 PyObject *cpathname)
792{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200793 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600794 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600795 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400796
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200797 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400798 if (d == NULL) {
799 return NULL;
800 }
801
Eric Snow08197a42014-05-12 17:54:55 -0600802 if (pathname == NULL) {
803 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200805 external = PyObject_GetAttrString(tstate->interp->importlib,
806 "_bootstrap_external");
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200807 if (external == NULL) {
808 Py_DECREF(d);
Eric Snow32439d62015-05-02 19:15:18 -0600809 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200810 }
Eric Snow32439d62015-05-02 19:15:18 -0600811 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600812 &PyId__fix_up_module,
813 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600814 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600815 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600816 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200817 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200819 Py_DECREF(d);
Eric Snow08197a42014-05-12 17:54:55 -0600820 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000821}
822
823
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000824static void
825update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyObject *constants, *tmp;
828 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (PyUnicode_Compare(co->co_filename, oldname))
831 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000832
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200833 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300834 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 constants = co->co_consts;
837 n = PyTuple_GET_SIZE(constants);
838 for (i = 0; i < n; i++) {
839 tmp = PyTuple_GET_ITEM(constants, i);
840 if (PyCode_Check(tmp))
841 update_code_filenames((PyCodeObject *)tmp,
842 oldname, newname);
843 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000844}
845
Victor Stinner2f42ae52011-03-20 00:41:24 +0100846static void
847update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000848{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100849 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000850
Victor Stinner2f42ae52011-03-20 00:41:24 +0100851 if (PyUnicode_Compare(co->co_filename, newname) == 0)
852 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 oldname = co->co_filename;
855 Py_INCREF(oldname);
856 update_code_filenames(co, oldname, newname);
857 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000858}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000859
Brett Cannon4caa61d2014-01-09 19:03:32 -0500860/*[clinic input]
861_imp._fix_co_filename
862
863 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
864 Code object to change.
865
866 path: unicode
867 File path to use.
868 /
869
870Changes code.co_filename to specify the passed-in file path.
871[clinic start generated code]*/
872
Brett Cannon4caa61d2014-01-09 19:03:32 -0500873static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300874_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400875 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300876/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700877
Brett Cannon4caa61d2014-01-09 19:03:32 -0500878{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500879 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700880
881 Py_RETURN_NONE;
882}
883
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000885/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700886static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000887
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000888
889/* Helper to test for built-in module */
890
891static int
Victor Stinner95872862011-03-07 18:20:56 +0100892is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000893{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200894 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200896 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (PyImport_Inittab[i].initfunc == NULL)
898 return -1;
899 else
900 return 1;
901 }
902 }
903 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000904}
905
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000906
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700907/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000908 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000909 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000910 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700911 this tells our caller that the path based finder could not find
912 a finder for this path item. Cache the result in
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200913 path_importer_cache. */
Just van Rossum52e14d62002-12-30 22:08:05 +0000914
915static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200916get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
917 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyObject *importer;
920 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* These conditions are the caller's responsibility: */
923 assert(PyList_Check(path_hooks));
924 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 nhooks = PyList_Size(path_hooks);
927 if (nhooks < 0)
928 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000929
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200930 importer = PyDict_GetItemWithError(path_importer_cache, p);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200931 if (importer != NULL || _PyErr_Occurred(tstate)) {
932 Py_XINCREF(importer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return importer;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200934 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* set path_importer_cache[p] to None to avoid recursion */
937 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
938 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 for (j = 0; j < nhooks; j++) {
941 PyObject *hook = PyList_GetItem(path_hooks, j);
942 if (hook == NULL)
943 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +0100944 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (importer != NULL)
946 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000947
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200948 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return NULL;
950 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200951 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
953 if (importer == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200954 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200956 if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 Py_DECREF(importer);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200958 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 }
960 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000961}
962
Benjamin Petersone5024512018-09-12 12:06:42 -0700963PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200964PyImport_GetImporter(PyObject *path)
965{
966 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200967 PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
968 PyObject *path_hooks = PySys_GetObject("path_hooks");
969 if (path_importer_cache == NULL || path_hooks == NULL) {
970 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200972 return get_path_importer(tstate, path_importer_cache, path_hooks, path);
Christian Heimes9cd17752007-11-18 19:35:23 +0000973}
974
Victor Stinner62230712020-11-18 23:18:29 +0100975static PyObject*
976create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
977{
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200978 PyObject *mod = import_find_extension(tstate, name, name);
Victor Stinner62230712020-11-18 23:18:29 +0100979 if (mod || _PyErr_Occurred(tstate)) {
Victor Stinner62230712020-11-18 23:18:29 +0100980 return mod;
981 }
982
983 PyObject *modules = tstate->interp->modules;
984 for (struct _inittab *p = PyImport_Inittab; p->name != NULL; p++) {
985 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
986 if (p->initfunc == NULL) {
987 /* Cannot re-init internal module ("sys" or "builtins") */
988 return PyImport_AddModuleObject(name);
989 }
990
991 mod = (*p->initfunc)();
992 if (mod == NULL) {
993 return NULL;
994 }
995
996 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
997 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
998 }
999 else {
1000 /* Remember pointer to module init function. */
1001 PyModuleDef *def = PyModule_GetDef(mod);
1002 if (def == NULL) {
1003 return NULL;
1004 }
1005
1006 def->m_base.m_init = p->initfunc;
1007 if (_PyImport_FixupExtensionObject(mod, name, name,
1008 modules) < 0) {
1009 return NULL;
1010 }
1011 return mod;
1012 }
1013 }
1014 }
1015
1016 // not found
1017 Py_RETURN_NONE;
1018}
1019
1020
1021
Nick Coghland5cacbb2015-05-23 22:24:10 +10001022/*[clinic input]
1023_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001024
Nick Coghland5cacbb2015-05-23 22:24:10 +10001025 spec: object
1026 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001027
Nick Coghland5cacbb2015-05-23 22:24:10 +10001028Create an extension module.
1029[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001030
Nick Coghland5cacbb2015-05-23 22:24:10 +10001031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001032_imp_create_builtin(PyObject *module, PyObject *spec)
1033/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001034{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001035 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001036
Victor Stinner62230712020-11-18 23:18:29 +01001037 PyObject *name = PyObject_GetAttrString(spec, "name");
Nick Coghland5cacbb2015-05-23 22:24:10 +10001038 if (name == NULL) {
1039 return NULL;
1040 }
1041
Victor Stinner62230712020-11-18 23:18:29 +01001042 PyObject *mod = create_builtin(tstate, name, spec);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001043 Py_DECREF(name);
Victor Stinner62230712020-11-18 23:18:29 +01001044 return mod;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001045}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001046
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001047
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001048/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001049
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001050static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001051find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001052{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001053 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001054
Victor Stinner53dc7352011-03-20 01:50:21 +01001055 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 for (p = PyImport_FrozenModules; ; p++) {
1059 if (p->name == NULL)
1060 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001061 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 break;
1063 }
1064 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001065}
1066
Guido van Rossum79f25d91997-04-29 20:08:16 +00001067static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001068get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001069{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001070 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (p == NULL) {
1074 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001075 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 name);
1077 return NULL;
1078 }
1079 if (p->code == NULL) {
1080 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001081 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 name);
1083 return NULL;
1084 }
1085 size = p->size;
1086 if (size < 0)
1087 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001088 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001089}
1090
Brett Cannon8d110132009-03-15 02:20:16 +00001091static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001092is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001093{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001094 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (p == NULL) {
1098 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001099 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 name);
1101 return NULL;
1102 }
Brett Cannon8d110132009-03-15 02:20:16 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (size < 0)
1107 Py_RETURN_TRUE;
1108 else
1109 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001110}
1111
1112
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001113/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001114 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001115 an exception set if the initialization failed.
1116 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001117
1118int
Victor Stinner53dc7352011-03-20 01:50:21 +01001119PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001120{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001121 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001122 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001123 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 int ispackage;
1125 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001126
Victor Stinner53dc7352011-03-20 01:50:21 +01001127 p = find_frozen(name);
1128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (p == NULL)
1130 return 0;
1131 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001132 _PyErr_Format(tstate, PyExc_ImportError,
1133 "Excluded frozen object named %R",
1134 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 return -1;
1136 }
1137 size = p->size;
1138 ispackage = (size < 0);
1139 if (ispackage)
1140 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001141 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (co == NULL)
1143 return -1;
1144 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001145 _PyErr_Format(tstate, PyExc_TypeError,
1146 "frozen object %R is not a code object",
1147 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 goto err_return;
1149 }
1150 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001151 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001152 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001154 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (m == NULL)
1156 goto err_return;
1157 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001158 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (l == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001160 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 goto err_return;
1162 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 err = PyDict_SetItemString(d, "__path__", l);
1164 Py_DECREF(l);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001165 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (err != 0)
1167 goto err_return;
1168 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001169 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001170 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001171 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001172 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001173 m = exec_code_in_module(tstate, name, d, co);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001174 Py_DECREF(d);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001175 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 Py_DECREF(co);
1179 Py_DECREF(m);
1180 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001181
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001182err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(co);
1184 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001185}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001186
Victor Stinner53dc7352011-03-20 01:50:21 +01001187int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001188PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001189{
1190 PyObject *nameobj;
1191 int ret;
1192 nameobj = PyUnicode_InternFromString(name);
1193 if (nameobj == NULL)
1194 return -1;
1195 ret = PyImport_ImportFrozenModuleObject(nameobj);
1196 Py_DECREF(nameobj);
1197 return ret;
1198}
1199
Guido van Rossum74e6a111994-08-29 12:54:38 +00001200
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001201/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001202 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001203
Guido van Rossum79f25d91997-04-29 20:08:16 +00001204PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001205PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 PyObject *pname;
1208 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 pname = PyUnicode_FromString(name);
1211 if (pname == NULL)
1212 return NULL;
1213 result = PyImport_Import(pname);
1214 Py_DECREF(pname);
1215 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001216}
1217
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001218
Christian Heimes072c0f12008-01-03 23:01:04 +00001219/* Import a module without blocking
1220 *
1221 * At first it tries to fetch the module from sys.modules. If the module was
1222 * never loaded before it loads it with PyImport_ImportModule() unless another
1223 * thread holds the import lock. In the latter case the function raises an
1224 * ImportError instead of blocking.
1225 *
1226 * Returns the module object with incremented ref count.
1227 */
1228PyObject *
1229PyImport_ImportModuleNoBlock(const char *name)
1230{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001231 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001232}
1233
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001234
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001235/* Remove importlib frames from the traceback,
1236 * except in Verbose mode. */
1237static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001238remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001239{
1240 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001241 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001242 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001243 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001244 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001245 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001246 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001247
1248 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001249 from the traceback. We always trim chunks
1250 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001251
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001252 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001253 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001254 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001255 }
1256
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001257 if (PyType_IsSubtype((PyTypeObject *) exception,
1258 (PyTypeObject *) PyExc_ImportError))
1259 always_trim = 1;
1260
1261 prev_link = &base_tb;
1262 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001263 while (tb != NULL) {
1264 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1265 PyObject *next = (PyObject *) traceback->tb_next;
1266 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001267 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001268 int now_in_importlib;
1269
1270 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001271 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1272 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001273 if (now_in_importlib && !in_importlib) {
1274 /* This is the link to this chunk of importlib tracebacks */
1275 outer_link = prev_link;
1276 }
1277 in_importlib = now_in_importlib;
1278
1279 if (in_importlib &&
1280 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001281 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001282 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001283 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001284 prev_link = outer_link;
1285 }
1286 else {
1287 prev_link = (PyObject **) &traceback->tb_next;
1288 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001289 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001290 tb = next;
1291 }
1292done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001293 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001294}
1295
1296
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001297static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001298resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001299{
Brett Cannonfd074152012-04-14 14:10:13 -04001300 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001301 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001302 _Py_IDENTIFIER(parent);
1303 PyObject *abs_name;
1304 PyObject *package = NULL;
1305 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001306 Py_ssize_t last_dot;
1307 PyObject *base;
1308 int level_up;
1309
1310 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001311 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001312 goto error;
1313 }
1314 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001315 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001316 goto error;
1317 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001318 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001319 if (package == Py_None) {
1320 package = NULL;
1321 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001322 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001323 goto error;
1324 }
1325 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001326 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001327 goto error;
1328 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001329
1330 if (package != NULL) {
1331 Py_INCREF(package);
1332 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001333 _PyErr_SetString(tstate, PyExc_TypeError,
1334 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001335 goto error;
1336 }
1337 else if (spec != NULL && spec != Py_None) {
1338 int equal;
1339 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1340 if (parent == NULL) {
1341 goto error;
1342 }
1343
1344 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1345 Py_DECREF(parent);
1346 if (equal < 0) {
1347 goto error;
1348 }
1349 else if (equal == 0) {
1350 if (PyErr_WarnEx(PyExc_ImportWarning,
1351 "__package__ != __spec__.parent", 1) < 0) {
1352 goto error;
1353 }
1354 }
1355 }
1356 }
1357 else if (spec != NULL && spec != Py_None) {
1358 package = _PyObject_GetAttrId(spec, &PyId_parent);
1359 if (package == NULL) {
1360 goto error;
1361 }
1362 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001363 _PyErr_SetString(tstate, PyExc_TypeError,
1364 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001365 goto error;
1366 }
1367 }
1368 else {
1369 if (PyErr_WarnEx(PyExc_ImportWarning,
1370 "can't resolve package from __spec__ or __package__, "
1371 "falling back on __name__ and __path__", 1) < 0) {
1372 goto error;
1373 }
1374
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001375 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001376 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001377 if (!_PyErr_Occurred(tstate)) {
1378 _PyErr_SetString(tstate, PyExc_KeyError,
1379 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001380 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001381 goto error;
1382 }
1383
1384 Py_INCREF(package);
1385 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001386 _PyErr_SetString(tstate, PyExc_TypeError,
1387 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001388 goto error;
1389 }
1390
Serhiy Storchakab510e102020-10-26 12:47:57 +02001391 int haspath = _PyDict_ContainsId(globals, &PyId___path__);
1392 if (haspath < 0) {
1393 goto error;
1394 }
1395 if (!haspath) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001396 Py_ssize_t dot;
1397
Serhiy Storchakab510e102020-10-26 12:47:57 +02001398 if (PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001399 goto error;
1400 }
1401
1402 dot = PyUnicode_FindChar(package, '.',
1403 0, PyUnicode_GET_LENGTH(package), -1);
1404 if (dot == -2) {
1405 goto error;
1406 }
Ben Lewis92420b32019-09-11 20:09:47 +10001407 else if (dot == -1) {
1408 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001409 }
Ben Lewis92420b32019-09-11 20:09:47 +10001410 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1411 if (substr == NULL) {
1412 goto error;
1413 }
1414 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001415 }
1416 }
1417
1418 last_dot = PyUnicode_GET_LENGTH(package);
1419 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001420 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001421 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001422
1423 for (level_up = 1; level_up < level; level_up += 1) {
1424 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1425 if (last_dot == -2) {
1426 goto error;
1427 }
1428 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001429 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001430 "attempted relative import beyond top-level "
1431 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001432 goto error;
1433 }
1434 }
1435
1436 base = PyUnicode_Substring(package, 0, last_dot);
1437 Py_DECREF(package);
1438 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1439 return base;
1440 }
1441
1442 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1443 Py_DECREF(base);
1444 return abs_name;
1445
Ben Lewis92420b32019-09-11 20:09:47 +10001446 no_parent_error:
1447 _PyErr_SetString(tstate, PyExc_ImportError,
1448 "attempted relative import "
1449 "with no known parent package");
1450
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001451 error:
1452 Py_XDECREF(package);
1453 return NULL;
1454}
1455
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001456static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001457import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001458{
1459 _Py_IDENTIFIER(_find_and_load);
1460 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001461 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001462 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001463 static int import_level;
1464 static _PyTime_t accumulated;
1465
1466 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1467
Steve Dowerb82e17e2019-05-23 08:45:22 -07001468 PyObject *sys_path = PySys_GetObject("path");
1469 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1470 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001471 if (_PySys_Audit(tstate, "import", "OOOOO",
1472 abs_name, Py_None, sys_path ? sys_path : Py_None,
1473 sys_meta_path ? sys_meta_path : Py_None,
1474 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001475 return NULL;
1476 }
1477
1478
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001479 /* XOptions is initialized after first some imports.
1480 * So we can't have negative cache before completed initialization.
1481 * Anyway, importlib._find_and_load is much slower than
1482 * _PyDict_GetItemIdWithError().
1483 */
1484 if (import_time) {
1485 static int header = 1;
1486 if (header) {
1487 fputs("import time: self [us] | cumulative | imported package\n",
1488 stderr);
1489 header = 0;
1490 }
1491
1492 import_level++;
1493 t1 = _PyTime_GetPerfCounter();
1494 accumulated = 0;
1495 }
1496
1497 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001498 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001499
1500 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1501 &PyId__find_and_load, abs_name,
1502 interp->import_func, NULL);
1503
1504 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001505 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001506 mod != NULL);
1507
1508 if (import_time) {
1509 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1510
1511 import_level--;
1512 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1513 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1514 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1515 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1516
1517 accumulated = accumulated_copy + cum;
1518 }
1519
1520 return mod;
1521}
1522
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001523PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001524PyImport_GetModule(PyObject *name)
1525{
1526 PyThreadState *tstate = _PyThreadState_GET();
1527 PyObject *mod;
1528
1529 mod = import_get_module(tstate, name);
1530 if (mod != NULL && mod != Py_None) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001531 if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001532 Py_DECREF(mod);
1533 remove_importlib_frames(tstate);
1534 return NULL;
1535 }
1536 }
1537 return mod;
1538}
1539
1540PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001541PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1542 PyObject *locals, PyObject *fromlist,
1543 int level)
1544{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001545 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001546 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001547 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001548 PyObject *final_mod = NULL;
1549 PyObject *mod = NULL;
1550 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001551 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001552 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001553
Brett Cannonfd074152012-04-14 14:10:13 -04001554 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001555 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001556 goto error;
1557 }
1558
1559 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1560 for added performance. */
1561
1562 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001563 _PyErr_SetString(tstate, PyExc_TypeError,
1564 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001565 goto error;
1566 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001567 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001568 goto error;
1569 }
1570 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001571 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001572 goto error;
1573 }
Brett Cannon849113a2016-01-22 15:25:50 -08001574
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001575 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001576 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001577 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001578 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001579 }
1580 else { /* level == 0 */
1581 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001582 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001583 goto error;
1584 }
Brett Cannonfd074152012-04-14 14:10:13 -04001585 abs_name = name;
1586 Py_INCREF(abs_name);
1587 }
1588
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001589 mod = import_get_module(tstate, abs_name);
1590 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001591 goto error;
1592 }
1593
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001594 if (mod != NULL && mod != Py_None) {
Antoine Pitrou2fd16ef2021-03-20 20:07:44 +01001595 if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001596 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001597 }
Brett Cannonfd074152012-04-14 14:10:13 -04001598 }
1599 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001600 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001601 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001602 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001603 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001604 }
1605 }
1606
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001607 has_from = 0;
1608 if (fromlist != NULL && fromlist != Py_None) {
1609 has_from = PyObject_IsTrue(fromlist);
1610 if (has_from < 0)
1611 goto error;
1612 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001613 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001614 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1615 if (level == 0 || len > 0) {
1616 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001617
Victor Stinner744c34e2016-05-20 11:36:13 +02001618 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1619 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001620 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001621 }
1622
Victor Stinner744c34e2016-05-20 11:36:13 +02001623 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001624 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001625 final_mod = mod;
1626 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001627 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001628 }
1629
Brett Cannonfd074152012-04-14 14:10:13 -04001630 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001631 PyObject *front = PyUnicode_Substring(name, 0, dot);
1632 if (front == NULL) {
1633 goto error;
1634 }
1635
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001636 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001637 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001638 }
1639 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001640 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001641 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001642 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001643 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001644 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001645 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001646 }
Brett Cannonfd074152012-04-14 14:10:13 -04001647
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001648 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001649 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001650 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001651 if (!_PyErr_Occurred(tstate)) {
1652 _PyErr_Format(tstate, PyExc_KeyError,
1653 "%R not in sys.modules as expected",
1654 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001655 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001656 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001657 }
Brett Cannonfd074152012-04-14 14:10:13 -04001658 }
1659 }
1660 else {
1661 final_mod = mod;
1662 Py_INCREF(mod);
1663 }
1664 }
1665 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001666 PyObject *path;
1667 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1668 goto error;
1669 }
1670 if (path) {
1671 Py_DECREF(path);
1672 final_mod = _PyObject_CallMethodIdObjArgs(
1673 interp->importlib, &PyId__handle_fromlist,
1674 mod, fromlist, interp->import_func, NULL);
1675 }
1676 else {
1677 final_mod = mod;
1678 Py_INCREF(mod);
1679 }
Brett Cannonfd074152012-04-14 14:10:13 -04001680 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001681
Brett Cannonfd074152012-04-14 14:10:13 -04001682 error:
1683 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001684 Py_XDECREF(mod);
1685 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001686 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001687 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001688 }
Brett Cannonfd074152012-04-14 14:10:13 -04001689 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001690}
1691
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001692PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001693PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001694 PyObject *fromlist, int level)
1695{
1696 PyObject *nameobj, *mod;
1697 nameobj = PyUnicode_FromString(name);
1698 if (nameobj == NULL)
1699 return NULL;
1700 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1701 fromlist, level);
1702 Py_DECREF(nameobj);
1703 return mod;
1704}
1705
1706
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001707/* Re-import a module of any kind and return its module object, WITH
1708 INCREMENTED REFERENCE COUNT */
1709
Guido van Rossum79f25d91997-04-29 20:08:16 +00001710PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001711PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001712{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001713 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001714 _Py_IDENTIFIER(reload);
1715 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001716 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1717 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001718 if (PyErr_Occurred()) {
1719 return NULL;
1720 }
1721
Robert Rouhanif40bd462020-05-01 16:28:06 -07001722 importlib = PyImport_ImportModule("importlib");
1723 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001724 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001727
Robert Rouhanif40bd462020-05-01 16:28:06 -07001728 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1729 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001730 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001731}
1732
1733
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001734/* Higher-level import emulator which emulates the "import" statement
1735 more accurately -- it invokes the __import__() function from the
1736 builtins of the current globals. This means that the import is
1737 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001738 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001739 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001740 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001741 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001742
1743PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001744PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001745{
junyixie88d99832021-03-22 17:47:10 +08001746 _Py_IDENTIFIER(__import__);
1747 _Py_IDENTIFIER(__builtins__);
1748
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001749 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyObject *globals = NULL;
1751 PyObject *import = NULL;
1752 PyObject *builtins = NULL;
1753 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 /* Initialize constant string objects */
junyixie88d99832021-03-22 17:47:10 +08001756 PyObject *import_str = _PyUnicode_FromId(&PyId___import__); // borrowed ref
1757 if (import_str == NULL) {
1758 return NULL;
1759 }
1760
1761 PyObject *builtins_str = _PyUnicode_FromId(&PyId___builtins__); // borrowed ref
1762 if (builtins_str == NULL) {
1763 return NULL;
1764 }
1765
1766 PyObject *from_list = PyList_New(0);
1767 if (from_list == NULL) {
1768 goto err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* Get the builtins from current globals */
1772 globals = PyEval_GetGlobals();
1773 if (globals != NULL) {
1774 Py_INCREF(globals);
1775 builtins = PyObject_GetItem(globals, builtins_str);
1776 if (builtins == NULL)
1777 goto err;
1778 }
1779 else {
1780 /* No globals -- use standard builtins, and fake globals */
1781 builtins = PyImport_ImportModuleLevel("builtins",
1782 NULL, NULL, NULL, 0);
junyixie88d99832021-03-22 17:47:10 +08001783 if (builtins == NULL) {
1784 goto err;
1785 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1787 if (globals == NULL)
1788 goto err;
1789 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 /* Get the __import__ function from the builtins */
1792 if (PyDict_Check(builtins)) {
1793 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001794 if (import == NULL) {
1795 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
1796 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 }
1798 else
1799 import = PyObject_GetAttr(builtins, import_str);
1800 if (import == NULL)
1801 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001804 Always use absolute import here.
1805 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
junyixie88d99832021-03-22 17:47:10 +08001807 globals, from_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001808 if (r == NULL)
1809 goto err;
1810 Py_DECREF(r);
1811
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001812 r = import_get_module(tstate, module_name);
1813 if (r == NULL && !_PyErr_Occurred(tstate)) {
1814 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001815 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001816
1817 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 Py_XDECREF(globals);
1819 Py_XDECREF(builtins);
1820 Py_XDECREF(import);
junyixie88d99832021-03-22 17:47:10 +08001821 Py_XDECREF(from_list);
Tim Peters50d8d372001-02-28 05:34:27 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001824}
1825
Brett Cannon4caa61d2014-01-09 19:03:32 -05001826/*[clinic input]
1827_imp.extension_suffixes
1828
1829Returns the list of file suffixes used to identify extension modules.
1830[clinic start generated code]*/
1831
Brett Cannon4caa61d2014-01-09 19:03:32 -05001832static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001833_imp_extension_suffixes_impl(PyObject *module)
1834/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 list = PyList_New(0);
1839 if (list == NULL)
1840 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001841#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01001842 const char *suffix;
1843 unsigned int index = 0;
1844
Brett Cannon2657df42012-05-04 15:20:40 -04001845 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1846 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (item == NULL) {
1848 Py_DECREF(list);
1849 return NULL;
1850 }
1851 if (PyList_Append(list, item) < 0) {
1852 Py_DECREF(list);
1853 Py_DECREF(item);
1854 return NULL;
1855 }
1856 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001857 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 }
Brett Cannon2657df42012-05-04 15:20:40 -04001859#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001861}
1862
Brett Cannon4caa61d2014-01-09 19:03:32 -05001863/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001864_imp.init_frozen
1865
1866 name: unicode
1867 /
1868
1869Initializes a frozen module.
1870[clinic start generated code]*/
1871
Brett Cannon4caa61d2014-01-09 19:03:32 -05001872static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001873_imp_init_frozen_impl(PyObject *module, PyObject *name)
1874/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001875{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001876 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 int ret;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001878
Victor Stinner53dc7352011-03-20 01:50:21 +01001879 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (ret < 0)
1881 return NULL;
1882 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001883 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001885 return import_add_module(tstate, name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001886}
1887
Brett Cannon4caa61d2014-01-09 19:03:32 -05001888/*[clinic input]
1889_imp.get_frozen_object
1890
1891 name: unicode
1892 /
1893
1894Create a code object for a frozen module.
1895[clinic start generated code]*/
1896
Brett Cannon4caa61d2014-01-09 19:03:32 -05001897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001898_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1899/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001902}
1903
Brett Cannon4caa61d2014-01-09 19:03:32 -05001904/*[clinic input]
1905_imp.is_frozen_package
1906
1907 name: unicode
1908 /
1909
1910Returns True if the module name is of a frozen package.
1911[clinic start generated code]*/
1912
Brett Cannon4caa61d2014-01-09 19:03:32 -05001913static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001914_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1915/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001918}
1919
Brett Cannon4caa61d2014-01-09 19:03:32 -05001920/*[clinic input]
1921_imp.is_builtin
1922
1923 name: unicode
1924 /
1925
1926Returns True if the module name corresponds to a built-in module.
1927[clinic start generated code]*/
1928
Guido van Rossum79f25d91997-04-29 20:08:16 +00001929static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001930_imp_is_builtin_impl(PyObject *module, PyObject *name)
1931/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001932{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001933 return PyLong_FromLong(is_builtin(name));
1934}
1935
1936/*[clinic input]
1937_imp.is_frozen
1938
1939 name: unicode
1940 /
1941
1942Returns True if the module name corresponds to a frozen module.
1943[clinic start generated code]*/
1944
Brett Cannon4caa61d2014-01-09 19:03:32 -05001945static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001946_imp_is_frozen_impl(PyObject *module, PyObject *name)
1947/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001948{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001949 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 p = find_frozen(name);
1952 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001953}
1954
Larry Hastings1df0b352015-08-24 19:53:56 -07001955/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1956static int
1957exec_builtin_or_dynamic(PyObject *mod) {
1958 PyModuleDef *def;
1959 void *state;
1960
1961 if (!PyModule_Check(mod)) {
1962 return 0;
1963 }
1964
1965 def = PyModule_GetDef(mod);
1966 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001967 return 0;
1968 }
Brett Cannon52794db2016-09-07 17:00:43 -07001969
Larry Hastings1df0b352015-08-24 19:53:56 -07001970 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001971 if (state) {
1972 /* Already initialized; skip reload */
1973 return 0;
1974 }
Brett Cannon52794db2016-09-07 17:00:43 -07001975
Larry Hastings1df0b352015-08-24 19:53:56 -07001976 return PyModule_ExecDef(mod, def);
1977}
1978
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001979#ifdef HAVE_DYNAMIC_LOADING
1980
Brett Cannon4caa61d2014-01-09 19:03:32 -05001981/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10001982_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05001983
Nick Coghland5cacbb2015-05-23 22:24:10 +10001984 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05001985 file: object = NULL
1986 /
1987
Nick Coghland5cacbb2015-05-23 22:24:10 +10001988Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05001989[clinic start generated code]*/
1990
Brett Cannon4caa61d2014-01-09 19:03:32 -05001991static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001992_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
1993/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001994{
Nick Coghland5cacbb2015-05-23 22:24:10 +10001995 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001996 FILE *fp;
1997
Nick Coghland5cacbb2015-05-23 22:24:10 +10001998 name = PyObject_GetAttrString(spec, "name");
1999 if (name == NULL) {
2000 return NULL;
2001 }
2002
2003 path = PyObject_GetAttrString(spec, "origin");
2004 if (path == NULL) {
2005 Py_DECREF(name);
2006 return NULL;
2007 }
2008
Serhiy Storchaka4db89882021-01-12 16:43:32 +02002009 PyThreadState *tstate = _PyThreadState_GET();
2010 mod = import_find_extension(tstate, name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002011 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002012 Py_DECREF(name);
2013 Py_DECREF(path);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002014 return mod;
2015 }
2016
Brett Cannon4caa61d2014-01-09 19:03:32 -05002017 if (file != NULL) {
2018 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002019 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002020 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002021 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002023 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002025 else
2026 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002027
2028 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2029
2030 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002031 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (fp)
2033 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002034 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002035}
2036
Nick Coghland5cacbb2015-05-23 22:24:10 +10002037/*[clinic input]
2038_imp.exec_dynamic -> int
2039
2040 mod: object
2041 /
2042
2043Initialize an extension module.
2044[clinic start generated code]*/
2045
2046static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002047_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2048/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002049{
Larry Hastings1df0b352015-08-24 19:53:56 -07002050 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002051}
2052
2053
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002054#endif /* HAVE_DYNAMIC_LOADING */
2055
Larry Hastings7726ac92014-01-31 22:03:12 -08002056/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002057_imp.exec_builtin -> int
2058
2059 mod: object
2060 /
2061
2062Initialize a built-in module.
2063[clinic start generated code]*/
2064
2065static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002066_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2067/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002068{
2069 return exec_builtin_or_dynamic(mod);
2070}
2071
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002072/*[clinic input]
2073_imp.source_hash
2074
2075 key: long
2076 source: Py_buffer
2077[clinic start generated code]*/
2078
2079static PyObject *
2080_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2081/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2082{
Benjamin Peterson83620772017-12-09 12:18:56 -08002083 union {
2084 uint64_t x;
2085 char data[sizeof(uint64_t)];
2086 } hash;
2087 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002088#if !PY_LITTLE_ENDIAN
2089 // Force to little-endian. There really ought to be a succinct standard way
2090 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002091 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2092 char tmp = hash.data[i];
2093 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2094 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002095 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002096#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002097 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002098}
2099
Barry Warsaw28a691b2010-04-17 00:19:56 +00002100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002101PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002102"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002103
Guido van Rossum79f25d91997-04-29 20:08:16 +00002104static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002105 _IMP_EXTENSION_SUFFIXES_METHODDEF
2106 _IMP_LOCK_HELD_METHODDEF
2107 _IMP_ACQUIRE_LOCK_METHODDEF
2108 _IMP_RELEASE_LOCK_METHODDEF
2109 _IMP_GET_FROZEN_OBJECT_METHODDEF
2110 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002111 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002112 _IMP_INIT_FROZEN_METHODDEF
2113 _IMP_IS_BUILTIN_METHODDEF
2114 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002115 _IMP_CREATE_DYNAMIC_METHODDEF
2116 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002117 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002118 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002119 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002120 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002121};
2122
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002123
Victor Stinner62230712020-11-18 23:18:29 +01002124static int
2125imp_module_exec(PyObject *module)
2126{
2127 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
2128 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
2129 if (pyc_mode == NULL) {
2130 return -1;
2131 }
2132 if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
2133 Py_DECREF(pyc_mode);
2134 return -1;
2135 }
2136 Py_DECREF(pyc_mode);
2137
2138 return 0;
2139}
2140
2141
2142static PyModuleDef_Slot imp_slots[] = {
2143 {Py_mod_exec, imp_module_exec},
2144 {0, NULL}
2145};
2146
2147static struct PyModuleDef imp_module = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyModuleDef_HEAD_INIT,
Victor Stinner62230712020-11-18 23:18:29 +01002149 .m_name = "_imp",
2150 .m_doc = doc_imp,
2151 .m_size = 0,
2152 .m_methods = imp_methods,
2153 .m_slots = imp_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00002154};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002155
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002156PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002157PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002158{
Victor Stinner62230712020-11-18 23:18:29 +01002159 return PyModuleDef_Init(&imp_module);
2160}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002161
Victor Stinner62230712020-11-18 23:18:29 +01002162
2163// Import the _imp extension by calling manually _imp.create_builtin() and
2164// _imp.exec_builtin() since importlib is not initialized yet. Initializing
2165// importlib requires the _imp module: this function fix the bootstrap issue.
2166PyObject*
2167_PyImport_BootstrapImp(PyThreadState *tstate)
2168{
2169 PyObject *name = PyUnicode_FromString("_imp");
2170 if (name == NULL) {
2171 return NULL;
Victor Stinner410b85a2019-05-13 17:12:45 +02002172 }
2173
Victor Stinner62230712020-11-18 23:18:29 +01002174 // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
2175 // an object with just a name attribute.
2176 //
2177 // _imp.__spec__ is overriden by importlib._bootstrap._instal() anyway.
2178 PyObject *attrs = Py_BuildValue("{sO}", "name", name);
2179 if (attrs == NULL) {
2180 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002181 }
Victor Stinner62230712020-11-18 23:18:29 +01002182 PyObject *spec = _PyNamespace_New(attrs);
2183 Py_DECREF(attrs);
2184 if (spec == NULL) {
2185 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002186 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002187
Victor Stinner62230712020-11-18 23:18:29 +01002188 // Create the _imp module from its definition.
2189 PyObject *mod = create_builtin(tstate, name, spec);
2190 Py_CLEAR(name);
2191 Py_DECREF(spec);
2192 if (mod == NULL) {
2193 goto error;
2194 }
2195 assert(mod != Py_None); // not found
2196
2197 // Execute the _imp module: call imp_module_exec().
2198 if (exec_builtin_or_dynamic(mod) < 0) {
2199 Py_DECREF(mod);
2200 goto error;
2201 }
2202 return mod;
2203
2204error:
2205 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002207}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002208
2209
Guido van Rossumb18618d2000-05-03 23:44:39 +00002210/* API for embedding applications that want to add their own entries
2211 to the table of built-in modules. This should normally be called
2212 *before* Py_Initialize(). When the table resize fails, -1 is
2213 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002214
2215 After a similar function by Just van Rossum. */
2216
2217int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002218PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002221 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002222 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Count the number of entries in both tables */
2225 for (n = 0; newtab[n].name != NULL; n++)
2226 ;
2227 if (n == 0)
2228 return 0; /* Nothing to do */
2229 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2230 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002231
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002232 /* Force default raw memory allocator to get a known allocator to be able
2233 to release the memory in _PyImport_Fini2() */
2234 PyMemAllocatorEx old_alloc;
2235 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002238 p = NULL;
2239 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002240 size_t size = sizeof(struct _inittab) * (i + n + 1);
2241 p = PyMem_RawRealloc(inittab_copy, size);
2242 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002243 if (p == NULL) {
2244 res = -1;
2245 goto done;
2246 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002247
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002248 /* Copy the tables into the new memory at the first call
2249 to PyImport_ExtendInittab(). */
2250 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002252 }
2253 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2254 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002255
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002256done:
2257 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2258 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002259}
2260
2261/* Shorthand to add a single entry given a name and a function */
2262
2263int
Brett Cannona826f322009-04-02 03:41:46 +00002264PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002269
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002270 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002274}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002275
2276#ifdef __cplusplus
2277}
2278#endif