blob: f2b30afe3f2284d55839e47d3f05b50a3d72a453 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module definition and import implementation */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004
Victor Stinner62230712020-11-18 23:18:29 +01005#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner61691d82019-10-02 23:51:20 +02006#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02007#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01008#include "pycore_pyhash.h"
9#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020010#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020011#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
12#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010013#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000015#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000017#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020018#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000019
Guido van Rossum55a83382000-09-20 20:31:38 +000020#ifdef HAVE_FCNTL_H
21#include <fcntl.h>
22#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000024extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000026
Barry Warsaw28a691b2010-04-17 00:19:56 +000027#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000028
Victor Stinner0a28f8d2019-06-19 02:54:39 +020029/* Forward references */
30static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
31
Victor Stinner95872862011-03-07 18:20:56 +010032/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000033static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000034
Guido van Rossum771c6c81997-10-31 18:37:24 +000035/* This table is defined in config.c: */
36extern struct _inittab _PyImport_Inittab[];
37
38struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010039static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000040
Hai Shi46874c22020-01-30 17:20:25 -060041_Py_IDENTIFIER(__path__);
42_Py_IDENTIFIER(__spec__);
43
Brett Cannon4caa61d2014-01-09 19:03:32 -050044/*[clinic input]
45module _imp
46[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030047/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040048
49#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050050
Guido van Rossum1ae940a1995-01-02 19:04:15 +000051/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052
Victor Stinner331a6a52019-05-27 16:39:22 +020053PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020054_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040055{
ukwksk5e6312c2018-05-15 04:10:52 +090056 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040057 int err = 0;
58
59 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020060 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020061 _PyErr_SetString(tstate, PyExc_RuntimeError,
62 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040063 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020064 }
Brett Cannonfd074152012-04-14 14:10:13 -040065
Victor Stinnerda7933e2020-04-13 03:04:28 +020066 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +020067 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -040068 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020069 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
ukwksk5e6312c2018-05-15 04:10:52 +090071 zipimport = PyImport_ImportModule("zipimport");
72 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020073 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020074 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 }
78 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020079 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090080 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020081 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090082 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020084 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020085 if (verbose) {
86 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
87 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 }
89 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -040090 /* sys.path_hooks.insert(0, zipimporter) */
91 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -040093 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -040095 }
Victor Stinner410b85a2019-05-13 17:12:45 +020096 if (verbose) {
97 PySys_WriteStderr("# installed zipimport hook\n");
98 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 }
100 }
Brett Cannonfd074152012-04-14 14:10:13 -0400101
Victor Stinner331a6a52019-05-27 16:39:22 +0200102 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400103
104 error:
105 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200106 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000107}
108
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000109/* Locking primitives to prevent parallel imports of the same module
110 in different threads to return with a partially loaded module.
111 These calls are serialized by the global interpreter lock. */
112
Victor Stinner26881c82020-06-02 15:51:37 +0200113static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200114static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000115static int import_lock_level = 0;
116
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000117void
118_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000119{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200120 unsigned long me = PyThread_get_thread_ident();
121 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 return; /* Too bad */
123 if (import_lock == NULL) {
124 import_lock = PyThread_allocate_lock();
125 if (import_lock == NULL)
126 return; /* Nothing much we can do. */
127 }
128 if (import_lock_thread == me) {
129 import_lock_level++;
130 return;
131 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200132 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
133 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 {
135 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200136 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 PyEval_RestoreThread(tstate);
138 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100139 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 import_lock_thread = me;
141 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000142}
143
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000144int
145_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000146{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200147 unsigned long me = PyThread_get_thread_ident();
148 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 return 0; /* Too bad */
150 if (import_lock_thread != me)
151 return -1;
152 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100153 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200155 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 PyThread_release_lock(import_lock);
157 }
158 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000159}
160
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900161#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200162/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000163 created child processes do not share locks with the parent.
164 We now acquire the import lock around fork() calls but on some platforms
165 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200166PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000167_PyImport_ReInitLock(void)
168{
Christian Heimes418fd742015-04-19 21:08:42 +0200169 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900170 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200171 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200172 }
173 }
Victor Stinner26881c82020-06-02 15:51:37 +0200174
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000175 if (import_lock_level > 1) {
176 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200177 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200178 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000179 import_lock_thread = me;
180 import_lock_level--;
181 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200182 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000183 import_lock_level = 0;
184 }
Victor Stinner26881c82020-06-02 15:51:37 +0200185 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000186}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900187#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000188
Brett Cannon4caa61d2014-01-09 19:03:32 -0500189/*[clinic input]
190_imp.lock_held
191
192Return True if the import lock is currently held, else False.
193
194On platforms without threads, return False.
195[clinic start generated code]*/
196
Brett Cannon4caa61d2014-01-09 19:03:32 -0500197static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300198_imp_lock_held_impl(PyObject *module)
199/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000200{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200201 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000202}
203
Brett Cannon4caa61d2014-01-09 19:03:32 -0500204/*[clinic input]
205_imp.acquire_lock
206
207Acquires the interpreter's import lock for the current thread.
208
209This lock should be used by import hooks to ensure thread-safety when importing
210modules. On platforms without threads, this function does nothing.
211[clinic start generated code]*/
212
Brett Cannon4caa61d2014-01-09 19:03:32 -0500213static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300214_imp_acquire_lock_impl(PyObject *module)
215/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200218 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000219}
220
Brett Cannon4caa61d2014-01-09 19:03:32 -0500221/*[clinic input]
222_imp.release_lock
223
224Release the interpreter's import lock.
225
226On platforms without threads, this function does nothing.
227[clinic start generated code]*/
228
Brett Cannon4caa61d2014-01-09 19:03:32 -0500229static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300230_imp_release_lock_impl(PyObject *module)
231/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (_PyImport_ReleaseLock() < 0) {
234 PyErr_SetString(PyExc_RuntimeError,
235 "not holding the import lock");
236 return NULL;
237 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200238 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000239}
240
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100241void
242_PyImport_Fini(void)
243{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200244 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100245 if (import_lock != NULL) {
246 PyThread_free_lock(import_lock);
247 import_lock = NULL;
248 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100249}
250
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100251void
252_PyImport_Fini2(void)
253{
254 /* Use the same memory allocator than PyImport_ExtendInittab(). */
255 PyMemAllocatorEx old_alloc;
256 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
257
Victor Stinnerece38412021-06-23 17:47:38 +0200258 // Reset PyImport_Inittab
259 PyImport_Inittab = _PyImport_Inittab;
260
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100261 /* Free memory allocated by PyImport_ExtendInittab() */
262 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700263 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100264
265 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
266}
267
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268/* Helper for sys */
269
270PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000271PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000272{
Victor Stinner81a7be32020-04-14 15:14:01 +0200273 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600274 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100275 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600276 }
Eric Snow93c92f72017-09-13 23:46:04 -0700277 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278}
279
Eric Snowd393c1b2017-09-14 12:18:12 -0600280/* In some corner cases it is important to be sure that the import
281 machinery has been initialized (or not cleaned up yet). For
282 example, see issue #4236 and PyModule_Create2(). */
283
284int
285_PyImport_IsInitialized(PyInterpreterState *interp)
286{
287 if (interp->modules == NULL)
288 return 0;
289 return 1;
290}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000291
Eric Snow3f9eee62017-09-15 16:35:20 -0600292PyObject *
293_PyImport_GetModuleId(struct _Py_Identifier *nameid)
294{
295 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
296 if (name == NULL) {
297 return NULL;
298 }
299 return PyImport_GetModule(name);
300}
301
302int
303_PyImport_SetModule(PyObject *name, PyObject *m)
304{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100305 PyInterpreterState *interp = _PyInterpreterState_GET();
306 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600307 return PyObject_SetItem(modules, name, m);
308}
309
310int
311_PyImport_SetModuleString(const char *name, PyObject *m)
312{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100313 PyInterpreterState *interp = _PyInterpreterState_GET();
314 PyObject *modules = interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600315 return PyMapping_SetItemString(modules, name, m);
316}
317
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200318static PyObject *
319import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600320{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200321 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600322 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200323 _PyErr_SetString(tstate, PyExc_RuntimeError,
324 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600325 return NULL;
326 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200327
328 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600329 Py_INCREF(modules);
330 if (PyDict_CheckExact(modules)) {
331 m = PyDict_GetItemWithError(modules, name); /* borrowed */
332 Py_XINCREF(m);
333 }
334 else {
335 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200336 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
337 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600338 }
339 }
340 Py_DECREF(modules);
341 return m;
342}
343
344
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100345static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100346import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200347{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100348 PyObject *spec;
349
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100350 _Py_IDENTIFIER(_lock_unlock_module);
351
352 /* Optimization: only call _bootstrap._lock_unlock_module() if
353 __spec__._initializing is true.
354 NOTE: because of this, initializing must be set *before*
355 stuffing the new module in sys.modules.
356 */
357 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
358 int busy = _PyModuleSpec_IsInitializing(spec);
359 Py_XDECREF(spec);
360 if (busy) {
361 /* Wait until module is done importing. */
362 PyObject *value = _PyObject_CallMethodIdOneArg(
363 interp->importlib, &PyId__lock_unlock_module, name);
364 if (value == NULL) {
365 return -1;
366 }
367 Py_DECREF(value);
368 }
369 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200370}
371
372
Barry Warsaw28a691b2010-04-17 00:19:56 +0000373/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000374
375long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000376PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000377{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200378 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200379 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600380 PyObject *external, *pyc_magic;
381
382 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
383 if (external == NULL)
384 return -1;
385 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
386 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400387 if (pyc_magic == NULL)
388 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200389 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700390 Py_DECREF(pyc_magic);
391 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000392}
393
394
Brett Cannon3adc7b72012-07-09 14:22:12 -0400395extern const char * _PySys_ImplCacheTag;
396
Barry Warsaw28a691b2010-04-17 00:19:56 +0000397const char *
398PyImport_GetMagicTag(void)
399{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400400 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000401}
402
Brett Cannon98979b82012-07-02 15:13:11 -0400403
Guido van Rossum25ce5661997-08-02 03:10:38 +0000404/* Magic for extension modules (built-in as well as dynamically
405 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200406 once, we keep a static dictionary 'extensions' keyed by the tuple
407 (module name, module name) (for built-in modules) or by
408 (filename, module name) (for dynamically loaded modules), containing these
409 modules. A copy of the module's dictionary is stored by calling
410 _PyImport_FixupExtensionObject() immediately after the module initialization
411 function succeeds. A copy can be retrieved from there by calling
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200412 import_find_extension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000413
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000414 Modules which do support multiple initialization set their m_size
415 field to a non-negative number (indicating the size of the
416 module-specific state). They are still recorded in the extensions
417 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000418*/
419
420int
Victor Stinner95872862011-03-07 18:20:56 +0100421_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200422 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (mod == NULL || !PyModule_Check(mod)) {
425 PyErr_BadInternalCall();
426 return -1;
427 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100428
429 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 if (!def) {
431 PyErr_BadInternalCall();
432 return -1;
433 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100434
435 PyThreadState *tstate = _PyThreadState_GET();
436 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100438 }
439 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600440 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return -1;
442 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100443
Victor Stinner101bf692021-02-19 13:33:31 +0100444 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinner82c83bd2019-11-22 18:52:27 +0100445 if (def->m_size == -1) {
446 if (def->m_base.m_copy) {
447 /* Somebody already imported the module,
448 likely under a different name.
449 XXX this should really not happen. */
450 Py_CLEAR(def->m_base.m_copy);
451 }
452 PyObject *dict = PyModule_GetDict(mod);
453 if (dict == NULL) {
454 return -1;
455 }
456 def->m_base.m_copy = PyDict_Copy(dict);
457 if (def->m_base.m_copy == NULL) {
458 return -1;
459 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100461
462 if (extensions == NULL) {
463 extensions = PyDict_New();
464 if (extensions == NULL) {
465 return -1;
466 }
467 }
468
469 PyObject *key = PyTuple_Pack(2, filename, name);
470 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100472 }
473 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
474 Py_DECREF(key);
475 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481}
482
Victor Stinner49d3f252010-10-17 01:24:53 +0000483int
Eric Snowd393c1b2017-09-14 12:18:12 -0600484_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000485{
486 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100487 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100488 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100489 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000490 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600491 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100492 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000493 return res;
494}
495
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200496static PyObject *
497import_find_extension(PyThreadState *tstate, PyObject *name,
498 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000499{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200500 if (extensions == NULL) {
501 return NULL;
502 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600503
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200504 PyObject *key = PyTuple_Pack(2, filename, name);
505 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200507 }
508 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500509 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200510 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200512 }
513
514 PyObject *mod, *mdict;
515 PyObject *modules = tstate->interp->modules;
516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (def->m_size == -1) {
518 /* Module does not support repeated initialization */
519 if (def->m_base.m_copy == NULL)
520 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200521 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (mod == NULL)
523 return NULL;
524 mdict = PyModule_GetDict(mod);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200525 if (mdict == NULL) {
526 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200528 }
529 if (PyDict_Update(mdict, def->m_base.m_copy)) {
530 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200532 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 }
534 else {
535 if (def->m_base.m_init == NULL)
536 return NULL;
537 mod = def->m_base.m_init();
538 if (mod == NULL)
539 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600540 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200541 Py_DECREF(mod);
542 return NULL;
543 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100545 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600546 PyMapping_DelItem(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200547 Py_DECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return NULL;
549 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200550
Victor Stinnerda7933e2020-04-13 03:04:28 +0200551 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200552 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100553 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200554 name, filename);
555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000557}
558
Serhiy Storchakaec4e2ec2021-09-29 00:12:50 +0300559PyObject *
560_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
561{
562 PyThreadState *tstate = _PyThreadState_GET();
563 PyObject *mod = import_find_extension(tstate, name, filename);
564 if (mod) {
565 PyObject *ref = PyWeakref_NewRef(mod, NULL);
566 Py_DECREF(mod);
567 if (ref == NULL) {
568 return NULL;
569 }
570 mod = PyWeakref_GetObject(ref);
571 Py_DECREF(ref);
572 }
573 return mod; /* borrowed reference */
574}
575
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000576
577/* Get the module object corresponding to a module name.
578 First check the modules dictionary if there's one there,
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200579 if not, create a new one and insert it in the modules dictionary. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000580
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200581static PyObject *
582import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000583{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200584 PyObject *modules = tstate->interp->modules;
585 if (modules == NULL) {
586 _PyErr_SetString(tstate, PyExc_RuntimeError,
587 "no import module dictionary");
588 return NULL;
589 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600590
Eric Snow86b7afd2017-09-04 17:54:09 -0600591 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600592 if (PyDict_CheckExact(modules)) {
593 m = PyDict_GetItemWithError(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200594 Py_XINCREF(m);
Eric Snow3f9eee62017-09-15 16:35:20 -0600595 }
596 else {
597 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000598 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600599 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200600 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
601 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600602 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200603 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200604 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200605 return NULL;
606 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600607 if (m != NULL && PyModule_Check(m)) {
608 return m;
609 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200610 Py_XDECREF(m);
Victor Stinner27ee0892011-03-04 12:57:09 +0000611 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (m == NULL)
613 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600614 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 Py_DECREF(m);
616 return NULL;
617 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620}
621
Victor Stinner27ee0892011-03-04 12:57:09 +0000622PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200623PyImport_AddModuleObject(PyObject *name)
624{
625 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200626 PyObject *mod = import_add_module(tstate, name);
627 if (mod) {
628 PyObject *ref = PyWeakref_NewRef(mod, NULL);
629 Py_DECREF(mod);
630 if (ref == NULL) {
631 return NULL;
632 }
633 mod = PyWeakref_GetObject(ref);
634 Py_DECREF(ref);
635 }
636 return mod; /* borrowed reference */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200637}
638
639
640PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000641PyImport_AddModule(const char *name)
642{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200643 PyObject *nameobj = PyUnicode_FromString(name);
644 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000645 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200646 }
647 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000648 Py_DECREF(nameobj);
649 return module;
650}
651
652
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300653/* Remove name from sys.modules, if it's there.
654 * Can be called with an exception raised.
655 * If fail to remove name a new exception will be chained with the old
656 * exception, otherwise the old exception is preserved.
657 */
Tim Peters1cd70172004-08-02 03:52:12 +0000658static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200659remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000660{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600661 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200662 _PyErr_Fetch(tstate, &type, &value, &traceback);
663
664 PyObject *modules = tstate->interp->modules;
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300665 if (PyDict_CheckExact(modules)) {
666 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
667 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600668 }
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300669 else if (PyMapping_DelItem(modules, name) < 0) {
670 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
671 _PyErr_Clear(tstate);
672 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600673 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200674
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300675 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000676}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000677
Christian Heimes3b06e532008-01-07 20:12:44 +0000678
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000679/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000680 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
681 * removed from sys.modules, to avoid leaving damaged module objects
682 * in sys.modules. The caller may wish to restore the original
683 * module object (if any) in this case; PyImport_ReloadModule is an
684 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000685 *
686 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
687 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000688 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000689PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300690PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 return PyImport_ExecCodeModuleWithPathnames(
693 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000694}
695
696PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300697PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 return PyImport_ExecCodeModuleWithPathnames(
700 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000701}
702
703PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300704PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
705 const char *pathname,
706 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000707{
Victor Stinner27ee0892011-03-04 12:57:09 +0000708 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600709 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000710
711 nameobj = PyUnicode_FromString(name);
712 if (nameobj == NULL)
713 return NULL;
714
Victor Stinner27ee0892011-03-04 12:57:09 +0000715 if (cpathname != NULL) {
716 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
717 if (cpathobj == NULL)
718 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400719 }
720 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000721 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400722
723 if (pathname != NULL) {
724 pathobj = PyUnicode_DecodeFSDefault(pathname);
725 if (pathobj == NULL)
726 goto error;
727 }
728 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200729 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400730 _Py_IDENTIFIER(_get_sourcefile);
731
732 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100733 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400734 }
735
Eric Snow32439d62015-05-02 19:15:18 -0600736 external= PyObject_GetAttrString(interp->importlib,
737 "_bootstrap_external");
738 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200739 pathobj = _PyObject_CallMethodIdOneArg(
740 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600741 Py_DECREF(external);
742 }
Brett Cannona6473f92012-07-13 13:57:03 -0400743 if (pathobj == NULL)
744 PyErr_Clear();
745 }
746 else
747 pathobj = NULL;
748
Victor Stinner27ee0892011-03-04 12:57:09 +0000749 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
750error:
751 Py_DECREF(nameobj);
752 Py_XDECREF(pathobj);
753 Py_XDECREF(cpathobj);
754 return m;
755}
756
Brett Cannon18fc4e72014-04-04 10:01:46 -0400757static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200758module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000759{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200760 _Py_IDENTIFIER(__builtins__);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200761 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000762
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200763 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (m == NULL)
765 return NULL;
766 /* If the module is being reloaded, we get the old module back
767 and re-use its dict to exec the new code. */
768 d = PyModule_GetDict(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200769 int r = _PyDict_ContainsId(d, &PyId___builtins__);
770 if (r == 0) {
771 r = _PyDict_SetItemId(d, &PyId___builtins__,
772 PyEval_GetBuiltins());
773 }
774 if (r < 0) {
775 remove_module(tstate, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200776 Py_DECREF(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200777 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400779
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200780 Py_INCREF(d);
781 Py_DECREF(m);
782 return d;
Brett Cannon18fc4e72014-04-04 10:01:46 -0400783}
784
785static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200786exec_code_in_module(PyThreadState *tstate, PyObject *name,
787 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -0400788{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400789 PyObject *v, *m;
790
791 v = PyEval_EvalCode(code_object, module_dict, module_dict);
792 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200793 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400794 return NULL;
795 }
796 Py_DECREF(v);
797
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200798 m = import_get_module(tstate, name);
799 if (m == NULL && !_PyErr_Occurred(tstate)) {
800 _PyErr_Format(tstate, PyExc_ImportError,
801 "Loaded module %R not found in sys.modules",
802 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400803 }
804
Brett Cannon18fc4e72014-04-04 10:01:46 -0400805 return m;
806}
807
808PyObject*
809PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
810 PyObject *cpathname)
811{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200812 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600813 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600814 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400815
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200816 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400817 if (d == NULL) {
818 return NULL;
819 }
820
Eric Snow08197a42014-05-12 17:54:55 -0600821 if (pathname == NULL) {
822 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200824 external = PyObject_GetAttrString(tstate->interp->importlib,
825 "_bootstrap_external");
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200826 if (external == NULL) {
827 Py_DECREF(d);
Eric Snow32439d62015-05-02 19:15:18 -0600828 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200829 }
Eric Snow32439d62015-05-02 19:15:18 -0600830 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600831 &PyId__fix_up_module,
832 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600833 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600834 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600835 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200836 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200838 Py_DECREF(d);
Eric Snow08197a42014-05-12 17:54:55 -0600839 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000840}
841
842
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000843static void
844update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyObject *constants, *tmp;
847 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (PyUnicode_Compare(co->co_filename, oldname))
850 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000851
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200852 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300853 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 constants = co->co_consts;
856 n = PyTuple_GET_SIZE(constants);
857 for (i = 0; i < n; i++) {
858 tmp = PyTuple_GET_ITEM(constants, i);
859 if (PyCode_Check(tmp))
860 update_code_filenames((PyCodeObject *)tmp,
861 oldname, newname);
862 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000863}
864
Victor Stinner2f42ae52011-03-20 00:41:24 +0100865static void
866update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000867{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100868 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000869
Victor Stinner2f42ae52011-03-20 00:41:24 +0100870 if (PyUnicode_Compare(co->co_filename, newname) == 0)
871 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 oldname = co->co_filename;
874 Py_INCREF(oldname);
875 update_code_filenames(co, oldname, newname);
876 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000877}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878
Brett Cannon4caa61d2014-01-09 19:03:32 -0500879/*[clinic input]
880_imp._fix_co_filename
881
882 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
883 Code object to change.
884
885 path: unicode
886 File path to use.
887 /
888
889Changes code.co_filename to specify the passed-in file path.
890[clinic start generated code]*/
891
Brett Cannon4caa61d2014-01-09 19:03:32 -0500892static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300893_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400894 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300895/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700896
Brett Cannon4caa61d2014-01-09 19:03:32 -0500897{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500898 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700899
900 Py_RETURN_NONE;
901}
902
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000903
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000904/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700905static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000906
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000907
908/* Helper to test for built-in module */
909
910static int
Victor Stinner95872862011-03-07 18:20:56 +0100911is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000912{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200913 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200915 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (PyImport_Inittab[i].initfunc == NULL)
917 return -1;
918 else
919 return 1;
920 }
921 }
922 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000923}
924
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000925
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700926/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000927 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000928 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000929 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700930 this tells our caller that the path based finder could not find
931 a finder for this path item. Cache the result in
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200932 path_importer_cache. */
Just van Rossum52e14d62002-12-30 22:08:05 +0000933
934static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200935get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
936 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyObject *importer;
939 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* These conditions are the caller's responsibility: */
942 assert(PyList_Check(path_hooks));
943 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 nhooks = PyList_Size(path_hooks);
946 if (nhooks < 0)
947 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000948
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200949 importer = PyDict_GetItemWithError(path_importer_cache, p);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200950 if (importer != NULL || _PyErr_Occurred(tstate)) {
951 Py_XINCREF(importer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return importer;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200953 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* set path_importer_cache[p] to None to avoid recursion */
956 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
957 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 for (j = 0; j < nhooks; j++) {
960 PyObject *hook = PyList_GetItem(path_hooks, j);
961 if (hook == NULL)
962 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +0100963 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (importer != NULL)
965 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000966
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200967 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 return NULL;
969 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200970 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 }
972 if (importer == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200973 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200975 if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 Py_DECREF(importer);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200977 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 }
979 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000980}
981
Benjamin Petersone5024512018-09-12 12:06:42 -0700982PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200983PyImport_GetImporter(PyObject *path)
984{
985 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200986 PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
987 PyObject *path_hooks = PySys_GetObject("path_hooks");
988 if (path_importer_cache == NULL || path_hooks == NULL) {
989 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200991 return get_path_importer(tstate, path_importer_cache, path_hooks, path);
Christian Heimes9cd17752007-11-18 19:35:23 +0000992}
993
Victor Stinner62230712020-11-18 23:18:29 +0100994static PyObject*
995create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
996{
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200997 PyObject *mod = import_find_extension(tstate, name, name);
Victor Stinner62230712020-11-18 23:18:29 +0100998 if (mod || _PyErr_Occurred(tstate)) {
Victor Stinner62230712020-11-18 23:18:29 +0100999 return mod;
1000 }
1001
1002 PyObject *modules = tstate->interp->modules;
1003 for (struct _inittab *p = PyImport_Inittab; p->name != NULL; p++) {
1004 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
1005 if (p->initfunc == NULL) {
1006 /* Cannot re-init internal module ("sys" or "builtins") */
1007 return PyImport_AddModuleObject(name);
1008 }
1009
1010 mod = (*p->initfunc)();
1011 if (mod == NULL) {
1012 return NULL;
1013 }
1014
1015 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1016 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1017 }
1018 else {
1019 /* Remember pointer to module init function. */
1020 PyModuleDef *def = PyModule_GetDef(mod);
1021 if (def == NULL) {
1022 return NULL;
1023 }
1024
1025 def->m_base.m_init = p->initfunc;
1026 if (_PyImport_FixupExtensionObject(mod, name, name,
1027 modules) < 0) {
1028 return NULL;
1029 }
1030 return mod;
1031 }
1032 }
1033 }
1034
1035 // not found
1036 Py_RETURN_NONE;
1037}
1038
1039
1040
Nick Coghland5cacbb2015-05-23 22:24:10 +10001041/*[clinic input]
1042_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001043
Nick Coghland5cacbb2015-05-23 22:24:10 +10001044 spec: object
1045 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001046
Nick Coghland5cacbb2015-05-23 22:24:10 +10001047Create an extension module.
1048[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001049
Nick Coghland5cacbb2015-05-23 22:24:10 +10001050static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001051_imp_create_builtin(PyObject *module, PyObject *spec)
1052/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001053{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001054 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001055
Victor Stinner62230712020-11-18 23:18:29 +01001056 PyObject *name = PyObject_GetAttrString(spec, "name");
Nick Coghland5cacbb2015-05-23 22:24:10 +10001057 if (name == NULL) {
1058 return NULL;
1059 }
1060
Victor Stinner62230712020-11-18 23:18:29 +01001061 PyObject *mod = create_builtin(tstate, name, spec);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001062 Py_DECREF(name);
Victor Stinner62230712020-11-18 23:18:29 +01001063 return mod;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001064}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001065
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001066
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001067/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001069static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001070find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001071{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001072 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001073
Victor Stinner53dc7352011-03-20 01:50:21 +01001074 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 for (p = PyImport_FrozenModules; ; p++) {
1078 if (p->name == NULL)
1079 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001080 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 break;
1082 }
1083 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001084}
1085
Guido van Rossum79f25d91997-04-29 20:08:16 +00001086static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001087get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001088{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001089 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (p == NULL) {
1093 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001094 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 name);
1096 return NULL;
1097 }
1098 if (p->code == NULL) {
1099 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001100 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 name);
1102 return NULL;
1103 }
1104 size = p->size;
1105 if (size < 0)
1106 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001107 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001108}
1109
Brett Cannon8d110132009-03-15 02:20:16 +00001110static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001111is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001112{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001113 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (p == NULL) {
1117 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001118 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 name);
1120 return NULL;
1121 }
Brett Cannon8d110132009-03-15 02:20:16 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (size < 0)
1126 Py_RETURN_TRUE;
1127 else
1128 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001129}
1130
1131
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001132/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001133 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001134 an exception set if the initialization failed.
1135 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001136
1137int
Victor Stinner53dc7352011-03-20 01:50:21 +01001138PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001139{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001140 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001141 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001142 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 int ispackage;
1144 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001145
Victor Stinner53dc7352011-03-20 01:50:21 +01001146 p = find_frozen(name);
1147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (p == NULL)
1149 return 0;
1150 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001151 _PyErr_Format(tstate, PyExc_ImportError,
1152 "Excluded frozen object named %R",
1153 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 return -1;
1155 }
1156 size = p->size;
1157 ispackage = (size < 0);
1158 if (ispackage)
1159 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001160 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (co == NULL)
1162 return -1;
1163 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001164 _PyErr_Format(tstate, PyExc_TypeError,
1165 "frozen object %R is not a code object",
1166 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 goto err_return;
1168 }
1169 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001170 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001171 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001173 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (m == NULL)
1175 goto err_return;
1176 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001177 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (l == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001179 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 goto err_return;
1181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 err = PyDict_SetItemString(d, "__path__", l);
1183 Py_DECREF(l);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001184 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (err != 0)
1186 goto err_return;
1187 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001188 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001189 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001190 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001191 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001192 m = exec_code_in_module(tstate, name, d, co);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001193 Py_DECREF(d);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001194 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001196 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 Py_DECREF(co);
1198 Py_DECREF(m);
1199 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001200
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001201err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 Py_DECREF(co);
1203 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001204}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001205
Victor Stinner53dc7352011-03-20 01:50:21 +01001206int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001207PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001208{
1209 PyObject *nameobj;
1210 int ret;
1211 nameobj = PyUnicode_InternFromString(name);
1212 if (nameobj == NULL)
1213 return -1;
1214 ret = PyImport_ImportFrozenModuleObject(nameobj);
1215 Py_DECREF(nameobj);
1216 return ret;
1217}
1218
Guido van Rossum74e6a111994-08-29 12:54:38 +00001219
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001220/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001221 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001222
Guido van Rossum79f25d91997-04-29 20:08:16 +00001223PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001224PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyObject *pname;
1227 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 pname = PyUnicode_FromString(name);
1230 if (pname == NULL)
1231 return NULL;
1232 result = PyImport_Import(pname);
1233 Py_DECREF(pname);
1234 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001235}
1236
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001237
Christian Heimes072c0f12008-01-03 23:01:04 +00001238/* Import a module without blocking
1239 *
1240 * At first it tries to fetch the module from sys.modules. If the module was
1241 * never loaded before it loads it with PyImport_ImportModule() unless another
1242 * thread holds the import lock. In the latter case the function raises an
1243 * ImportError instead of blocking.
1244 *
1245 * Returns the module object with incremented ref count.
1246 */
1247PyObject *
1248PyImport_ImportModuleNoBlock(const char *name)
1249{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001250 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001251}
1252
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001253
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001254/* Remove importlib frames from the traceback,
1255 * except in Verbose mode. */
1256static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001257remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001258{
1259 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001260 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001261 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001262 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001263 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001264 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001265 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001266
1267 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001268 from the traceback. We always trim chunks
1269 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001270
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001271 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001272 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001273 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001274 }
1275
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001276 if (PyType_IsSubtype((PyTypeObject *) exception,
1277 (PyTypeObject *) PyExc_ImportError))
1278 always_trim = 1;
1279
1280 prev_link = &base_tb;
1281 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001282 while (tb != NULL) {
1283 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1284 PyObject *next = (PyObject *) traceback->tb_next;
1285 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001286 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001287 int now_in_importlib;
1288
1289 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001290 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1291 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001292 if (now_in_importlib && !in_importlib) {
1293 /* This is the link to this chunk of importlib tracebacks */
1294 outer_link = prev_link;
1295 }
1296 in_importlib = now_in_importlib;
1297
1298 if (in_importlib &&
1299 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001300 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001301 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001302 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001303 prev_link = outer_link;
1304 }
1305 else {
1306 prev_link = (PyObject **) &traceback->tb_next;
1307 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001308 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001309 tb = next;
1310 }
1311done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001312 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001313}
1314
1315
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001316static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001317resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001318{
Brett Cannonfd074152012-04-14 14:10:13 -04001319 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001320 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001321 _Py_IDENTIFIER(parent);
1322 PyObject *abs_name;
1323 PyObject *package = NULL;
1324 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001325 Py_ssize_t last_dot;
1326 PyObject *base;
1327 int level_up;
1328
1329 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001330 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001331 goto error;
1332 }
1333 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001334 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001335 goto error;
1336 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001337 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001338 if (package == Py_None) {
1339 package = NULL;
1340 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001341 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001342 goto error;
1343 }
1344 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001345 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001346 goto error;
1347 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001348
1349 if (package != NULL) {
1350 Py_INCREF(package);
1351 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001352 _PyErr_SetString(tstate, PyExc_TypeError,
1353 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001354 goto error;
1355 }
1356 else if (spec != NULL && spec != Py_None) {
1357 int equal;
1358 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1359 if (parent == NULL) {
1360 goto error;
1361 }
1362
1363 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1364 Py_DECREF(parent);
1365 if (equal < 0) {
1366 goto error;
1367 }
1368 else if (equal == 0) {
1369 if (PyErr_WarnEx(PyExc_ImportWarning,
1370 "__package__ != __spec__.parent", 1) < 0) {
1371 goto error;
1372 }
1373 }
1374 }
1375 }
1376 else if (spec != NULL && spec != Py_None) {
1377 package = _PyObject_GetAttrId(spec, &PyId_parent);
1378 if (package == NULL) {
1379 goto error;
1380 }
1381 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001382 _PyErr_SetString(tstate, PyExc_TypeError,
1383 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001384 goto error;
1385 }
1386 }
1387 else {
1388 if (PyErr_WarnEx(PyExc_ImportWarning,
1389 "can't resolve package from __spec__ or __package__, "
1390 "falling back on __name__ and __path__", 1) < 0) {
1391 goto error;
1392 }
1393
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001394 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001395 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001396 if (!_PyErr_Occurred(tstate)) {
1397 _PyErr_SetString(tstate, PyExc_KeyError,
1398 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001399 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001400 goto error;
1401 }
1402
1403 Py_INCREF(package);
1404 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001405 _PyErr_SetString(tstate, PyExc_TypeError,
1406 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001407 goto error;
1408 }
1409
Serhiy Storchakab510e102020-10-26 12:47:57 +02001410 int haspath = _PyDict_ContainsId(globals, &PyId___path__);
1411 if (haspath < 0) {
1412 goto error;
1413 }
1414 if (!haspath) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001415 Py_ssize_t dot;
1416
Serhiy Storchakab510e102020-10-26 12:47:57 +02001417 if (PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001418 goto error;
1419 }
1420
1421 dot = PyUnicode_FindChar(package, '.',
1422 0, PyUnicode_GET_LENGTH(package), -1);
1423 if (dot == -2) {
1424 goto error;
1425 }
Ben Lewis92420b32019-09-11 20:09:47 +10001426 else if (dot == -1) {
1427 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001428 }
Ben Lewis92420b32019-09-11 20:09:47 +10001429 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1430 if (substr == NULL) {
1431 goto error;
1432 }
1433 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001434 }
1435 }
1436
1437 last_dot = PyUnicode_GET_LENGTH(package);
1438 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001439 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001440 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001441
1442 for (level_up = 1; level_up < level; level_up += 1) {
1443 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1444 if (last_dot == -2) {
1445 goto error;
1446 }
1447 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001448 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001449 "attempted relative import beyond top-level "
1450 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001451 goto error;
1452 }
1453 }
1454
1455 base = PyUnicode_Substring(package, 0, last_dot);
1456 Py_DECREF(package);
1457 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1458 return base;
1459 }
1460
1461 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1462 Py_DECREF(base);
1463 return abs_name;
1464
Ben Lewis92420b32019-09-11 20:09:47 +10001465 no_parent_error:
1466 _PyErr_SetString(tstate, PyExc_ImportError,
1467 "attempted relative import "
1468 "with no known parent package");
1469
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001470 error:
1471 Py_XDECREF(package);
1472 return NULL;
1473}
1474
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001475static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001476import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001477{
1478 _Py_IDENTIFIER(_find_and_load);
1479 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001480 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001481 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001482 static int import_level;
1483 static _PyTime_t accumulated;
1484
1485 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1486
Steve Dowerb82e17e2019-05-23 08:45:22 -07001487 PyObject *sys_path = PySys_GetObject("path");
1488 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1489 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001490 if (_PySys_Audit(tstate, "import", "OOOOO",
1491 abs_name, Py_None, sys_path ? sys_path : Py_None,
1492 sys_meta_path ? sys_meta_path : Py_None,
1493 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001494 return NULL;
1495 }
1496
1497
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001498 /* XOptions is initialized after first some imports.
1499 * So we can't have negative cache before completed initialization.
1500 * Anyway, importlib._find_and_load is much slower than
1501 * _PyDict_GetItemIdWithError().
1502 */
1503 if (import_time) {
1504 static int header = 1;
1505 if (header) {
1506 fputs("import time: self [us] | cumulative | imported package\n",
1507 stderr);
1508 header = 0;
1509 }
1510
1511 import_level++;
1512 t1 = _PyTime_GetPerfCounter();
1513 accumulated = 0;
1514 }
1515
1516 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001517 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001518
1519 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1520 &PyId__find_and_load, abs_name,
1521 interp->import_func, NULL);
1522
1523 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001524 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001525 mod != NULL);
1526
1527 if (import_time) {
1528 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1529
1530 import_level--;
1531 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1532 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1533 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1534 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1535
1536 accumulated = accumulated_copy + cum;
1537 }
1538
1539 return mod;
1540}
1541
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001542PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001543PyImport_GetModule(PyObject *name)
1544{
1545 PyThreadState *tstate = _PyThreadState_GET();
1546 PyObject *mod;
1547
1548 mod = import_get_module(tstate, name);
1549 if (mod != NULL && mod != Py_None) {
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001550 if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001551 Py_DECREF(mod);
1552 remove_importlib_frames(tstate);
1553 return NULL;
1554 }
1555 }
1556 return mod;
1557}
1558
1559PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001560PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1561 PyObject *locals, PyObject *fromlist,
1562 int level)
1563{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001564 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001565 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001566 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001567 PyObject *final_mod = NULL;
1568 PyObject *mod = NULL;
1569 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001570 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001571 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001572
Brett Cannonfd074152012-04-14 14:10:13 -04001573 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001574 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001575 goto error;
1576 }
1577
1578 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1579 for added performance. */
1580
1581 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001582 _PyErr_SetString(tstate, PyExc_TypeError,
1583 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001584 goto error;
1585 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001586 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001587 goto error;
1588 }
1589 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001590 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001591 goto error;
1592 }
Brett Cannon849113a2016-01-22 15:25:50 -08001593
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001594 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001595 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001596 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001597 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001598 }
1599 else { /* level == 0 */
1600 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001601 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001602 goto error;
1603 }
Brett Cannonfd074152012-04-14 14:10:13 -04001604 abs_name = name;
1605 Py_INCREF(abs_name);
1606 }
1607
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001608 mod = import_get_module(tstate, abs_name);
1609 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001610 goto error;
1611 }
1612
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001613 if (mod != NULL && mod != Py_None) {
Antoine Pitrou2fd16ef2021-03-20 20:07:44 +01001614 if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001615 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001616 }
Brett Cannonfd074152012-04-14 14:10:13 -04001617 }
1618 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001619 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001620 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001621 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001622 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001623 }
1624 }
1625
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001626 has_from = 0;
1627 if (fromlist != NULL && fromlist != Py_None) {
1628 has_from = PyObject_IsTrue(fromlist);
1629 if (has_from < 0)
1630 goto error;
1631 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001632 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001633 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1634 if (level == 0 || len > 0) {
1635 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001636
Victor Stinner744c34e2016-05-20 11:36:13 +02001637 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1638 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001639 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001640 }
1641
Victor Stinner744c34e2016-05-20 11:36:13 +02001642 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001643 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001644 final_mod = mod;
1645 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001646 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001647 }
1648
Brett Cannonfd074152012-04-14 14:10:13 -04001649 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001650 PyObject *front = PyUnicode_Substring(name, 0, dot);
1651 if (front == NULL) {
1652 goto error;
1653 }
1654
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001655 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001656 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001657 }
1658 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001659 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001660 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001661 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001662 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001663 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001664 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001665 }
Brett Cannonfd074152012-04-14 14:10:13 -04001666
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001667 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001668 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001669 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001670 if (!_PyErr_Occurred(tstate)) {
1671 _PyErr_Format(tstate, PyExc_KeyError,
1672 "%R not in sys.modules as expected",
1673 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001674 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001675 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001676 }
Brett Cannonfd074152012-04-14 14:10:13 -04001677 }
1678 }
1679 else {
1680 final_mod = mod;
1681 Py_INCREF(mod);
1682 }
1683 }
1684 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001685 PyObject *path;
1686 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1687 goto error;
1688 }
1689 if (path) {
1690 Py_DECREF(path);
1691 final_mod = _PyObject_CallMethodIdObjArgs(
1692 interp->importlib, &PyId__handle_fromlist,
1693 mod, fromlist, interp->import_func, NULL);
1694 }
1695 else {
1696 final_mod = mod;
1697 Py_INCREF(mod);
1698 }
Brett Cannonfd074152012-04-14 14:10:13 -04001699 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001700
Brett Cannonfd074152012-04-14 14:10:13 -04001701 error:
1702 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001703 Py_XDECREF(mod);
1704 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001705 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001706 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001707 }
Brett Cannonfd074152012-04-14 14:10:13 -04001708 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001709}
1710
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001711PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001712PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001713 PyObject *fromlist, int level)
1714{
1715 PyObject *nameobj, *mod;
1716 nameobj = PyUnicode_FromString(name);
1717 if (nameobj == NULL)
1718 return NULL;
1719 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1720 fromlist, level);
1721 Py_DECREF(nameobj);
1722 return mod;
1723}
1724
1725
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001726/* Re-import a module of any kind and return its module object, WITH
1727 INCREMENTED REFERENCE COUNT */
1728
Guido van Rossum79f25d91997-04-29 20:08:16 +00001729PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001730PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001731{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001732 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001733 _Py_IDENTIFIER(reload);
1734 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001735 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1736 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001737 if (PyErr_Occurred()) {
1738 return NULL;
1739 }
1740
Robert Rouhanif40bd462020-05-01 16:28:06 -07001741 importlib = PyImport_ImportModule("importlib");
1742 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001743 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001746
Robert Rouhanif40bd462020-05-01 16:28:06 -07001747 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1748 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001749 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001750}
1751
1752
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001753/* Higher-level import emulator which emulates the "import" statement
1754 more accurately -- it invokes the __import__() function from the
1755 builtins of the current globals. This means that the import is
1756 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001757 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001758 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001759 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001760 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001761
1762PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001763PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001764{
junyixie88d99832021-03-22 17:47:10 +08001765 _Py_IDENTIFIER(__import__);
1766 _Py_IDENTIFIER(__builtins__);
1767
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001768 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyObject *globals = NULL;
1770 PyObject *import = NULL;
1771 PyObject *builtins = NULL;
1772 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* Initialize constant string objects */
junyixie88d99832021-03-22 17:47:10 +08001775 PyObject *import_str = _PyUnicode_FromId(&PyId___import__); // borrowed ref
1776 if (import_str == NULL) {
1777 return NULL;
1778 }
1779
1780 PyObject *builtins_str = _PyUnicode_FromId(&PyId___builtins__); // borrowed ref
1781 if (builtins_str == NULL) {
1782 return NULL;
1783 }
1784
1785 PyObject *from_list = PyList_New(0);
1786 if (from_list == NULL) {
1787 goto err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* Get the builtins from current globals */
1791 globals = PyEval_GetGlobals();
1792 if (globals != NULL) {
1793 Py_INCREF(globals);
1794 builtins = PyObject_GetItem(globals, builtins_str);
1795 if (builtins == NULL)
1796 goto err;
1797 }
1798 else {
1799 /* No globals -- use standard builtins, and fake globals */
1800 builtins = PyImport_ImportModuleLevel("builtins",
1801 NULL, NULL, NULL, 0);
junyixie88d99832021-03-22 17:47:10 +08001802 if (builtins == NULL) {
1803 goto err;
1804 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1806 if (globals == NULL)
1807 goto err;
1808 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 /* Get the __import__ function from the builtins */
1811 if (PyDict_Check(builtins)) {
1812 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001813 if (import == NULL) {
1814 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
1815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 }
1817 else
1818 import = PyObject_GetAttr(builtins, import_str);
1819 if (import == NULL)
1820 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001823 Always use absolute import here.
1824 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
junyixie88d99832021-03-22 17:47:10 +08001826 globals, from_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001827 if (r == NULL)
1828 goto err;
1829 Py_DECREF(r);
1830
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001831 r = import_get_module(tstate, module_name);
1832 if (r == NULL && !_PyErr_Occurred(tstate)) {
1833 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001834 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001835
1836 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 Py_XDECREF(globals);
1838 Py_XDECREF(builtins);
1839 Py_XDECREF(import);
junyixie88d99832021-03-22 17:47:10 +08001840 Py_XDECREF(from_list);
Tim Peters50d8d372001-02-28 05:34:27 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001843}
1844
Brett Cannon4caa61d2014-01-09 19:03:32 -05001845/*[clinic input]
1846_imp.extension_suffixes
1847
1848Returns the list of file suffixes used to identify extension modules.
1849[clinic start generated code]*/
1850
Brett Cannon4caa61d2014-01-09 19:03:32 -05001851static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001852_imp_extension_suffixes_impl(PyObject *module)
1853/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 list = PyList_New(0);
1858 if (list == NULL)
1859 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001860#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01001861 const char *suffix;
1862 unsigned int index = 0;
1863
Brett Cannon2657df42012-05-04 15:20:40 -04001864 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1865 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (item == NULL) {
1867 Py_DECREF(list);
1868 return NULL;
1869 }
1870 if (PyList_Append(list, item) < 0) {
1871 Py_DECREF(list);
1872 Py_DECREF(item);
1873 return NULL;
1874 }
1875 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001876 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 }
Brett Cannon2657df42012-05-04 15:20:40 -04001878#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001880}
1881
Brett Cannon4caa61d2014-01-09 19:03:32 -05001882/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001883_imp.init_frozen
1884
1885 name: unicode
1886 /
1887
1888Initializes a frozen module.
1889[clinic start generated code]*/
1890
Brett Cannon4caa61d2014-01-09 19:03:32 -05001891static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001892_imp_init_frozen_impl(PyObject *module, PyObject *name)
1893/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001894{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001895 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 int ret;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001897
Victor Stinner53dc7352011-03-20 01:50:21 +01001898 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (ret < 0)
1900 return NULL;
1901 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001902 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001904 return import_add_module(tstate, name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001905}
1906
Brett Cannon4caa61d2014-01-09 19:03:32 -05001907/*[clinic input]
1908_imp.get_frozen_object
1909
1910 name: unicode
1911 /
1912
1913Create a code object for a frozen module.
1914[clinic start generated code]*/
1915
Brett Cannon4caa61d2014-01-09 19:03:32 -05001916static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001917_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1918/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001921}
1922
Brett Cannon4caa61d2014-01-09 19:03:32 -05001923/*[clinic input]
1924_imp.is_frozen_package
1925
1926 name: unicode
1927 /
1928
1929Returns True if the module name is of a frozen package.
1930[clinic start generated code]*/
1931
Brett Cannon4caa61d2014-01-09 19:03:32 -05001932static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001933_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1934/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001937}
1938
Brett Cannon4caa61d2014-01-09 19:03:32 -05001939/*[clinic input]
1940_imp.is_builtin
1941
1942 name: unicode
1943 /
1944
1945Returns True if the module name corresponds to a built-in module.
1946[clinic start generated code]*/
1947
Guido van Rossum79f25d91997-04-29 20:08:16 +00001948static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001949_imp_is_builtin_impl(PyObject *module, PyObject *name)
1950/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001951{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001952 return PyLong_FromLong(is_builtin(name));
1953}
1954
1955/*[clinic input]
1956_imp.is_frozen
1957
1958 name: unicode
1959 /
1960
1961Returns True if the module name corresponds to a frozen module.
1962[clinic start generated code]*/
1963
Brett Cannon4caa61d2014-01-09 19:03:32 -05001964static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001965_imp_is_frozen_impl(PyObject *module, PyObject *name)
1966/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001967{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001968 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 p = find_frozen(name);
1971 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001972}
1973
Larry Hastings1df0b352015-08-24 19:53:56 -07001974/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1975static int
1976exec_builtin_or_dynamic(PyObject *mod) {
1977 PyModuleDef *def;
1978 void *state;
1979
1980 if (!PyModule_Check(mod)) {
1981 return 0;
1982 }
1983
1984 def = PyModule_GetDef(mod);
1985 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001986 return 0;
1987 }
Brett Cannon52794db2016-09-07 17:00:43 -07001988
Larry Hastings1df0b352015-08-24 19:53:56 -07001989 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001990 if (state) {
1991 /* Already initialized; skip reload */
1992 return 0;
1993 }
Brett Cannon52794db2016-09-07 17:00:43 -07001994
Larry Hastings1df0b352015-08-24 19:53:56 -07001995 return PyModule_ExecDef(mod, def);
1996}
1997
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001998#ifdef HAVE_DYNAMIC_LOADING
1999
Brett Cannon4caa61d2014-01-09 19:03:32 -05002000/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002001_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002002
Nick Coghland5cacbb2015-05-23 22:24:10 +10002003 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002004 file: object = NULL
2005 /
2006
Nick Coghland5cacbb2015-05-23 22:24:10 +10002007Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002008[clinic start generated code]*/
2009
Brett Cannon4caa61d2014-01-09 19:03:32 -05002010static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002011_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2012/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002013{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002014 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002015 FILE *fp;
2016
Nick Coghland5cacbb2015-05-23 22:24:10 +10002017 name = PyObject_GetAttrString(spec, "name");
2018 if (name == NULL) {
2019 return NULL;
2020 }
2021
2022 path = PyObject_GetAttrString(spec, "origin");
2023 if (path == NULL) {
2024 Py_DECREF(name);
2025 return NULL;
2026 }
2027
Serhiy Storchaka4db89882021-01-12 16:43:32 +02002028 PyThreadState *tstate = _PyThreadState_GET();
2029 mod = import_find_extension(tstate, name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002030 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002031 Py_DECREF(name);
2032 Py_DECREF(path);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002033 return mod;
2034 }
2035
Brett Cannon4caa61d2014-01-09 19:03:32 -05002036 if (file != NULL) {
2037 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002038 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002039 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002040 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002042 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002044 else
2045 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002046
2047 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2048
2049 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002050 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (fp)
2052 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002053 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002054}
2055
Nick Coghland5cacbb2015-05-23 22:24:10 +10002056/*[clinic input]
2057_imp.exec_dynamic -> int
2058
2059 mod: object
2060 /
2061
2062Initialize an extension module.
2063[clinic start generated code]*/
2064
2065static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002066_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2067/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002068{
Larry Hastings1df0b352015-08-24 19:53:56 -07002069 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002070}
2071
2072
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002073#endif /* HAVE_DYNAMIC_LOADING */
2074
Larry Hastings7726ac92014-01-31 22:03:12 -08002075/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002076_imp.exec_builtin -> int
2077
2078 mod: object
2079 /
2080
2081Initialize a built-in module.
2082[clinic start generated code]*/
2083
2084static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002085_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2086/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002087{
2088 return exec_builtin_or_dynamic(mod);
2089}
2090
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002091/*[clinic input]
2092_imp.source_hash
2093
2094 key: long
2095 source: Py_buffer
2096[clinic start generated code]*/
2097
2098static PyObject *
2099_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2100/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2101{
Benjamin Peterson83620772017-12-09 12:18:56 -08002102 union {
2103 uint64_t x;
2104 char data[sizeof(uint64_t)];
2105 } hash;
2106 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002107#if !PY_LITTLE_ENDIAN
2108 // Force to little-endian. There really ought to be a succinct standard way
2109 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002110 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2111 char tmp = hash.data[i];
2112 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2113 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002114 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002115#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002116 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002117}
2118
Barry Warsaw28a691b2010-04-17 00:19:56 +00002119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002121"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002122
Guido van Rossum79f25d91997-04-29 20:08:16 +00002123static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002124 _IMP_EXTENSION_SUFFIXES_METHODDEF
2125 _IMP_LOCK_HELD_METHODDEF
2126 _IMP_ACQUIRE_LOCK_METHODDEF
2127 _IMP_RELEASE_LOCK_METHODDEF
2128 _IMP_GET_FROZEN_OBJECT_METHODDEF
2129 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002130 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002131 _IMP_INIT_FROZEN_METHODDEF
2132 _IMP_IS_BUILTIN_METHODDEF
2133 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002134 _IMP_CREATE_DYNAMIC_METHODDEF
2135 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002136 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002137 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002138 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002139 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002140};
2141
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002142
Victor Stinner62230712020-11-18 23:18:29 +01002143static int
2144imp_module_exec(PyObject *module)
2145{
2146 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
2147 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
2148 if (pyc_mode == NULL) {
2149 return -1;
2150 }
2151 if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
2152 Py_DECREF(pyc_mode);
2153 return -1;
2154 }
2155 Py_DECREF(pyc_mode);
2156
2157 return 0;
2158}
2159
2160
2161static PyModuleDef_Slot imp_slots[] = {
2162 {Py_mod_exec, imp_module_exec},
2163 {0, NULL}
2164};
2165
2166static struct PyModuleDef imp_module = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 PyModuleDef_HEAD_INIT,
Victor Stinner62230712020-11-18 23:18:29 +01002168 .m_name = "_imp",
2169 .m_doc = doc_imp,
2170 .m_size = 0,
2171 .m_methods = imp_methods,
2172 .m_slots = imp_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00002173};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002174
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002175PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002176PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002177{
Victor Stinner62230712020-11-18 23:18:29 +01002178 return PyModuleDef_Init(&imp_module);
2179}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002180
Victor Stinner62230712020-11-18 23:18:29 +01002181
2182// Import the _imp extension by calling manually _imp.create_builtin() and
2183// _imp.exec_builtin() since importlib is not initialized yet. Initializing
2184// importlib requires the _imp module: this function fix the bootstrap issue.
2185PyObject*
2186_PyImport_BootstrapImp(PyThreadState *tstate)
2187{
2188 PyObject *name = PyUnicode_FromString("_imp");
2189 if (name == NULL) {
2190 return NULL;
Victor Stinner410b85a2019-05-13 17:12:45 +02002191 }
2192
Victor Stinner62230712020-11-18 23:18:29 +01002193 // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
2194 // an object with just a name attribute.
2195 //
2196 // _imp.__spec__ is overriden by importlib._bootstrap._instal() anyway.
2197 PyObject *attrs = Py_BuildValue("{sO}", "name", name);
2198 if (attrs == NULL) {
2199 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002200 }
Victor Stinner62230712020-11-18 23:18:29 +01002201 PyObject *spec = _PyNamespace_New(attrs);
2202 Py_DECREF(attrs);
2203 if (spec == NULL) {
2204 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002205 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002206
Victor Stinner62230712020-11-18 23:18:29 +01002207 // Create the _imp module from its definition.
2208 PyObject *mod = create_builtin(tstate, name, spec);
2209 Py_CLEAR(name);
2210 Py_DECREF(spec);
2211 if (mod == NULL) {
2212 goto error;
2213 }
2214 assert(mod != Py_None); // not found
2215
2216 // Execute the _imp module: call imp_module_exec().
2217 if (exec_builtin_or_dynamic(mod) < 0) {
2218 Py_DECREF(mod);
2219 goto error;
2220 }
2221 return mod;
2222
2223error:
2224 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002226}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002227
2228
Guido van Rossumb18618d2000-05-03 23:44:39 +00002229/* API for embedding applications that want to add their own entries
2230 to the table of built-in modules. This should normally be called
2231 *before* Py_Initialize(). When the table resize fails, -1 is
2232 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002233
2234 After a similar function by Just van Rossum. */
2235
2236int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002237PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002240 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002241 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 /* Count the number of entries in both tables */
2244 for (n = 0; newtab[n].name != NULL; n++)
2245 ;
2246 if (n == 0)
2247 return 0; /* Nothing to do */
2248 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2249 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002250
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002251 /* Force default raw memory allocator to get a known allocator to be able
2252 to release the memory in _PyImport_Fini2() */
2253 PyMemAllocatorEx old_alloc;
2254 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002257 p = NULL;
2258 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002259 size_t size = sizeof(struct _inittab) * (i + n + 1);
2260 p = PyMem_RawRealloc(inittab_copy, size);
2261 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002262 if (p == NULL) {
2263 res = -1;
2264 goto done;
2265 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002266
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002267 /* Copy the tables into the new memory at the first call
2268 to PyImport_ExtendInittab(). */
2269 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002271 }
2272 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2273 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002274
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002275done:
2276 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2277 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002278}
2279
2280/* Shorthand to add a single entry given a name and a function */
2281
2282int
Brett Cannona826f322009-04-02 03:41:46 +00002283PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002288
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002289 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002293}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002294
2295#ifdef __cplusplus
2296}
2297#endif