blob: b898a2bd9260de7d87449a41f9664621d5a0c089 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module definition and import implementation */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner62230712020-11-18 23:18:29 +01007#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner61691d82019-10-02 23:51:20 +02008#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02009#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010010#include "pycore_pyhash.h"
11#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020012#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020013#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
14#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010015#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000016#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000019#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020020#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000021
Guido van Rossum55a83382000-09-20 20:31:38 +000022#ifdef HAVE_FCNTL_H
23#include <fcntl.h>
24#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000026extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000028
Barry Warsaw28a691b2010-04-17 00:19:56 +000029#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000030
Victor Stinner0a28f8d2019-06-19 02:54:39 +020031/* Forward references */
32static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
33
Victor Stinner95872862011-03-07 18:20:56 +010034/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000035static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000036
Guido van Rossum771c6c81997-10-31 18:37:24 +000037/* This table is defined in config.c: */
38extern struct _inittab _PyImport_Inittab[];
39
40struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010041static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000042
Hai Shi46874c22020-01-30 17:20:25 -060043_Py_IDENTIFIER(__path__);
44_Py_IDENTIFIER(__spec__);
45
Brett Cannon4caa61d2014-01-09 19:03:32 -050046/*[clinic input]
47module _imp
48[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030049/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040050
51#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050052
Guido van Rossum1ae940a1995-01-02 19:04:15 +000053/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054
Victor Stinner331a6a52019-05-27 16:39:22 +020055PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020056_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040057{
ukwksk5e6312c2018-05-15 04:10:52 +090058 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040059 int err = 0;
60
61 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020062 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020063 _PyErr_SetString(tstate, PyExc_RuntimeError,
64 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040065 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020066 }
Brett Cannonfd074152012-04-14 14:10:13 -040067
Victor Stinnerda7933e2020-04-13 03:04:28 +020068 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +020069 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -040070 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020071 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
ukwksk5e6312c2018-05-15 04:10:52 +090073 zipimport = PyImport_ImportModule("zipimport");
74 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020075 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020076 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 }
80 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020081 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090082 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020083 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090084 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020086 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020087 if (verbose) {
88 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
89 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 }
91 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -040092 /* sys.path_hooks.insert(0, zipimporter) */
93 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -040095 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -040097 }
Victor Stinner410b85a2019-05-13 17:12:45 +020098 if (verbose) {
99 PySys_WriteStderr("# installed zipimport hook\n");
100 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 }
102 }
Brett Cannonfd074152012-04-14 14:10:13 -0400103
Victor Stinner331a6a52019-05-27 16:39:22 +0200104 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400105
106 error:
107 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200108 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000109}
110
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000111/* Locking primitives to prevent parallel imports of the same module
112 in different threads to return with a partially loaded module.
113 These calls are serialized by the global interpreter lock. */
114
Victor Stinner26881c82020-06-02 15:51:37 +0200115static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200116static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000117static int import_lock_level = 0;
118
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000119void
120_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000121{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200122 unsigned long me = PyThread_get_thread_ident();
123 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 return; /* Too bad */
125 if (import_lock == NULL) {
126 import_lock = PyThread_allocate_lock();
127 if (import_lock == NULL)
128 return; /* Nothing much we can do. */
129 }
130 if (import_lock_thread == me) {
131 import_lock_level++;
132 return;
133 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200134 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
135 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 {
137 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200138 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 PyEval_RestoreThread(tstate);
140 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100141 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 import_lock_thread = me;
143 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000144}
145
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000146int
147_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200149 unsigned long me = PyThread_get_thread_ident();
150 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 return 0; /* Too bad */
152 if (import_lock_thread != me)
153 return -1;
154 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100155 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200157 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 PyThread_release_lock(import_lock);
159 }
160 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000161}
162
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900163#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200164/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000165 created child processes do not share locks with the parent.
166 We now acquire the import lock around fork() calls but on some platforms
167 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200168PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000169_PyImport_ReInitLock(void)
170{
Christian Heimes418fd742015-04-19 21:08:42 +0200171 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900172 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200173 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200174 }
175 }
Victor Stinner26881c82020-06-02 15:51:37 +0200176
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000177 if (import_lock_level > 1) {
178 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200179 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200180 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000181 import_lock_thread = me;
182 import_lock_level--;
183 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200184 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000185 import_lock_level = 0;
186 }
Victor Stinner26881c82020-06-02 15:51:37 +0200187 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000188}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900189#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000190
Brett Cannon4caa61d2014-01-09 19:03:32 -0500191/*[clinic input]
192_imp.lock_held
193
194Return True if the import lock is currently held, else False.
195
196On platforms without threads, return False.
197[clinic start generated code]*/
198
Brett Cannon4caa61d2014-01-09 19:03:32 -0500199static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300200_imp_lock_held_impl(PyObject *module)
201/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000202{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200203 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000204}
205
Brett Cannon4caa61d2014-01-09 19:03:32 -0500206/*[clinic input]
207_imp.acquire_lock
208
209Acquires the interpreter's import lock for the current thread.
210
211This lock should be used by import hooks to ensure thread-safety when importing
212modules. On platforms without threads, this function does nothing.
213[clinic start generated code]*/
214
Brett Cannon4caa61d2014-01-09 19:03:32 -0500215static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300216_imp_acquire_lock_impl(PyObject *module)
217/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200220 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000221}
222
Brett Cannon4caa61d2014-01-09 19:03:32 -0500223/*[clinic input]
224_imp.release_lock
225
226Release the interpreter's import lock.
227
228On platforms without threads, this function does nothing.
229[clinic start generated code]*/
230
Brett Cannon4caa61d2014-01-09 19:03:32 -0500231static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300232_imp_release_lock_impl(PyObject *module)
233/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (_PyImport_ReleaseLock() < 0) {
236 PyErr_SetString(PyExc_RuntimeError,
237 "not holding the import lock");
238 return NULL;
239 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200240 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000241}
242
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100243void
244_PyImport_Fini(void)
245{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200246 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100247 if (import_lock != NULL) {
248 PyThread_free_lock(import_lock);
249 import_lock = NULL;
250 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100251}
252
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100253void
254_PyImport_Fini2(void)
255{
256 /* Use the same memory allocator than PyImport_ExtendInittab(). */
257 PyMemAllocatorEx old_alloc;
258 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
259
260 /* Free memory allocated by PyImport_ExtendInittab() */
261 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700262 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100263
264 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
265}
266
Guido van Rossum25ce5661997-08-02 03:10:38 +0000267/* Helper for sys */
268
269PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000270PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271{
Victor Stinner81a7be32020-04-14 15:14:01 +0200272 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600273 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100274 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600275 }
Eric Snow93c92f72017-09-13 23:46:04 -0700276 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000277}
278
Eric Snowd393c1b2017-09-14 12:18:12 -0600279/* In some corner cases it is important to be sure that the import
280 machinery has been initialized (or not cleaned up yet). For
281 example, see issue #4236 and PyModule_Create2(). */
282
283int
284_PyImport_IsInitialized(PyInterpreterState *interp)
285{
286 if (interp->modules == NULL)
287 return 0;
288 return 1;
289}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000290
Eric Snow3f9eee62017-09-15 16:35:20 -0600291PyObject *
292_PyImport_GetModuleId(struct _Py_Identifier *nameid)
293{
294 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
295 if (name == NULL) {
296 return NULL;
297 }
298 return PyImport_GetModule(name);
299}
300
301int
302_PyImport_SetModule(PyObject *name, PyObject *m)
303{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100304 PyInterpreterState *interp = _PyInterpreterState_GET();
305 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600306 return PyObject_SetItem(modules, name, m);
307}
308
309int
310_PyImport_SetModuleString(const char *name, PyObject *m)
311{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100312 PyInterpreterState *interp = _PyInterpreterState_GET();
313 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600314 return PyMapping_SetItemString(modules, name, m);
315}
316
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200317static PyObject *
318import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600319{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200320 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600321 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200322 _PyErr_SetString(tstate, PyExc_RuntimeError,
323 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600324 return NULL;
325 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200326
327 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600328 Py_INCREF(modules);
329 if (PyDict_CheckExact(modules)) {
330 m = PyDict_GetItemWithError(modules, name); /* borrowed */
331 Py_XINCREF(m);
332 }
333 else {
334 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200335 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
336 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600337 }
338 }
339 Py_DECREF(modules);
340 return m;
341}
342
343
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100344static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100345import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200346{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100347 PyObject *spec;
348
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100349 _Py_IDENTIFIER(_lock_unlock_module);
350
351 /* Optimization: only call _bootstrap._lock_unlock_module() if
352 __spec__._initializing is true.
353 NOTE: because of this, initializing must be set *before*
354 stuffing the new module in sys.modules.
355 */
356 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
357 int busy = _PyModuleSpec_IsInitializing(spec);
358 Py_XDECREF(spec);
359 if (busy) {
360 /* Wait until module is done importing. */
361 PyObject *value = _PyObject_CallMethodIdOneArg(
362 interp->importlib, &PyId__lock_unlock_module, name);
363 if (value == NULL) {
364 return -1;
365 }
366 Py_DECREF(value);
367 }
368 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200369}
370
371
Barry Warsaw28a691b2010-04-17 00:19:56 +0000372/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000373
374long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000376{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200377 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200378 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600379 PyObject *external, *pyc_magic;
380
381 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
382 if (external == NULL)
383 return -1;
384 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
385 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400386 if (pyc_magic == NULL)
387 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200388 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700389 Py_DECREF(pyc_magic);
390 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000391}
392
393
Brett Cannon3adc7b72012-07-09 14:22:12 -0400394extern const char * _PySys_ImplCacheTag;
395
Barry Warsaw28a691b2010-04-17 00:19:56 +0000396const char *
397PyImport_GetMagicTag(void)
398{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400399 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000400}
401
Brett Cannon98979b82012-07-02 15:13:11 -0400402
Guido van Rossum25ce5661997-08-02 03:10:38 +0000403/* Magic for extension modules (built-in as well as dynamically
404 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200405 once, we keep a static dictionary 'extensions' keyed by the tuple
406 (module name, module name) (for built-in modules) or by
407 (filename, module name) (for dynamically loaded modules), containing these
408 modules. A copy of the module's dictionary is stored by calling
409 _PyImport_FixupExtensionObject() immediately after the module initialization
410 function succeeds. A copy can be retrieved from there by calling
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200411 import_find_extension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000412
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000413 Modules which do support multiple initialization set their m_size
414 field to a non-negative number (indicating the size of the
415 module-specific state). They are still recorded in the extensions
416 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000417*/
418
419int
Victor Stinner95872862011-03-07 18:20:56 +0100420_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200421 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (mod == NULL || !PyModule_Check(mod)) {
424 PyErr_BadInternalCall();
425 return -1;
426 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100427
428 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (!def) {
430 PyErr_BadInternalCall();
431 return -1;
432 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100433
434 PyThreadState *tstate = _PyThreadState_GET();
435 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100437 }
438 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600439 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 return -1;
441 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100442
Victor Stinner101bf692021-02-19 13:33:31 +0100443 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner82c83bd2019-11-22 18:52:27 +0100444 if (def->m_size == -1) {
445 if (def->m_base.m_copy) {
446 /* Somebody already imported the module,
447 likely under a different name.
448 XXX this should really not happen. */
449 Py_CLEAR(def->m_base.m_copy);
450 }
451 PyObject *dict = PyModule_GetDict(mod);
452 if (dict == NULL) {
453 return -1;
454 }
455 def->m_base.m_copy = PyDict_Copy(dict);
456 if (def->m_base.m_copy == NULL) {
457 return -1;
458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100460
461 if (extensions == NULL) {
462 extensions = PyDict_New();
463 if (extensions == NULL) {
464 return -1;
465 }
466 }
467
468 PyObject *key = PyTuple_Pack(2, filename, name);
469 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100471 }
472 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
473 Py_DECREF(key);
474 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000480}
481
Victor Stinner49d3f252010-10-17 01:24:53 +0000482int
Eric Snowd393c1b2017-09-14 12:18:12 -0600483_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000484{
485 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100486 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100487 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100488 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000489 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600490 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100491 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000492 return res;
493}
494
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200495static PyObject *
496import_find_extension(PyThreadState *tstate, PyObject *name,
497 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200499 if (extensions == NULL) {
500 return NULL;
501 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600502
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200503 PyObject *key = PyTuple_Pack(2, filename, name);
504 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200506 }
507 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500508 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200509 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200511 }
512
513 PyObject *mod, *mdict;
514 PyObject *modules = tstate->interp->modules;
515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (def->m_size == -1) {
517 /* Module does not support repeated initialization */
518 if (def->m_base.m_copy == NULL)
519 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200520 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (mod == NULL)
522 return NULL;
523 mdict = PyModule_GetDict(mod);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200524 if (mdict == NULL) {
525 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200527 }
528 if (PyDict_Update(mdict, def->m_base.m_copy)) {
529 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200531 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 }
533 else {
534 if (def->m_base.m_init == NULL)
535 return NULL;
536 mod = def->m_base.m_init();
537 if (mod == NULL)
538 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600539 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200540 Py_DECREF(mod);
541 return NULL;
542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100544 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600545 PyMapping_DelItem(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200546 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 return NULL;
548 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200549
Victor Stinnerda7933e2020-04-13 03:04:28 +0200550 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200551 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100552 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200553 name, filename);
554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000556}
557
558
559/* Get the module object corresponding to a module name.
560 First check the modules dictionary if there's one there,
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200561 if not, create a new one and insert it in the modules dictionary. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000562
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200563static PyObject *
564import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000565{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200566 PyObject *modules = tstate->interp->modules;
567 if (modules == NULL) {
568 _PyErr_SetString(tstate, PyExc_RuntimeError,
569 "no import module dictionary");
570 return NULL;
571 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600572
Eric Snow86b7afd2017-09-04 17:54:09 -0600573 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600574 if (PyDict_CheckExact(modules)) {
575 m = PyDict_GetItemWithError(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200576 Py_XINCREF(m);
Eric Snow3f9eee62017-09-15 16:35:20 -0600577 }
578 else {
579 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000580 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600581 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200582 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
583 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600584 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200585 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200586 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200587 return NULL;
588 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600589 if (m != NULL && PyModule_Check(m)) {
590 return m;
591 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200592 Py_XDECREF(m);
Victor Stinner27ee0892011-03-04 12:57:09 +0000593 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (m == NULL)
595 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600596 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 Py_DECREF(m);
598 return NULL;
599 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000602}
603
Victor Stinner27ee0892011-03-04 12:57:09 +0000604PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200605PyImport_AddModuleObject(PyObject *name)
606{
607 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200608 PyObject *mod = import_add_module(tstate, name);
609 if (mod) {
610 PyObject *ref = PyWeakref_NewRef(mod, NULL);
611 Py_DECREF(mod);
612 if (ref == NULL) {
613 return NULL;
614 }
615 mod = PyWeakref_GetObject(ref);
616 Py_DECREF(ref);
617 }
618 return mod; /* borrowed reference */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200619}
620
621
622PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000623PyImport_AddModule(const char *name)
624{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200625 PyObject *nameobj = PyUnicode_FromString(name);
626 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000627 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200628 }
629 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000630 Py_DECREF(nameobj);
631 return module;
632}
633
634
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300635/* Remove name from sys.modules, if it's there.
636 * Can be called with an exception raised.
637 * If fail to remove name a new exception will be chained with the old
638 * exception, otherwise the old exception is preserved.
639 */
Tim Peters1cd70172004-08-02 03:52:12 +0000640static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200641remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000642{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600643 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200644 _PyErr_Fetch(tstate, &type, &value, &traceback);
645
646 PyObject *modules = tstate->interp->modules;
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300647 if (PyDict_CheckExact(modules)) {
648 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
649 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600650 }
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300651 else if (PyMapping_DelItem(modules, name) < 0) {
652 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
653 _PyErr_Clear(tstate);
654 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600655 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200656
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300657 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000658}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000659
Christian Heimes3b06e532008-01-07 20:12:44 +0000660
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000661/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000662 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
663 * removed from sys.modules, to avoid leaving damaged module objects
664 * in sys.modules. The caller may wish to restore the original
665 * module object (if any) in this case; PyImport_ReloadModule is an
666 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000667 *
668 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
669 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000670 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000671PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300672PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 return PyImport_ExecCodeModuleWithPathnames(
675 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000676}
677
678PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300679PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return PyImport_ExecCodeModuleWithPathnames(
682 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000683}
684
685PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300686PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
687 const char *pathname,
688 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000689{
Victor Stinner27ee0892011-03-04 12:57:09 +0000690 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600691 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000692
693 nameobj = PyUnicode_FromString(name);
694 if (nameobj == NULL)
695 return NULL;
696
Victor Stinner27ee0892011-03-04 12:57:09 +0000697 if (cpathname != NULL) {
698 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
699 if (cpathobj == NULL)
700 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400701 }
702 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000703 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400704
705 if (pathname != NULL) {
706 pathobj = PyUnicode_DecodeFSDefault(pathname);
707 if (pathobj == NULL)
708 goto error;
709 }
710 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200711 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400712 _Py_IDENTIFIER(_get_sourcefile);
713
714 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100715 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400716 }
717
Eric Snow32439d62015-05-02 19:15:18 -0600718 external= PyObject_GetAttrString(interp->importlib,
719 "_bootstrap_external");
720 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200721 pathobj = _PyObject_CallMethodIdOneArg(
722 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600723 Py_DECREF(external);
724 }
Brett Cannona6473f92012-07-13 13:57:03 -0400725 if (pathobj == NULL)
726 PyErr_Clear();
727 }
728 else
729 pathobj = NULL;
730
Victor Stinner27ee0892011-03-04 12:57:09 +0000731 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
732error:
733 Py_DECREF(nameobj);
734 Py_XDECREF(pathobj);
735 Py_XDECREF(cpathobj);
736 return m;
737}
738
Brett Cannon18fc4e72014-04-04 10:01:46 -0400739static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200740module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000741{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200742 _Py_IDENTIFIER(__builtins__);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200743 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000744
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200745 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (m == NULL)
747 return NULL;
748 /* If the module is being reloaded, we get the old module back
749 and re-use its dict to exec the new code. */
750 d = PyModule_GetDict(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200751 int r = _PyDict_ContainsId(d, &PyId___builtins__);
752 if (r == 0) {
753 r = _PyDict_SetItemId(d, &PyId___builtins__,
754 PyEval_GetBuiltins());
755 }
756 if (r < 0) {
757 remove_module(tstate, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200758 Py_DECREF(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200759 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400761
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200762 Py_INCREF(d);
763 Py_DECREF(m);
764 return d;
Brett Cannon18fc4e72014-04-04 10:01:46 -0400765}
766
767static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200768exec_code_in_module(PyThreadState *tstate, PyObject *name,
769 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -0400770{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400771 PyObject *v, *m;
772
773 v = PyEval_EvalCode(code_object, module_dict, module_dict);
774 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200775 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400776 return NULL;
777 }
778 Py_DECREF(v);
779
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200780 m = import_get_module(tstate, name);
781 if (m == NULL && !_PyErr_Occurred(tstate)) {
782 _PyErr_Format(tstate, PyExc_ImportError,
783 "Loaded module %R not found in sys.modules",
784 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400785 }
786
Brett Cannon18fc4e72014-04-04 10:01:46 -0400787 return m;
788}
789
790PyObject*
791PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
792 PyObject *cpathname)
793{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200794 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600795 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600796 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400797
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200798 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400799 if (d == NULL) {
800 return NULL;
801 }
802
Eric Snow08197a42014-05-12 17:54:55 -0600803 if (pathname == NULL) {
804 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200806 external = PyObject_GetAttrString(tstate->interp->importlib,
807 "_bootstrap_external");
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200808 if (external == NULL) {
809 Py_DECREF(d);
Eric Snow32439d62015-05-02 19:15:18 -0600810 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200811 }
Eric Snow32439d62015-05-02 19:15:18 -0600812 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600813 &PyId__fix_up_module,
814 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600815 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600816 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600817 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200818 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200820 Py_DECREF(d);
Eric Snow08197a42014-05-12 17:54:55 -0600821 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000822}
823
824
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000825static void
826update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyObject *constants, *tmp;
829 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (PyUnicode_Compare(co->co_filename, oldname))
832 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000833
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200834 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300835 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 constants = co->co_consts;
838 n = PyTuple_GET_SIZE(constants);
839 for (i = 0; i < n; i++) {
840 tmp = PyTuple_GET_ITEM(constants, i);
841 if (PyCode_Check(tmp))
842 update_code_filenames((PyCodeObject *)tmp,
843 oldname, newname);
844 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000845}
846
Victor Stinner2f42ae52011-03-20 00:41:24 +0100847static void
848update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000849{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100850 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000851
Victor Stinner2f42ae52011-03-20 00:41:24 +0100852 if (PyUnicode_Compare(co->co_filename, newname) == 0)
853 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 oldname = co->co_filename;
856 Py_INCREF(oldname);
857 update_code_filenames(co, oldname, newname);
858 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000859}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000860
Brett Cannon4caa61d2014-01-09 19:03:32 -0500861/*[clinic input]
862_imp._fix_co_filename
863
864 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
865 Code object to change.
866
867 path: unicode
868 File path to use.
869 /
870
871Changes code.co_filename to specify the passed-in file path.
872[clinic start generated code]*/
873
Brett Cannon4caa61d2014-01-09 19:03:32 -0500874static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300875_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400876 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300877/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700878
Brett Cannon4caa61d2014-01-09 19:03:32 -0500879{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500880 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700881
882 Py_RETURN_NONE;
883}
884
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000886/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700887static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000888
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000889
890/* Helper to test for built-in module */
891
892static int
Victor Stinner95872862011-03-07 18:20:56 +0100893is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000894{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200895 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200897 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (PyImport_Inittab[i].initfunc == NULL)
899 return -1;
900 else
901 return 1;
902 }
903 }
904 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000905}
906
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000907
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700908/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000909 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000910 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000911 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700912 this tells our caller that the path based finder could not find
913 a finder for this path item. Cache the result in
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200914 path_importer_cache. */
Just van Rossum52e14d62002-12-30 22:08:05 +0000915
916static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200917get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
918 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyObject *importer;
921 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* These conditions are the caller's responsibility: */
924 assert(PyList_Check(path_hooks));
925 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 nhooks = PyList_Size(path_hooks);
928 if (nhooks < 0)
929 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000930
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200931 importer = PyDict_GetItemWithError(path_importer_cache, p);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200932 if (importer != NULL || _PyErr_Occurred(tstate)) {
933 Py_XINCREF(importer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 return importer;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200935 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* set path_importer_cache[p] to None to avoid recursion */
938 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
939 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 for (j = 0; j < nhooks; j++) {
942 PyObject *hook = PyList_GetItem(path_hooks, j);
943 if (hook == NULL)
944 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +0100945 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (importer != NULL)
947 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000948
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200949 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 return NULL;
951 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200952 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 }
954 if (importer == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200955 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200957 if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 Py_DECREF(importer);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200959 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 }
961 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000962}
963
Benjamin Petersone5024512018-09-12 12:06:42 -0700964PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200965PyImport_GetImporter(PyObject *path)
966{
967 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200968 PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
969 PyObject *path_hooks = PySys_GetObject("path_hooks");
970 if (path_importer_cache == NULL || path_hooks == NULL) {
971 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200973 return get_path_importer(tstate, path_importer_cache, path_hooks, path);
Christian Heimes9cd17752007-11-18 19:35:23 +0000974}
975
Victor Stinner62230712020-11-18 23:18:29 +0100976static PyObject*
977create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
978{
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200979 PyObject *mod = import_find_extension(tstate, name, name);
Victor Stinner62230712020-11-18 23:18:29 +0100980 if (mod || _PyErr_Occurred(tstate)) {
Victor Stinner62230712020-11-18 23:18:29 +0100981 return mod;
982 }
983
984 PyObject *modules = tstate->interp->modules;
985 for (struct _inittab *p = PyImport_Inittab; p->name != NULL; p++) {
986 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
987 if (p->initfunc == NULL) {
988 /* Cannot re-init internal module ("sys" or "builtins") */
989 return PyImport_AddModuleObject(name);
990 }
991
992 mod = (*p->initfunc)();
993 if (mod == NULL) {
994 return NULL;
995 }
996
997 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
998 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
999 }
1000 else {
1001 /* Remember pointer to module init function. */
1002 PyModuleDef *def = PyModule_GetDef(mod);
1003 if (def == NULL) {
1004 return NULL;
1005 }
1006
1007 def->m_base.m_init = p->initfunc;
1008 if (_PyImport_FixupExtensionObject(mod, name, name,
1009 modules) < 0) {
1010 return NULL;
1011 }
1012 return mod;
1013 }
1014 }
1015 }
1016
1017 // not found
1018 Py_RETURN_NONE;
1019}
1020
1021
1022
Nick Coghland5cacbb2015-05-23 22:24:10 +10001023/*[clinic input]
1024_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001025
Nick Coghland5cacbb2015-05-23 22:24:10 +10001026 spec: object
1027 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001028
Nick Coghland5cacbb2015-05-23 22:24:10 +10001029Create an extension module.
1030[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001031
Nick Coghland5cacbb2015-05-23 22:24:10 +10001032static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001033_imp_create_builtin(PyObject *module, PyObject *spec)
1034/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001035{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001036 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001037
Victor Stinner62230712020-11-18 23:18:29 +01001038 PyObject *name = PyObject_GetAttrString(spec, "name");
Nick Coghland5cacbb2015-05-23 22:24:10 +10001039 if (name == NULL) {
1040 return NULL;
1041 }
1042
Victor Stinner62230712020-11-18 23:18:29 +01001043 PyObject *mod = create_builtin(tstate, name, spec);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001044 Py_DECREF(name);
Victor Stinner62230712020-11-18 23:18:29 +01001045 return mod;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001046}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001047
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001049/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001050
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001051static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001052find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001053{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001054 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001055
Victor Stinner53dc7352011-03-20 01:50:21 +01001056 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 for (p = PyImport_FrozenModules; ; p++) {
1060 if (p->name == NULL)
1061 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001062 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 break;
1064 }
1065 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001066}
1067
Guido van Rossum79f25d91997-04-29 20:08:16 +00001068static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001069get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001070{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001071 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 if (p == NULL) {
1075 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001076 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 name);
1078 return NULL;
1079 }
1080 if (p->code == NULL) {
1081 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001082 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 name);
1084 return NULL;
1085 }
1086 size = p->size;
1087 if (size < 0)
1088 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001089 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001090}
1091
Brett Cannon8d110132009-03-15 02:20:16 +00001092static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001093is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001094{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001095 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (p == NULL) {
1099 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001100 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 name);
1102 return NULL;
1103 }
Brett Cannon8d110132009-03-15 02:20:16 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (size < 0)
1108 Py_RETURN_TRUE;
1109 else
1110 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001111}
1112
1113
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001114/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001115 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001116 an exception set if the initialization failed.
1117 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001118
1119int
Victor Stinner53dc7352011-03-20 01:50:21 +01001120PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001121{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001122 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001123 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001124 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 int ispackage;
1126 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001127
Victor Stinner53dc7352011-03-20 01:50:21 +01001128 p = find_frozen(name);
1129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (p == NULL)
1131 return 0;
1132 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001133 _PyErr_Format(tstate, PyExc_ImportError,
1134 "Excluded frozen object named %R",
1135 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 return -1;
1137 }
1138 size = p->size;
1139 ispackage = (size < 0);
1140 if (ispackage)
1141 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001142 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (co == NULL)
1144 return -1;
1145 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001146 _PyErr_Format(tstate, PyExc_TypeError,
1147 "frozen object %R is not a code object",
1148 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 goto err_return;
1150 }
1151 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001152 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001153 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001155 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (m == NULL)
1157 goto err_return;
1158 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001159 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (l == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001161 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 goto err_return;
1163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 err = PyDict_SetItemString(d, "__path__", l);
1165 Py_DECREF(l);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001166 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (err != 0)
1168 goto err_return;
1169 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001170 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001171 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001172 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001173 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001174 m = exec_code_in_module(tstate, name, d, co);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001175 Py_DECREF(d);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001176 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001178 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 Py_DECREF(co);
1180 Py_DECREF(m);
1181 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001182
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001183err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 Py_DECREF(co);
1185 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001186}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001187
Victor Stinner53dc7352011-03-20 01:50:21 +01001188int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001189PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001190{
1191 PyObject *nameobj;
1192 int ret;
1193 nameobj = PyUnicode_InternFromString(name);
1194 if (nameobj == NULL)
1195 return -1;
1196 ret = PyImport_ImportFrozenModuleObject(nameobj);
1197 Py_DECREF(nameobj);
1198 return ret;
1199}
1200
Guido van Rossum74e6a111994-08-29 12:54:38 +00001201
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001202/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001203 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001204
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001206PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *pname;
1209 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 pname = PyUnicode_FromString(name);
1212 if (pname == NULL)
1213 return NULL;
1214 result = PyImport_Import(pname);
1215 Py_DECREF(pname);
1216 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001217}
1218
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001219
Christian Heimes072c0f12008-01-03 23:01:04 +00001220/* Import a module without blocking
1221 *
1222 * At first it tries to fetch the module from sys.modules. If the module was
1223 * never loaded before it loads it with PyImport_ImportModule() unless another
1224 * thread holds the import lock. In the latter case the function raises an
1225 * ImportError instead of blocking.
1226 *
1227 * Returns the module object with incremented ref count.
1228 */
1229PyObject *
1230PyImport_ImportModuleNoBlock(const char *name)
1231{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001232 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001233}
1234
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001235
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001236/* Remove importlib frames from the traceback,
1237 * except in Verbose mode. */
1238static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001239remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001240{
1241 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001242 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001243 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001244 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001245 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001246 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001247 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001248
1249 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001250 from the traceback. We always trim chunks
1251 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001252
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001253 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001254 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001255 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001256 }
1257
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001258 if (PyType_IsSubtype((PyTypeObject *) exception,
1259 (PyTypeObject *) PyExc_ImportError))
1260 always_trim = 1;
1261
1262 prev_link = &base_tb;
1263 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001264 while (tb != NULL) {
1265 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1266 PyObject *next = (PyObject *) traceback->tb_next;
1267 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001268 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001269 int now_in_importlib;
1270
1271 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001272 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1273 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001274 if (now_in_importlib && !in_importlib) {
1275 /* This is the link to this chunk of importlib tracebacks */
1276 outer_link = prev_link;
1277 }
1278 in_importlib = now_in_importlib;
1279
1280 if (in_importlib &&
1281 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001282 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001283 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001284 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001285 prev_link = outer_link;
1286 }
1287 else {
1288 prev_link = (PyObject **) &traceback->tb_next;
1289 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001290 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001291 tb = next;
1292 }
1293done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001294 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001295}
1296
1297
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001298static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001299resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001300{
Brett Cannonfd074152012-04-14 14:10:13 -04001301 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001302 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001303 _Py_IDENTIFIER(parent);
1304 PyObject *abs_name;
1305 PyObject *package = NULL;
1306 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001307 Py_ssize_t last_dot;
1308 PyObject *base;
1309 int level_up;
1310
1311 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001312 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001313 goto error;
1314 }
1315 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001316 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001317 goto error;
1318 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001319 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001320 if (package == Py_None) {
1321 package = NULL;
1322 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001323 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001324 goto error;
1325 }
1326 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001327 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001328 goto error;
1329 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001330
1331 if (package != NULL) {
1332 Py_INCREF(package);
1333 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001334 _PyErr_SetString(tstate, PyExc_TypeError,
1335 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001336 goto error;
1337 }
1338 else if (spec != NULL && spec != Py_None) {
1339 int equal;
1340 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1341 if (parent == NULL) {
1342 goto error;
1343 }
1344
1345 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1346 Py_DECREF(parent);
1347 if (equal < 0) {
1348 goto error;
1349 }
1350 else if (equal == 0) {
1351 if (PyErr_WarnEx(PyExc_ImportWarning,
1352 "__package__ != __spec__.parent", 1) < 0) {
1353 goto error;
1354 }
1355 }
1356 }
1357 }
1358 else if (spec != NULL && spec != Py_None) {
1359 package = _PyObject_GetAttrId(spec, &PyId_parent);
1360 if (package == NULL) {
1361 goto error;
1362 }
1363 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001364 _PyErr_SetString(tstate, PyExc_TypeError,
1365 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001366 goto error;
1367 }
1368 }
1369 else {
1370 if (PyErr_WarnEx(PyExc_ImportWarning,
1371 "can't resolve package from __spec__ or __package__, "
1372 "falling back on __name__ and __path__", 1) < 0) {
1373 goto error;
1374 }
1375
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001376 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001377 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001378 if (!_PyErr_Occurred(tstate)) {
1379 _PyErr_SetString(tstate, PyExc_KeyError,
1380 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001381 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001382 goto error;
1383 }
1384
1385 Py_INCREF(package);
1386 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001387 _PyErr_SetString(tstate, PyExc_TypeError,
1388 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001389 goto error;
1390 }
1391
Serhiy Storchakab510e102020-10-26 12:47:57 +02001392 int haspath = _PyDict_ContainsId(globals, &PyId___path__);
1393 if (haspath < 0) {
1394 goto error;
1395 }
1396 if (!haspath) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001397 Py_ssize_t dot;
1398
Serhiy Storchakab510e102020-10-26 12:47:57 +02001399 if (PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001400 goto error;
1401 }
1402
1403 dot = PyUnicode_FindChar(package, '.',
1404 0, PyUnicode_GET_LENGTH(package), -1);
1405 if (dot == -2) {
1406 goto error;
1407 }
Ben Lewis92420b32019-09-11 20:09:47 +10001408 else if (dot == -1) {
1409 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001410 }
Ben Lewis92420b32019-09-11 20:09:47 +10001411 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1412 if (substr == NULL) {
1413 goto error;
1414 }
1415 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001416 }
1417 }
1418
1419 last_dot = PyUnicode_GET_LENGTH(package);
1420 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001421 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001422 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001423
1424 for (level_up = 1; level_up < level; level_up += 1) {
1425 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1426 if (last_dot == -2) {
1427 goto error;
1428 }
1429 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001430 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001431 "attempted relative import beyond top-level "
1432 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001433 goto error;
1434 }
1435 }
1436
1437 base = PyUnicode_Substring(package, 0, last_dot);
1438 Py_DECREF(package);
1439 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1440 return base;
1441 }
1442
1443 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1444 Py_DECREF(base);
1445 return abs_name;
1446
Ben Lewis92420b32019-09-11 20:09:47 +10001447 no_parent_error:
1448 _PyErr_SetString(tstate, PyExc_ImportError,
1449 "attempted relative import "
1450 "with no known parent package");
1451
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001452 error:
1453 Py_XDECREF(package);
1454 return NULL;
1455}
1456
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001457static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001458import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001459{
1460 _Py_IDENTIFIER(_find_and_load);
1461 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001462 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001463 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001464 static int import_level;
1465 static _PyTime_t accumulated;
1466
1467 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1468
Steve Dowerb82e17e2019-05-23 08:45:22 -07001469 PyObject *sys_path = PySys_GetObject("path");
1470 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1471 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001472 if (_PySys_Audit(tstate, "import", "OOOOO",
1473 abs_name, Py_None, sys_path ? sys_path : Py_None,
1474 sys_meta_path ? sys_meta_path : Py_None,
1475 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001476 return NULL;
1477 }
1478
1479
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001480 /* XOptions is initialized after first some imports.
1481 * So we can't have negative cache before completed initialization.
1482 * Anyway, importlib._find_and_load is much slower than
1483 * _PyDict_GetItemIdWithError().
1484 */
1485 if (import_time) {
1486 static int header = 1;
1487 if (header) {
1488 fputs("import time: self [us] | cumulative | imported package\n",
1489 stderr);
1490 header = 0;
1491 }
1492
1493 import_level++;
1494 t1 = _PyTime_GetPerfCounter();
1495 accumulated = 0;
1496 }
1497
1498 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001499 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001500
1501 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1502 &PyId__find_and_load, abs_name,
1503 interp->import_func, NULL);
1504
1505 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001506 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001507 mod != NULL);
1508
1509 if (import_time) {
1510 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1511
1512 import_level--;
1513 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1514 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1515 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1516 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1517
1518 accumulated = accumulated_copy + cum;
1519 }
1520
1521 return mod;
1522}
1523
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001524PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001525PyImport_GetModule(PyObject *name)
1526{
1527 PyThreadState *tstate = _PyThreadState_GET();
1528 PyObject *mod;
1529
1530 mod = import_get_module(tstate, name);
1531 if (mod != NULL && mod != Py_None) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001532 if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001533 Py_DECREF(mod);
1534 remove_importlib_frames(tstate);
1535 return NULL;
1536 }
1537 }
1538 return mod;
1539}
1540
1541PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001542PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1543 PyObject *locals, PyObject *fromlist,
1544 int level)
1545{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001546 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001547 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001548 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001549 PyObject *final_mod = NULL;
1550 PyObject *mod = NULL;
1551 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001552 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001553 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001554
Brett Cannonfd074152012-04-14 14:10:13 -04001555 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001556 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001557 goto error;
1558 }
1559
1560 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1561 for added performance. */
1562
1563 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001564 _PyErr_SetString(tstate, PyExc_TypeError,
1565 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001566 goto error;
1567 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001568 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001569 goto error;
1570 }
1571 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001572 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001573 goto error;
1574 }
Brett Cannon849113a2016-01-22 15:25:50 -08001575
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001576 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001577 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001578 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001579 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001580 }
1581 else { /* level == 0 */
1582 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001583 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001584 goto error;
1585 }
Brett Cannonfd074152012-04-14 14:10:13 -04001586 abs_name = name;
1587 Py_INCREF(abs_name);
1588 }
1589
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001590 mod = import_get_module(tstate, abs_name);
1591 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001592 goto error;
1593 }
1594
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001595 if (mod != NULL && mod != Py_None) {
Antoine Pitrou2fd16ef2021-03-20 20:07:44 +01001596 if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001597 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001598 }
Brett Cannonfd074152012-04-14 14:10:13 -04001599 }
1600 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001601 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001602 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001603 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001604 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001605 }
1606 }
1607
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001608 has_from = 0;
1609 if (fromlist != NULL && fromlist != Py_None) {
1610 has_from = PyObject_IsTrue(fromlist);
1611 if (has_from < 0)
1612 goto error;
1613 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001614 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001615 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1616 if (level == 0 || len > 0) {
1617 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001618
Victor Stinner744c34e2016-05-20 11:36:13 +02001619 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1620 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001621 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001622 }
1623
Victor Stinner744c34e2016-05-20 11:36:13 +02001624 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001625 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001626 final_mod = mod;
1627 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001628 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001629 }
1630
Brett Cannonfd074152012-04-14 14:10:13 -04001631 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001632 PyObject *front = PyUnicode_Substring(name, 0, dot);
1633 if (front == NULL) {
1634 goto error;
1635 }
1636
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001637 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001638 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001639 }
1640 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001641 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001642 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001643 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001644 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001645 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001646 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001647 }
Brett Cannonfd074152012-04-14 14:10:13 -04001648
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001649 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001650 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001651 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001652 if (!_PyErr_Occurred(tstate)) {
1653 _PyErr_Format(tstate, PyExc_KeyError,
1654 "%R not in sys.modules as expected",
1655 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001656 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001657 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001658 }
Brett Cannonfd074152012-04-14 14:10:13 -04001659 }
1660 }
1661 else {
1662 final_mod = mod;
1663 Py_INCREF(mod);
1664 }
1665 }
1666 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001667 PyObject *path;
1668 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1669 goto error;
1670 }
1671 if (path) {
1672 Py_DECREF(path);
1673 final_mod = _PyObject_CallMethodIdObjArgs(
1674 interp->importlib, &PyId__handle_fromlist,
1675 mod, fromlist, interp->import_func, NULL);
1676 }
1677 else {
1678 final_mod = mod;
1679 Py_INCREF(mod);
1680 }
Brett Cannonfd074152012-04-14 14:10:13 -04001681 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001682
Brett Cannonfd074152012-04-14 14:10:13 -04001683 error:
1684 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001685 Py_XDECREF(mod);
1686 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001687 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001688 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001689 }
Brett Cannonfd074152012-04-14 14:10:13 -04001690 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001691}
1692
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001693PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001694PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001695 PyObject *fromlist, int level)
1696{
1697 PyObject *nameobj, *mod;
1698 nameobj = PyUnicode_FromString(name);
1699 if (nameobj == NULL)
1700 return NULL;
1701 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1702 fromlist, level);
1703 Py_DECREF(nameobj);
1704 return mod;
1705}
1706
1707
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001708/* Re-import a module of any kind and return its module object, WITH
1709 INCREMENTED REFERENCE COUNT */
1710
Guido van Rossum79f25d91997-04-29 20:08:16 +00001711PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001712PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001713{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001714 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001715 _Py_IDENTIFIER(reload);
1716 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001717 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1718 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001719 if (PyErr_Occurred()) {
1720 return NULL;
1721 }
1722
Robert Rouhanif40bd462020-05-01 16:28:06 -07001723 importlib = PyImport_ImportModule("importlib");
1724 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001725 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001728
Robert Rouhanif40bd462020-05-01 16:28:06 -07001729 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1730 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001731 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001732}
1733
1734
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001735/* Higher-level import emulator which emulates the "import" statement
1736 more accurately -- it invokes the __import__() function from the
1737 builtins of the current globals. This means that the import is
1738 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001739 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001740 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001741 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001742 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001743
1744PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001745PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001746{
junyixie88d99832021-03-22 17:47:10 +08001747 _Py_IDENTIFIER(__import__);
1748 _Py_IDENTIFIER(__builtins__);
1749
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001750 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyObject *globals = NULL;
1752 PyObject *import = NULL;
1753 PyObject *builtins = NULL;
1754 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 /* Initialize constant string objects */
junyixie88d99832021-03-22 17:47:10 +08001757 PyObject *import_str = _PyUnicode_FromId(&PyId___import__); // borrowed ref
1758 if (import_str == NULL) {
1759 return NULL;
1760 }
1761
1762 PyObject *builtins_str = _PyUnicode_FromId(&PyId___builtins__); // borrowed ref
1763 if (builtins_str == NULL) {
1764 return NULL;
1765 }
1766
1767 PyObject *from_list = PyList_New(0);
1768 if (from_list == NULL) {
1769 goto err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* Get the builtins from current globals */
1773 globals = PyEval_GetGlobals();
1774 if (globals != NULL) {
1775 Py_INCREF(globals);
1776 builtins = PyObject_GetItem(globals, builtins_str);
1777 if (builtins == NULL)
1778 goto err;
1779 }
1780 else {
1781 /* No globals -- use standard builtins, and fake globals */
1782 builtins = PyImport_ImportModuleLevel("builtins",
1783 NULL, NULL, NULL, 0);
junyixie88d99832021-03-22 17:47:10 +08001784 if (builtins == NULL) {
1785 goto err;
1786 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1788 if (globals == NULL)
1789 goto err;
1790 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* Get the __import__ function from the builtins */
1793 if (PyDict_Check(builtins)) {
1794 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001795 if (import == NULL) {
1796 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
1797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
1799 else
1800 import = PyObject_GetAttr(builtins, import_str);
1801 if (import == NULL)
1802 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001805 Always use absolute import here.
1806 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
junyixie88d99832021-03-22 17:47:10 +08001808 globals, from_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001809 if (r == NULL)
1810 goto err;
1811 Py_DECREF(r);
1812
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001813 r = import_get_module(tstate, module_name);
1814 if (r == NULL && !_PyErr_Occurred(tstate)) {
1815 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001816 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001817
1818 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 Py_XDECREF(globals);
1820 Py_XDECREF(builtins);
1821 Py_XDECREF(import);
junyixie88d99832021-03-22 17:47:10 +08001822 Py_XDECREF(from_list);
Tim Peters50d8d372001-02-28 05:34:27 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001825}
1826
Brett Cannon4caa61d2014-01-09 19:03:32 -05001827/*[clinic input]
1828_imp.extension_suffixes
1829
1830Returns the list of file suffixes used to identify extension modules.
1831[clinic start generated code]*/
1832
Brett Cannon4caa61d2014-01-09 19:03:32 -05001833static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001834_imp_extension_suffixes_impl(PyObject *module)
1835/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 list = PyList_New(0);
1840 if (list == NULL)
1841 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001842#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01001843 const char *suffix;
1844 unsigned int index = 0;
1845
Brett Cannon2657df42012-05-04 15:20:40 -04001846 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1847 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 if (item == NULL) {
1849 Py_DECREF(list);
1850 return NULL;
1851 }
1852 if (PyList_Append(list, item) < 0) {
1853 Py_DECREF(list);
1854 Py_DECREF(item);
1855 return NULL;
1856 }
1857 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001858 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 }
Brett Cannon2657df42012-05-04 15:20:40 -04001860#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001862}
1863
Brett Cannon4caa61d2014-01-09 19:03:32 -05001864/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001865_imp.init_frozen
1866
1867 name: unicode
1868 /
1869
1870Initializes a frozen module.
1871[clinic start generated code]*/
1872
Brett Cannon4caa61d2014-01-09 19:03:32 -05001873static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001874_imp_init_frozen_impl(PyObject *module, PyObject *name)
1875/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001876{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001877 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 int ret;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001879
Victor Stinner53dc7352011-03-20 01:50:21 +01001880 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (ret < 0)
1882 return NULL;
1883 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001884 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001886 return import_add_module(tstate, name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001887}
1888
Brett Cannon4caa61d2014-01-09 19:03:32 -05001889/*[clinic input]
1890_imp.get_frozen_object
1891
1892 name: unicode
1893 /
1894
1895Create a code object for a frozen module.
1896[clinic start generated code]*/
1897
Brett Cannon4caa61d2014-01-09 19:03:32 -05001898static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001899_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1900/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001903}
1904
Brett Cannon4caa61d2014-01-09 19:03:32 -05001905/*[clinic input]
1906_imp.is_frozen_package
1907
1908 name: unicode
1909 /
1910
1911Returns True if the module name is of a frozen package.
1912[clinic start generated code]*/
1913
Brett Cannon4caa61d2014-01-09 19:03:32 -05001914static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001915_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1916/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001919}
1920
Brett Cannon4caa61d2014-01-09 19:03:32 -05001921/*[clinic input]
1922_imp.is_builtin
1923
1924 name: unicode
1925 /
1926
1927Returns True if the module name corresponds to a built-in module.
1928[clinic start generated code]*/
1929
Guido van Rossum79f25d91997-04-29 20:08:16 +00001930static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001931_imp_is_builtin_impl(PyObject *module, PyObject *name)
1932/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001933{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001934 return PyLong_FromLong(is_builtin(name));
1935}
1936
1937/*[clinic input]
1938_imp.is_frozen
1939
1940 name: unicode
1941 /
1942
1943Returns True if the module name corresponds to a frozen module.
1944[clinic start generated code]*/
1945
Brett Cannon4caa61d2014-01-09 19:03:32 -05001946static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001947_imp_is_frozen_impl(PyObject *module, PyObject *name)
1948/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001949{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001950 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 p = find_frozen(name);
1953 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001954}
1955
Larry Hastings1df0b352015-08-24 19:53:56 -07001956/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1957static int
1958exec_builtin_or_dynamic(PyObject *mod) {
1959 PyModuleDef *def;
1960 void *state;
1961
1962 if (!PyModule_Check(mod)) {
1963 return 0;
1964 }
1965
1966 def = PyModule_GetDef(mod);
1967 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001968 return 0;
1969 }
Brett Cannon52794db2016-09-07 17:00:43 -07001970
Larry Hastings1df0b352015-08-24 19:53:56 -07001971 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001972 if (state) {
1973 /* Already initialized; skip reload */
1974 return 0;
1975 }
Brett Cannon52794db2016-09-07 17:00:43 -07001976
Larry Hastings1df0b352015-08-24 19:53:56 -07001977 return PyModule_ExecDef(mod, def);
1978}
1979
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001980#ifdef HAVE_DYNAMIC_LOADING
1981
Brett Cannon4caa61d2014-01-09 19:03:32 -05001982/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10001983_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05001984
Nick Coghland5cacbb2015-05-23 22:24:10 +10001985 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05001986 file: object = NULL
1987 /
1988
Nick Coghland5cacbb2015-05-23 22:24:10 +10001989Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990[clinic start generated code]*/
1991
Brett Cannon4caa61d2014-01-09 19:03:32 -05001992static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001993_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
1994/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001995{
Nick Coghland5cacbb2015-05-23 22:24:10 +10001996 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001997 FILE *fp;
1998
Nick Coghland5cacbb2015-05-23 22:24:10 +10001999 name = PyObject_GetAttrString(spec, "name");
2000 if (name == NULL) {
2001 return NULL;
2002 }
2003
2004 path = PyObject_GetAttrString(spec, "origin");
2005 if (path == NULL) {
2006 Py_DECREF(name);
2007 return NULL;
2008 }
2009
Serhiy Storchaka4db89882021-01-12 16:43:32 +02002010 PyThreadState *tstate = _PyThreadState_GET();
2011 mod = import_find_extension(tstate, name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002012 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002013 Py_DECREF(name);
2014 Py_DECREF(path);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002015 return mod;
2016 }
2017
Brett Cannon4caa61d2014-01-09 19:03:32 -05002018 if (file != NULL) {
2019 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002020 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002021 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002022 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002024 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002026 else
2027 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002028
2029 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2030
2031 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002032 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (fp)
2034 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002035 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002036}
2037
Nick Coghland5cacbb2015-05-23 22:24:10 +10002038/*[clinic input]
2039_imp.exec_dynamic -> int
2040
2041 mod: object
2042 /
2043
2044Initialize an extension module.
2045[clinic start generated code]*/
2046
2047static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002048_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2049/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002050{
Larry Hastings1df0b352015-08-24 19:53:56 -07002051 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002052}
2053
2054
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002055#endif /* HAVE_DYNAMIC_LOADING */
2056
Larry Hastings7726ac92014-01-31 22:03:12 -08002057/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002058_imp.exec_builtin -> int
2059
2060 mod: object
2061 /
2062
2063Initialize a built-in module.
2064[clinic start generated code]*/
2065
2066static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002067_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2068/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002069{
2070 return exec_builtin_or_dynamic(mod);
2071}
2072
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002073/*[clinic input]
2074_imp.source_hash
2075
2076 key: long
2077 source: Py_buffer
2078[clinic start generated code]*/
2079
2080static PyObject *
2081_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2082/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2083{
Benjamin Peterson83620772017-12-09 12:18:56 -08002084 union {
2085 uint64_t x;
2086 char data[sizeof(uint64_t)];
2087 } hash;
2088 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002089#if !PY_LITTLE_ENDIAN
2090 // Force to little-endian. There really ought to be a succinct standard way
2091 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002092 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2093 char tmp = hash.data[i];
2094 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2095 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002096 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002097#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002098 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002099}
2100
Barry Warsaw28a691b2010-04-17 00:19:56 +00002101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002102PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002103"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002104
Guido van Rossum79f25d91997-04-29 20:08:16 +00002105static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002106 _IMP_EXTENSION_SUFFIXES_METHODDEF
2107 _IMP_LOCK_HELD_METHODDEF
2108 _IMP_ACQUIRE_LOCK_METHODDEF
2109 _IMP_RELEASE_LOCK_METHODDEF
2110 _IMP_GET_FROZEN_OBJECT_METHODDEF
2111 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002112 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002113 _IMP_INIT_FROZEN_METHODDEF
2114 _IMP_IS_BUILTIN_METHODDEF
2115 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002116 _IMP_CREATE_DYNAMIC_METHODDEF
2117 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002118 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002119 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002120 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002121 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002122};
2123
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002124
Victor Stinner62230712020-11-18 23:18:29 +01002125static int
2126imp_module_exec(PyObject *module)
2127{
2128 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
2129 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
2130 if (pyc_mode == NULL) {
2131 return -1;
2132 }
2133 if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
2134 Py_DECREF(pyc_mode);
2135 return -1;
2136 }
2137 Py_DECREF(pyc_mode);
2138
2139 return 0;
2140}
2141
2142
2143static PyModuleDef_Slot imp_slots[] = {
2144 {Py_mod_exec, imp_module_exec},
2145 {0, NULL}
2146};
2147
2148static struct PyModuleDef imp_module = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyModuleDef_HEAD_INIT,
Victor Stinner62230712020-11-18 23:18:29 +01002150 .m_name = "_imp",
2151 .m_doc = doc_imp,
2152 .m_size = 0,
2153 .m_methods = imp_methods,
2154 .m_slots = imp_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00002155};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002156
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002157PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002158PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002159{
Victor Stinner62230712020-11-18 23:18:29 +01002160 return PyModuleDef_Init(&imp_module);
2161}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002162
Victor Stinner62230712020-11-18 23:18:29 +01002163
2164// Import the _imp extension by calling manually _imp.create_builtin() and
2165// _imp.exec_builtin() since importlib is not initialized yet. Initializing
2166// importlib requires the _imp module: this function fix the bootstrap issue.
2167PyObject*
2168_PyImport_BootstrapImp(PyThreadState *tstate)
2169{
2170 PyObject *name = PyUnicode_FromString("_imp");
2171 if (name == NULL) {
2172 return NULL;
Victor Stinner410b85a2019-05-13 17:12:45 +02002173 }
2174
Victor Stinner62230712020-11-18 23:18:29 +01002175 // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
2176 // an object with just a name attribute.
2177 //
2178 // _imp.__spec__ is overriden by importlib._bootstrap._instal() anyway.
2179 PyObject *attrs = Py_BuildValue("{sO}", "name", name);
2180 if (attrs == NULL) {
2181 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002182 }
Victor Stinner62230712020-11-18 23:18:29 +01002183 PyObject *spec = _PyNamespace_New(attrs);
2184 Py_DECREF(attrs);
2185 if (spec == NULL) {
2186 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002187 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002188
Victor Stinner62230712020-11-18 23:18:29 +01002189 // Create the _imp module from its definition.
2190 PyObject *mod = create_builtin(tstate, name, spec);
2191 Py_CLEAR(name);
2192 Py_DECREF(spec);
2193 if (mod == NULL) {
2194 goto error;
2195 }
2196 assert(mod != Py_None); // not found
2197
2198 // Execute the _imp module: call imp_module_exec().
2199 if (exec_builtin_or_dynamic(mod) < 0) {
2200 Py_DECREF(mod);
2201 goto error;
2202 }
2203 return mod;
2204
2205error:
2206 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002208}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002209
2210
Guido van Rossumb18618d2000-05-03 23:44:39 +00002211/* API for embedding applications that want to add their own entries
2212 to the table of built-in modules. This should normally be called
2213 *before* Py_Initialize(). When the table resize fails, -1 is
2214 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002215
2216 After a similar function by Just van Rossum. */
2217
2218int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002219PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002222 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002223 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Count the number of entries in both tables */
2226 for (n = 0; newtab[n].name != NULL; n++)
2227 ;
2228 if (n == 0)
2229 return 0; /* Nothing to do */
2230 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2231 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002232
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002233 /* Force default raw memory allocator to get a known allocator to be able
2234 to release the memory in _PyImport_Fini2() */
2235 PyMemAllocatorEx old_alloc;
2236 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002239 p = NULL;
2240 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002241 size_t size = sizeof(struct _inittab) * (i + n + 1);
2242 p = PyMem_RawRealloc(inittab_copy, size);
2243 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002244 if (p == NULL) {
2245 res = -1;
2246 goto done;
2247 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002248
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002249 /* Copy the tables into the new memory at the first call
2250 to PyImport_ExtendInittab(). */
2251 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002253 }
2254 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2255 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002256
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002257done:
2258 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2259 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002260}
2261
2262/* Shorthand to add a single entry given a name and a function */
2263
2264int
Brett Cannona826f322009-04-02 03:41:46 +00002265PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002270
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002271 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002275}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002276
2277#ifdef __cplusplus
2278}
2279#endif