blob: 75ac21df82da94db5f018ec1f89728fafe9d6217 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module definition and import implementation */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner62230712020-11-18 23:18:29 +01007#include "pycore_import.h" // _PyImport_BootstrapImp()
Victor Stinner61691d82019-10-02 23:51:20 +02008#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02009#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010010#include "pycore_pyhash.h"
11#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020012#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020013#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
14#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010015#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000016#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000019#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020020#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000021
Guido van Rossum55a83382000-09-20 20:31:38 +000022#ifdef HAVE_FCNTL_H
23#include <fcntl.h>
24#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000026extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000028
Barry Warsaw28a691b2010-04-17 00:19:56 +000029#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000030
Victor Stinner0a28f8d2019-06-19 02:54:39 +020031/* Forward references */
32static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
33
Victor Stinner95872862011-03-07 18:20:56 +010034/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000035static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000036
Guido van Rossum771c6c81997-10-31 18:37:24 +000037/* This table is defined in config.c: */
38extern struct _inittab _PyImport_Inittab[];
39
40struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010041static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000042
Hai Shi46874c22020-01-30 17:20:25 -060043_Py_IDENTIFIER(__path__);
44_Py_IDENTIFIER(__spec__);
45
Brett Cannon4caa61d2014-01-09 19:03:32 -050046/*[clinic input]
47module _imp
48[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030049/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040050
51#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050052
Guido van Rossum1ae940a1995-01-02 19:04:15 +000053/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054
Victor Stinner331a6a52019-05-27 16:39:22 +020055PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020056_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040057{
ukwksk5e6312c2018-05-15 04:10:52 +090058 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040059 int err = 0;
60
61 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020062 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020063 _PyErr_SetString(tstate, PyExc_RuntimeError,
64 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040065 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020066 }
Brett Cannonfd074152012-04-14 14:10:13 -040067
Victor Stinnerda7933e2020-04-13 03:04:28 +020068 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +020069 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -040070 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020071 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
ukwksk5e6312c2018-05-15 04:10:52 +090073 zipimport = PyImport_ImportModule("zipimport");
74 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020075 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020076 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 }
80 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020081 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090082 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020083 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090084 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020086 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020087 if (verbose) {
88 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
89 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 }
91 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -040092 /* sys.path_hooks.insert(0, zipimporter) */
93 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -040095 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -040097 }
Victor Stinner410b85a2019-05-13 17:12:45 +020098 if (verbose) {
99 PySys_WriteStderr("# installed zipimport hook\n");
100 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 }
102 }
Brett Cannonfd074152012-04-14 14:10:13 -0400103
Victor Stinner331a6a52019-05-27 16:39:22 +0200104 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400105
106 error:
107 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200108 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000109}
110
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000111/* Locking primitives to prevent parallel imports of the same module
112 in different threads to return with a partially loaded module.
113 These calls are serialized by the global interpreter lock. */
114
Victor Stinner26881c82020-06-02 15:51:37 +0200115static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200116static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000117static int import_lock_level = 0;
118
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000119void
120_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000121{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200122 unsigned long me = PyThread_get_thread_ident();
123 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 return; /* Too bad */
125 if (import_lock == NULL) {
126 import_lock = PyThread_allocate_lock();
127 if (import_lock == NULL)
128 return; /* Nothing much we can do. */
129 }
130 if (import_lock_thread == me) {
131 import_lock_level++;
132 return;
133 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200134 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
135 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 {
137 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200138 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 PyEval_RestoreThread(tstate);
140 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100141 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 import_lock_thread = me;
143 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000144}
145
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000146int
147_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200149 unsigned long me = PyThread_get_thread_ident();
150 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 return 0; /* Too bad */
152 if (import_lock_thread != me)
153 return -1;
154 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100155 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200157 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 PyThread_release_lock(import_lock);
159 }
160 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000161}
162
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900163#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200164/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000165 created child processes do not share locks with the parent.
166 We now acquire the import lock around fork() calls but on some platforms
167 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200168PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000169_PyImport_ReInitLock(void)
170{
Christian Heimes418fd742015-04-19 21:08:42 +0200171 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900172 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200173 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200174 }
175 }
Victor Stinner26881c82020-06-02 15:51:37 +0200176
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000177 if (import_lock_level > 1) {
178 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200179 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200180 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000181 import_lock_thread = me;
182 import_lock_level--;
183 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200184 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000185 import_lock_level = 0;
186 }
Victor Stinner26881c82020-06-02 15:51:37 +0200187 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000188}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900189#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000190
Brett Cannon4caa61d2014-01-09 19:03:32 -0500191/*[clinic input]
192_imp.lock_held
193
194Return True if the import lock is currently held, else False.
195
196On platforms without threads, return False.
197[clinic start generated code]*/
198
Brett Cannon4caa61d2014-01-09 19:03:32 -0500199static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300200_imp_lock_held_impl(PyObject *module)
201/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000202{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200203 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000204}
205
Brett Cannon4caa61d2014-01-09 19:03:32 -0500206/*[clinic input]
207_imp.acquire_lock
208
209Acquires the interpreter's import lock for the current thread.
210
211This lock should be used by import hooks to ensure thread-safety when importing
212modules. On platforms without threads, this function does nothing.
213[clinic start generated code]*/
214
Brett Cannon4caa61d2014-01-09 19:03:32 -0500215static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300216_imp_acquire_lock_impl(PyObject *module)
217/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200220 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000221}
222
Brett Cannon4caa61d2014-01-09 19:03:32 -0500223/*[clinic input]
224_imp.release_lock
225
226Release the interpreter's import lock.
227
228On platforms without threads, this function does nothing.
229[clinic start generated code]*/
230
Brett Cannon4caa61d2014-01-09 19:03:32 -0500231static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300232_imp_release_lock_impl(PyObject *module)
233/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (_PyImport_ReleaseLock() < 0) {
236 PyErr_SetString(PyExc_RuntimeError,
237 "not holding the import lock");
238 return NULL;
239 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200240 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000241}
242
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100243void
244_PyImport_Fini(void)
245{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200246 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100247 if (import_lock != NULL) {
248 PyThread_free_lock(import_lock);
249 import_lock = NULL;
250 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100251}
252
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100253void
254_PyImport_Fini2(void)
255{
256 /* Use the same memory allocator than PyImport_ExtendInittab(). */
257 PyMemAllocatorEx old_alloc;
258 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
259
260 /* Free memory allocated by PyImport_ExtendInittab() */
261 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700262 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100263
264 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
265}
266
Guido van Rossum25ce5661997-08-02 03:10:38 +0000267/* Helper for sys */
268
269PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000270PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271{
Victor Stinner81a7be32020-04-14 15:14:01 +0200272 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600273 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100274 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600275 }
Eric Snow93c92f72017-09-13 23:46:04 -0700276 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000277}
278
Eric Snowd393c1b2017-09-14 12:18:12 -0600279/* In some corner cases it is important to be sure that the import
280 machinery has been initialized (or not cleaned up yet). For
281 example, see issue #4236 and PyModule_Create2(). */
282
283int
284_PyImport_IsInitialized(PyInterpreterState *interp)
285{
286 if (interp->modules == NULL)
287 return 0;
288 return 1;
289}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000290
Eric Snow3f9eee62017-09-15 16:35:20 -0600291PyObject *
292_PyImport_GetModuleId(struct _Py_Identifier *nameid)
293{
294 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
295 if (name == NULL) {
296 return NULL;
297 }
298 return PyImport_GetModule(name);
299}
300
301int
302_PyImport_SetModule(PyObject *name, PyObject *m)
303{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200304 PyThreadState *tstate = _PyThreadState_GET();
305 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600306 return PyObject_SetItem(modules, name, m);
307}
308
309int
310_PyImport_SetModuleString(const char *name, PyObject *m)
311{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200312 PyThreadState *tstate = _PyThreadState_GET();
313 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600314 return PyMapping_SetItemString(modules, name, m);
315}
316
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200317static PyObject *
318import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600319{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200320 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600321 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200322 _PyErr_SetString(tstate, PyExc_RuntimeError,
323 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600324 return NULL;
325 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200326
327 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600328 Py_INCREF(modules);
329 if (PyDict_CheckExact(modules)) {
330 m = PyDict_GetItemWithError(modules, name); /* borrowed */
331 Py_XINCREF(m);
332 }
333 else {
334 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200335 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
336 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600337 }
338 }
339 Py_DECREF(modules);
340 return m;
341}
342
343
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100344static int
345import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200346{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100347 PyInterpreterState *interp = tstate->interp;
348 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
444 if (_Py_IsMainInterpreter(tstate)) {
445 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
559
560/* Get the module object corresponding to a module name.
561 First check the modules dictionary if there's one there,
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200562 if not, create a new one and insert it in the modules dictionary. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000563
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200564static PyObject *
565import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000566{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200567 PyObject *modules = tstate->interp->modules;
568 if (modules == NULL) {
569 _PyErr_SetString(tstate, PyExc_RuntimeError,
570 "no import module dictionary");
571 return NULL;
572 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600573
Eric Snow86b7afd2017-09-04 17:54:09 -0600574 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600575 if (PyDict_CheckExact(modules)) {
576 m = PyDict_GetItemWithError(modules, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200577 Py_XINCREF(m);
Eric Snow3f9eee62017-09-15 16:35:20 -0600578 }
579 else {
580 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000581 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600582 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200583 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
584 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600585 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200586 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200587 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200588 return NULL;
589 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600590 if (m != NULL && PyModule_Check(m)) {
591 return m;
592 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200593 Py_XDECREF(m);
Victor Stinner27ee0892011-03-04 12:57:09 +0000594 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (m == NULL)
596 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600597 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 Py_DECREF(m);
599 return NULL;
600 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000603}
604
Victor Stinner27ee0892011-03-04 12:57:09 +0000605PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200606PyImport_AddModuleObject(PyObject *name)
607{
608 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200609 PyObject *mod = import_add_module(tstate, name);
610 if (mod) {
611 PyObject *ref = PyWeakref_NewRef(mod, NULL);
612 Py_DECREF(mod);
613 if (ref == NULL) {
614 return NULL;
615 }
616 mod = PyWeakref_GetObject(ref);
617 Py_DECREF(ref);
618 }
619 return mod; /* borrowed reference */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200620}
621
622
623PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000624PyImport_AddModule(const char *name)
625{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200626 PyObject *nameobj = PyUnicode_FromString(name);
627 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000628 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200629 }
630 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000631 Py_DECREF(nameobj);
632 return module;
633}
634
635
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300636/* Remove name from sys.modules, if it's there.
637 * Can be called with an exception raised.
638 * If fail to remove name a new exception will be chained with the old
639 * exception, otherwise the old exception is preserved.
640 */
Tim Peters1cd70172004-08-02 03:52:12 +0000641static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200642remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000643{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600644 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200645 _PyErr_Fetch(tstate, &type, &value, &traceback);
646
647 PyObject *modules = tstate->interp->modules;
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300648 if (PyDict_CheckExact(modules)) {
649 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
650 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600651 }
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300652 else if (PyMapping_DelItem(modules, name) < 0) {
653 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
654 _PyErr_Clear(tstate);
655 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600656 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200657
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300658 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000659}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000660
Christian Heimes3b06e532008-01-07 20:12:44 +0000661
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000662/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000663 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
664 * removed from sys.modules, to avoid leaving damaged module objects
665 * in sys.modules. The caller may wish to restore the original
666 * module object (if any) in this case; PyImport_ReloadModule is an
667 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000668 *
669 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
670 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000671 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000672PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300673PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return PyImport_ExecCodeModuleWithPathnames(
676 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000677}
678
679PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300680PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 return PyImport_ExecCodeModuleWithPathnames(
683 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000684}
685
686PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300687PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
688 const char *pathname,
689 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000690{
Victor Stinner27ee0892011-03-04 12:57:09 +0000691 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600692 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000693
694 nameobj = PyUnicode_FromString(name);
695 if (nameobj == NULL)
696 return NULL;
697
Victor Stinner27ee0892011-03-04 12:57:09 +0000698 if (cpathname != NULL) {
699 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
700 if (cpathobj == NULL)
701 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400702 }
703 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000704 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400705
706 if (pathname != NULL) {
707 pathobj = PyUnicode_DecodeFSDefault(pathname);
708 if (pathobj == NULL)
709 goto error;
710 }
711 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200712 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400713 _Py_IDENTIFIER(_get_sourcefile);
714
715 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100716 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400717 }
718
Eric Snow32439d62015-05-02 19:15:18 -0600719 external= PyObject_GetAttrString(interp->importlib,
720 "_bootstrap_external");
721 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200722 pathobj = _PyObject_CallMethodIdOneArg(
723 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600724 Py_DECREF(external);
725 }
Brett Cannona6473f92012-07-13 13:57:03 -0400726 if (pathobj == NULL)
727 PyErr_Clear();
728 }
729 else
730 pathobj = NULL;
731
Victor Stinner27ee0892011-03-04 12:57:09 +0000732 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
733error:
734 Py_DECREF(nameobj);
735 Py_XDECREF(pathobj);
736 Py_XDECREF(cpathobj);
737 return m;
738}
739
Brett Cannon18fc4e72014-04-04 10:01:46 -0400740static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200741module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000742{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200743 _Py_IDENTIFIER(__builtins__);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200744 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000745
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200746 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (m == NULL)
748 return NULL;
749 /* If the module is being reloaded, we get the old module back
750 and re-use its dict to exec the new code. */
751 d = PyModule_GetDict(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200752 int r = _PyDict_ContainsId(d, &PyId___builtins__);
753 if (r == 0) {
754 r = _PyDict_SetItemId(d, &PyId___builtins__,
755 PyEval_GetBuiltins());
756 }
757 if (r < 0) {
758 remove_module(tstate, name);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200759 Py_DECREF(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200760 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400762
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200763 Py_INCREF(d);
764 Py_DECREF(m);
765 return d;
Brett Cannon18fc4e72014-04-04 10:01:46 -0400766}
767
768static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200769exec_code_in_module(PyThreadState *tstate, PyObject *name,
770 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -0400771{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400772 PyObject *v, *m;
773
774 v = PyEval_EvalCode(code_object, module_dict, module_dict);
775 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200776 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400777 return NULL;
778 }
779 Py_DECREF(v);
780
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200781 m = import_get_module(tstate, name);
782 if (m == NULL && !_PyErr_Occurred(tstate)) {
783 _PyErr_Format(tstate, PyExc_ImportError,
784 "Loaded module %R not found in sys.modules",
785 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400786 }
787
Brett Cannon18fc4e72014-04-04 10:01:46 -0400788 return m;
789}
790
791PyObject*
792PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
793 PyObject *cpathname)
794{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200795 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600796 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600797 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400798
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200799 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400800 if (d == NULL) {
801 return NULL;
802 }
803
Eric Snow08197a42014-05-12 17:54:55 -0600804 if (pathname == NULL) {
805 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200807 external = PyObject_GetAttrString(tstate->interp->importlib,
808 "_bootstrap_external");
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200809 if (external == NULL) {
810 Py_DECREF(d);
Eric Snow32439d62015-05-02 19:15:18 -0600811 return NULL;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200812 }
Eric Snow32439d62015-05-02 19:15:18 -0600813 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600814 &PyId__fix_up_module,
815 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600816 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600817 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600818 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200819 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200821 Py_DECREF(d);
Eric Snow08197a42014-05-12 17:54:55 -0600822 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000823}
824
825
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000826static void
827update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyObject *constants, *tmp;
830 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (PyUnicode_Compare(co->co_filename, oldname))
833 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000834
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200835 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300836 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 constants = co->co_consts;
839 n = PyTuple_GET_SIZE(constants);
840 for (i = 0; i < n; i++) {
841 tmp = PyTuple_GET_ITEM(constants, i);
842 if (PyCode_Check(tmp))
843 update_code_filenames((PyCodeObject *)tmp,
844 oldname, newname);
845 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000846}
847
Victor Stinner2f42ae52011-03-20 00:41:24 +0100848static void
849update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000850{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100851 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000852
Victor Stinner2f42ae52011-03-20 00:41:24 +0100853 if (PyUnicode_Compare(co->co_filename, newname) == 0)
854 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 oldname = co->co_filename;
857 Py_INCREF(oldname);
858 update_code_filenames(co, oldname, newname);
859 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000860}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000861
Brett Cannon4caa61d2014-01-09 19:03:32 -0500862/*[clinic input]
863_imp._fix_co_filename
864
865 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
866 Code object to change.
867
868 path: unicode
869 File path to use.
870 /
871
872Changes code.co_filename to specify the passed-in file path.
873[clinic start generated code]*/
874
Brett Cannon4caa61d2014-01-09 19:03:32 -0500875static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300876_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400877 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300878/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700879
Brett Cannon4caa61d2014-01-09 19:03:32 -0500880{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500881 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700882
883 Py_RETURN_NONE;
884}
885
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000887/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700888static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000889
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000890
891/* Helper to test for built-in module */
892
893static int
Victor Stinner95872862011-03-07 18:20:56 +0100894is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000895{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200896 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200898 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (PyImport_Inittab[i].initfunc == NULL)
900 return -1;
901 else
902 return 1;
903 }
904 }
905 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000906}
907
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000908
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700909/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000910 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000911 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000912 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700913 this tells our caller that the path based finder could not find
914 a finder for this path item. Cache the result in
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200915 path_importer_cache. */
Just van Rossum52e14d62002-12-30 22:08:05 +0000916
917static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200918get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
919 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyObject *importer;
922 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* These conditions are the caller's responsibility: */
925 assert(PyList_Check(path_hooks));
926 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 nhooks = PyList_Size(path_hooks);
929 if (nhooks < 0)
930 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000931
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200932 importer = PyDict_GetItemWithError(path_importer_cache, p);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200933 if (importer != NULL || _PyErr_Occurred(tstate)) {
934 Py_XINCREF(importer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 return importer;
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200936 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* set path_importer_cache[p] to None to avoid recursion */
939 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
940 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 for (j = 0; j < nhooks; j++) {
943 PyObject *hook = PyList_GetItem(path_hooks, j);
944 if (hook == NULL)
945 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +0100946 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (importer != NULL)
948 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000949
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200950 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 return NULL;
952 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200953 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 }
955 if (importer == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200956 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200958 if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 Py_DECREF(importer);
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200960 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
962 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000963}
964
Benjamin Petersone5024512018-09-12 12:06:42 -0700965PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200966PyImport_GetImporter(PyObject *path)
967{
968 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200969 PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
970 PyObject *path_hooks = PySys_GetObject("path_hooks");
971 if (path_importer_cache == NULL || path_hooks == NULL) {
972 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200974 return get_path_importer(tstate, path_importer_cache, path_hooks, path);
Christian Heimes9cd17752007-11-18 19:35:23 +0000975}
976
Victor Stinner62230712020-11-18 23:18:29 +0100977static PyObject*
978create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
979{
Serhiy Storchaka4db89882021-01-12 16:43:32 +0200980 PyObject *mod = import_find_extension(tstate, name, name);
Victor Stinner62230712020-11-18 23:18:29 +0100981 if (mod || _PyErr_Occurred(tstate)) {
Victor Stinner62230712020-11-18 23:18:29 +0100982 return mod;
983 }
984
985 PyObject *modules = tstate->interp->modules;
986 for (struct _inittab *p = PyImport_Inittab; p->name != NULL; p++) {
987 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
988 if (p->initfunc == NULL) {
989 /* Cannot re-init internal module ("sys" or "builtins") */
990 return PyImport_AddModuleObject(name);
991 }
992
993 mod = (*p->initfunc)();
994 if (mod == NULL) {
995 return NULL;
996 }
997
998 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
999 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1000 }
1001 else {
1002 /* Remember pointer to module init function. */
1003 PyModuleDef *def = PyModule_GetDef(mod);
1004 if (def == NULL) {
1005 return NULL;
1006 }
1007
1008 def->m_base.m_init = p->initfunc;
1009 if (_PyImport_FixupExtensionObject(mod, name, name,
1010 modules) < 0) {
1011 return NULL;
1012 }
1013 return mod;
1014 }
1015 }
1016 }
1017
1018 // not found
1019 Py_RETURN_NONE;
1020}
1021
1022
1023
Nick Coghland5cacbb2015-05-23 22:24:10 +10001024/*[clinic input]
1025_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001026
Nick Coghland5cacbb2015-05-23 22:24:10 +10001027 spec: object
1028 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001029
Nick Coghland5cacbb2015-05-23 22:24:10 +10001030Create an extension module.
1031[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001032
Nick Coghland5cacbb2015-05-23 22:24:10 +10001033static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001034_imp_create_builtin(PyObject *module, PyObject *spec)
1035/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001036{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001037 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001038
Victor Stinner62230712020-11-18 23:18:29 +01001039 PyObject *name = PyObject_GetAttrString(spec, "name");
Nick Coghland5cacbb2015-05-23 22:24:10 +10001040 if (name == NULL) {
1041 return NULL;
1042 }
1043
Victor Stinner62230712020-11-18 23:18:29 +01001044 PyObject *mod = create_builtin(tstate, name, spec);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001045 Py_DECREF(name);
Victor Stinner62230712020-11-18 23:18:29 +01001046 return mod;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001047}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001048
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001049
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001050/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001051
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001052static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001053find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001054{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001055 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001056
Victor Stinner53dc7352011-03-20 01:50:21 +01001057 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 for (p = PyImport_FrozenModules; ; p++) {
1061 if (p->name == NULL)
1062 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001063 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 break;
1065 }
1066 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001067}
1068
Guido van Rossum79f25d91997-04-29 20:08:16 +00001069static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001070get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001071{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001072 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (p == NULL) {
1076 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001077 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 name);
1079 return NULL;
1080 }
1081 if (p->code == NULL) {
1082 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001083 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 name);
1085 return NULL;
1086 }
1087 size = p->size;
1088 if (size < 0)
1089 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001090 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001091}
1092
Brett Cannon8d110132009-03-15 02:20:16 +00001093static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001094is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001095{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001096 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 if (p == NULL) {
1100 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001101 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 name);
1103 return NULL;
1104 }
Brett Cannon8d110132009-03-15 02:20:16 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 if (size < 0)
1109 Py_RETURN_TRUE;
1110 else
1111 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001112}
1113
1114
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001115/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001116 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001117 an exception set if the initialization failed.
1118 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001119
1120int
Victor Stinner53dc7352011-03-20 01:50:21 +01001121PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001122{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001123 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001124 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001125 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 int ispackage;
1127 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001128
Victor Stinner53dc7352011-03-20 01:50:21 +01001129 p = find_frozen(name);
1130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (p == NULL)
1132 return 0;
1133 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001134 _PyErr_Format(tstate, PyExc_ImportError,
1135 "Excluded frozen object named %R",
1136 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 return -1;
1138 }
1139 size = p->size;
1140 ispackage = (size < 0);
1141 if (ispackage)
1142 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001143 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (co == NULL)
1145 return -1;
1146 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001147 _PyErr_Format(tstate, PyExc_TypeError,
1148 "frozen object %R is not a code object",
1149 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 goto err_return;
1151 }
1152 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001153 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001154 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001156 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (m == NULL)
1158 goto err_return;
1159 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001160 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (l == NULL) {
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001162 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 goto err_return;
1164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 err = PyDict_SetItemString(d, "__path__", l);
1166 Py_DECREF(l);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001167 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (err != 0)
1169 goto err_return;
1170 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001171 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001172 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001173 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001174 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001175 m = exec_code_in_module(tstate, name, d, co);
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001176 Py_DECREF(d);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001177 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001179 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 Py_DECREF(co);
1181 Py_DECREF(m);
1182 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001183
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001184err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 Py_DECREF(co);
1186 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001187}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001188
Victor Stinner53dc7352011-03-20 01:50:21 +01001189int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001190PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001191{
1192 PyObject *nameobj;
1193 int ret;
1194 nameobj = PyUnicode_InternFromString(name);
1195 if (nameobj == NULL)
1196 return -1;
1197 ret = PyImport_ImportFrozenModuleObject(nameobj);
1198 Py_DECREF(nameobj);
1199 return ret;
1200}
1201
Guido van Rossum74e6a111994-08-29 12:54:38 +00001202
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001203/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001204 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001205
Guido van Rossum79f25d91997-04-29 20:08:16 +00001206PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001207PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *pname;
1210 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 pname = PyUnicode_FromString(name);
1213 if (pname == NULL)
1214 return NULL;
1215 result = PyImport_Import(pname);
1216 Py_DECREF(pname);
1217 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001218}
1219
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001220
Christian Heimes072c0f12008-01-03 23:01:04 +00001221/* Import a module without blocking
1222 *
1223 * At first it tries to fetch the module from sys.modules. If the module was
1224 * never loaded before it loads it with PyImport_ImportModule() unless another
1225 * thread holds the import lock. In the latter case the function raises an
1226 * ImportError instead of blocking.
1227 *
1228 * Returns the module object with incremented ref count.
1229 */
1230PyObject *
1231PyImport_ImportModuleNoBlock(const char *name)
1232{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001233 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001234}
1235
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001236
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001237/* Remove importlib frames from the traceback,
1238 * except in Verbose mode. */
1239static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001240remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001241{
1242 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001243 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001244 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001245 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001246 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001247 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001248 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001249
1250 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001251 from the traceback. We always trim chunks
1252 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001253
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001254 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001255 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001256 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001257 }
1258
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001259 if (PyType_IsSubtype((PyTypeObject *) exception,
1260 (PyTypeObject *) PyExc_ImportError))
1261 always_trim = 1;
1262
1263 prev_link = &base_tb;
1264 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001265 while (tb != NULL) {
1266 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1267 PyObject *next = (PyObject *) traceback->tb_next;
1268 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001269 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001270 int now_in_importlib;
1271
1272 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001273 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1274 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001275 if (now_in_importlib && !in_importlib) {
1276 /* This is the link to this chunk of importlib tracebacks */
1277 outer_link = prev_link;
1278 }
1279 in_importlib = now_in_importlib;
1280
1281 if (in_importlib &&
1282 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001283 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001284 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001285 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001286 prev_link = outer_link;
1287 }
1288 else {
1289 prev_link = (PyObject **) &traceback->tb_next;
1290 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001291 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001292 tb = next;
1293 }
1294done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001295 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001296}
1297
1298
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001299static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001300resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001301{
Brett Cannonfd074152012-04-14 14:10:13 -04001302 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001303 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001304 _Py_IDENTIFIER(parent);
1305 PyObject *abs_name;
1306 PyObject *package = NULL;
1307 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001308 Py_ssize_t last_dot;
1309 PyObject *base;
1310 int level_up;
1311
1312 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001313 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001314 goto error;
1315 }
1316 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001317 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001318 goto error;
1319 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001320 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001321 if (package == Py_None) {
1322 package = NULL;
1323 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001324 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001325 goto error;
1326 }
1327 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001328 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001329 goto error;
1330 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001331
1332 if (package != NULL) {
1333 Py_INCREF(package);
1334 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001335 _PyErr_SetString(tstate, PyExc_TypeError,
1336 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001337 goto error;
1338 }
1339 else if (spec != NULL && spec != Py_None) {
1340 int equal;
1341 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1342 if (parent == NULL) {
1343 goto error;
1344 }
1345
1346 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1347 Py_DECREF(parent);
1348 if (equal < 0) {
1349 goto error;
1350 }
1351 else if (equal == 0) {
1352 if (PyErr_WarnEx(PyExc_ImportWarning,
1353 "__package__ != __spec__.parent", 1) < 0) {
1354 goto error;
1355 }
1356 }
1357 }
1358 }
1359 else if (spec != NULL && spec != Py_None) {
1360 package = _PyObject_GetAttrId(spec, &PyId_parent);
1361 if (package == NULL) {
1362 goto error;
1363 }
1364 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001365 _PyErr_SetString(tstate, PyExc_TypeError,
1366 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001367 goto error;
1368 }
1369 }
1370 else {
1371 if (PyErr_WarnEx(PyExc_ImportWarning,
1372 "can't resolve package from __spec__ or __package__, "
1373 "falling back on __name__ and __path__", 1) < 0) {
1374 goto error;
1375 }
1376
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001377 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001378 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001379 if (!_PyErr_Occurred(tstate)) {
1380 _PyErr_SetString(tstate, PyExc_KeyError,
1381 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001382 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001383 goto error;
1384 }
1385
1386 Py_INCREF(package);
1387 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001388 _PyErr_SetString(tstate, PyExc_TypeError,
1389 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001390 goto error;
1391 }
1392
Serhiy Storchakab510e102020-10-26 12:47:57 +02001393 int haspath = _PyDict_ContainsId(globals, &PyId___path__);
1394 if (haspath < 0) {
1395 goto error;
1396 }
1397 if (!haspath) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001398 Py_ssize_t dot;
1399
Serhiy Storchakab510e102020-10-26 12:47:57 +02001400 if (PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001401 goto error;
1402 }
1403
1404 dot = PyUnicode_FindChar(package, '.',
1405 0, PyUnicode_GET_LENGTH(package), -1);
1406 if (dot == -2) {
1407 goto error;
1408 }
Ben Lewis92420b32019-09-11 20:09:47 +10001409 else if (dot == -1) {
1410 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001411 }
Ben Lewis92420b32019-09-11 20:09:47 +10001412 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1413 if (substr == NULL) {
1414 goto error;
1415 }
1416 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001417 }
1418 }
1419
1420 last_dot = PyUnicode_GET_LENGTH(package);
1421 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001422 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001423 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001424
1425 for (level_up = 1; level_up < level; level_up += 1) {
1426 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1427 if (last_dot == -2) {
1428 goto error;
1429 }
1430 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001431 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001432 "attempted relative import beyond top-level "
1433 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001434 goto error;
1435 }
1436 }
1437
1438 base = PyUnicode_Substring(package, 0, last_dot);
1439 Py_DECREF(package);
1440 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1441 return base;
1442 }
1443
1444 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1445 Py_DECREF(base);
1446 return abs_name;
1447
Ben Lewis92420b32019-09-11 20:09:47 +10001448 no_parent_error:
1449 _PyErr_SetString(tstate, PyExc_ImportError,
1450 "attempted relative import "
1451 "with no known parent package");
1452
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001453 error:
1454 Py_XDECREF(package);
1455 return NULL;
1456}
1457
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001458static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001459import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001460{
1461 _Py_IDENTIFIER(_find_and_load);
1462 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001463 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001464 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001465 static int import_level;
1466 static _PyTime_t accumulated;
1467
1468 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1469
Steve Dowerb82e17e2019-05-23 08:45:22 -07001470 PyObject *sys_path = PySys_GetObject("path");
1471 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1472 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001473 if (_PySys_Audit(tstate, "import", "OOOOO",
1474 abs_name, Py_None, sys_path ? sys_path : Py_None,
1475 sys_meta_path ? sys_meta_path : Py_None,
1476 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001477 return NULL;
1478 }
1479
1480
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001481 /* XOptions is initialized after first some imports.
1482 * So we can't have negative cache before completed initialization.
1483 * Anyway, importlib._find_and_load is much slower than
1484 * _PyDict_GetItemIdWithError().
1485 */
1486 if (import_time) {
1487 static int header = 1;
1488 if (header) {
1489 fputs("import time: self [us] | cumulative | imported package\n",
1490 stderr);
1491 header = 0;
1492 }
1493
1494 import_level++;
1495 t1 = _PyTime_GetPerfCounter();
1496 accumulated = 0;
1497 }
1498
1499 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001500 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001501
1502 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1503 &PyId__find_and_load, abs_name,
1504 interp->import_func, NULL);
1505
1506 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001507 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001508 mod != NULL);
1509
1510 if (import_time) {
1511 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1512
1513 import_level--;
1514 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1515 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1516 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1517 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1518
1519 accumulated = accumulated_copy + cum;
1520 }
1521
1522 return mod;
1523}
1524
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001525PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001526PyImport_GetModule(PyObject *name)
1527{
1528 PyThreadState *tstate = _PyThreadState_GET();
1529 PyObject *mod;
1530
1531 mod = import_get_module(tstate, name);
1532 if (mod != NULL && mod != Py_None) {
1533 if (import_ensure_initialized(tstate, mod, name) < 0) {
1534 Py_DECREF(mod);
1535 remove_importlib_frames(tstate);
1536 return NULL;
1537 }
1538 }
1539 return mod;
1540}
1541
1542PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001543PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1544 PyObject *locals, PyObject *fromlist,
1545 int level)
1546{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001547 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001548 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001549 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001550 PyObject *final_mod = NULL;
1551 PyObject *mod = NULL;
1552 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001553 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001554 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001555
Brett Cannonfd074152012-04-14 14:10:13 -04001556 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001557 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001558 goto error;
1559 }
1560
1561 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1562 for added performance. */
1563
1564 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001565 _PyErr_SetString(tstate, PyExc_TypeError,
1566 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001567 goto error;
1568 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001569 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001570 goto error;
1571 }
1572 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001573 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001574 goto error;
1575 }
Brett Cannon849113a2016-01-22 15:25:50 -08001576
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001577 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001578 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001579 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001580 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001581 }
1582 else { /* level == 0 */
1583 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001584 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001585 goto error;
1586 }
Brett Cannonfd074152012-04-14 14:10:13 -04001587 abs_name = name;
1588 Py_INCREF(abs_name);
1589 }
1590
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001591 mod = import_get_module(tstate, abs_name);
1592 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001593 goto error;
1594 }
1595
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001596 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001597 if (import_ensure_initialized(tstate, mod, name) < 0) {
1598 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001599 }
Brett Cannonfd074152012-04-14 14:10:13 -04001600 }
1601 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001602 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001603 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001604 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001605 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001606 }
1607 }
1608
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001609 has_from = 0;
1610 if (fromlist != NULL && fromlist != Py_None) {
1611 has_from = PyObject_IsTrue(fromlist);
1612 if (has_from < 0)
1613 goto error;
1614 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001615 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001616 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1617 if (level == 0 || len > 0) {
1618 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001619
Victor Stinner744c34e2016-05-20 11:36:13 +02001620 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1621 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001622 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001623 }
1624
Victor Stinner744c34e2016-05-20 11:36:13 +02001625 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001626 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001627 final_mod = mod;
1628 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001629 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001630 }
1631
Brett Cannonfd074152012-04-14 14:10:13 -04001632 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001633 PyObject *front = PyUnicode_Substring(name, 0, dot);
1634 if (front == NULL) {
1635 goto error;
1636 }
1637
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001638 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001639 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001640 }
1641 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001642 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001643 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001644 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001645 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001646 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001647 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001648 }
Brett Cannonfd074152012-04-14 14:10:13 -04001649
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001650 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001651 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001652 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001653 if (!_PyErr_Occurred(tstate)) {
1654 _PyErr_Format(tstate, PyExc_KeyError,
1655 "%R not in sys.modules as expected",
1656 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001657 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001658 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001659 }
Brett Cannonfd074152012-04-14 14:10:13 -04001660 }
1661 }
1662 else {
1663 final_mod = mod;
1664 Py_INCREF(mod);
1665 }
1666 }
1667 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001668 PyObject *path;
1669 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1670 goto error;
1671 }
1672 if (path) {
1673 Py_DECREF(path);
1674 final_mod = _PyObject_CallMethodIdObjArgs(
1675 interp->importlib, &PyId__handle_fromlist,
1676 mod, fromlist, interp->import_func, NULL);
1677 }
1678 else {
1679 final_mod = mod;
1680 Py_INCREF(mod);
1681 }
Brett Cannonfd074152012-04-14 14:10:13 -04001682 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001683
Brett Cannonfd074152012-04-14 14:10:13 -04001684 error:
1685 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001686 Py_XDECREF(mod);
1687 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001688 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001689 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001690 }
Brett Cannonfd074152012-04-14 14:10:13 -04001691 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001692}
1693
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001694PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001695PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001696 PyObject *fromlist, int level)
1697{
1698 PyObject *nameobj, *mod;
1699 nameobj = PyUnicode_FromString(name);
1700 if (nameobj == NULL)
1701 return NULL;
1702 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1703 fromlist, level);
1704 Py_DECREF(nameobj);
1705 return mod;
1706}
1707
1708
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001709/* Re-import a module of any kind and return its module object, WITH
1710 INCREMENTED REFERENCE COUNT */
1711
Guido van Rossum79f25d91997-04-29 20:08:16 +00001712PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001713PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001714{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001715 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001716 _Py_IDENTIFIER(reload);
1717 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001718 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1719 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001720 if (PyErr_Occurred()) {
1721 return NULL;
1722 }
1723
Robert Rouhanif40bd462020-05-01 16:28:06 -07001724 importlib = PyImport_ImportModule("importlib");
1725 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001726 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001729
Robert Rouhanif40bd462020-05-01 16:28:06 -07001730 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1731 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001732 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001733}
1734
1735
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001736/* Higher-level import emulator which emulates the "import" statement
1737 more accurately -- it invokes the __import__() function from the
1738 builtins of the current globals. This means that the import is
1739 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001740 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001741 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001742 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001743 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001744
1745PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001746PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001747{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001748 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 static PyObject *silly_list = NULL;
1750 static PyObject *builtins_str = NULL;
1751 static PyObject *import_str = NULL;
1752 PyObject *globals = NULL;
1753 PyObject *import = NULL;
1754 PyObject *builtins = NULL;
1755 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 /* Initialize constant string objects */
1758 if (silly_list == NULL) {
1759 import_str = PyUnicode_InternFromString("__import__");
1760 if (import_str == NULL)
1761 return NULL;
1762 builtins_str = PyUnicode_InternFromString("__builtins__");
1763 if (builtins_str == NULL)
1764 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001765 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (silly_list == NULL)
1767 return NULL;
1768 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 /* Get the builtins from current globals */
1771 globals = PyEval_GetGlobals();
1772 if (globals != NULL) {
1773 Py_INCREF(globals);
1774 builtins = PyObject_GetItem(globals, builtins_str);
1775 if (builtins == NULL)
1776 goto err;
1777 }
1778 else {
1779 /* No globals -- use standard builtins, and fake globals */
1780 builtins = PyImport_ImportModuleLevel("builtins",
1781 NULL, NULL, NULL, 0);
1782 if (builtins == NULL)
1783 return NULL;
1784 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1785 if (globals == NULL)
1786 goto err;
1787 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 /* Get the __import__ function from the builtins */
1790 if (PyDict_Check(builtins)) {
1791 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001792 if (import == NULL) {
1793 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
1794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 }
1796 else
1797 import = PyObject_GetAttr(builtins, import_str);
1798 if (import == NULL)
1799 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001802 Always use absolute import here.
1803 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1805 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001806 if (r == NULL)
1807 goto err;
1808 Py_DECREF(r);
1809
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001810 r = import_get_module(tstate, module_name);
1811 if (r == NULL && !_PyErr_Occurred(tstate)) {
1812 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001813 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001814
1815 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 Py_XDECREF(globals);
1817 Py_XDECREF(builtins);
1818 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001821}
1822
Brett Cannon4caa61d2014-01-09 19:03:32 -05001823/*[clinic input]
1824_imp.extension_suffixes
1825
1826Returns the list of file suffixes used to identify extension modules.
1827[clinic start generated code]*/
1828
Brett Cannon4caa61d2014-01-09 19:03:32 -05001829static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001830_imp_extension_suffixes_impl(PyObject *module)
1831/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 list = PyList_New(0);
1836 if (list == NULL)
1837 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001838#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01001839 const char *suffix;
1840 unsigned int index = 0;
1841
Brett Cannon2657df42012-05-04 15:20:40 -04001842 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1843 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (item == NULL) {
1845 Py_DECREF(list);
1846 return NULL;
1847 }
1848 if (PyList_Append(list, item) < 0) {
1849 Py_DECREF(list);
1850 Py_DECREF(item);
1851 return NULL;
1852 }
1853 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001854 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 }
Brett Cannon2657df42012-05-04 15:20:40 -04001856#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001858}
1859
Brett Cannon4caa61d2014-01-09 19:03:32 -05001860/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001861_imp.init_frozen
1862
1863 name: unicode
1864 /
1865
1866Initializes a frozen module.
1867[clinic start generated code]*/
1868
Brett Cannon4caa61d2014-01-09 19:03:32 -05001869static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001870_imp_init_frozen_impl(PyObject *module, PyObject *name)
1871/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001872{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001873 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 int ret;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001875
Victor Stinner53dc7352011-03-20 01:50:21 +01001876 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (ret < 0)
1878 return NULL;
1879 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001880 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 }
Serhiy Storchaka4db89882021-01-12 16:43:32 +02001882 return import_add_module(tstate, name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001883}
1884
Brett Cannon4caa61d2014-01-09 19:03:32 -05001885/*[clinic input]
1886_imp.get_frozen_object
1887
1888 name: unicode
1889 /
1890
1891Create a code object for a frozen module.
1892[clinic start generated code]*/
1893
Brett Cannon4caa61d2014-01-09 19:03:32 -05001894static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001895_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1896/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001899}
1900
Brett Cannon4caa61d2014-01-09 19:03:32 -05001901/*[clinic input]
1902_imp.is_frozen_package
1903
1904 name: unicode
1905 /
1906
1907Returns True if the module name is of a frozen package.
1908[clinic start generated code]*/
1909
Brett Cannon4caa61d2014-01-09 19:03:32 -05001910static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001911_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1912/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001915}
1916
Brett Cannon4caa61d2014-01-09 19:03:32 -05001917/*[clinic input]
1918_imp.is_builtin
1919
1920 name: unicode
1921 /
1922
1923Returns True if the module name corresponds to a built-in module.
1924[clinic start generated code]*/
1925
Guido van Rossum79f25d91997-04-29 20:08:16 +00001926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001927_imp_is_builtin_impl(PyObject *module, PyObject *name)
1928/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001929{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001930 return PyLong_FromLong(is_builtin(name));
1931}
1932
1933/*[clinic input]
1934_imp.is_frozen
1935
1936 name: unicode
1937 /
1938
1939Returns True if the module name corresponds to a frozen module.
1940[clinic start generated code]*/
1941
Brett Cannon4caa61d2014-01-09 19:03:32 -05001942static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001943_imp_is_frozen_impl(PyObject *module, PyObject *name)
1944/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001945{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001946 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 p = find_frozen(name);
1949 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001950}
1951
Larry Hastings1df0b352015-08-24 19:53:56 -07001952/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1953static int
1954exec_builtin_or_dynamic(PyObject *mod) {
1955 PyModuleDef *def;
1956 void *state;
1957
1958 if (!PyModule_Check(mod)) {
1959 return 0;
1960 }
1961
1962 def = PyModule_GetDef(mod);
1963 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001964 return 0;
1965 }
Brett Cannon52794db2016-09-07 17:00:43 -07001966
Larry Hastings1df0b352015-08-24 19:53:56 -07001967 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001968 if (state) {
1969 /* Already initialized; skip reload */
1970 return 0;
1971 }
Brett Cannon52794db2016-09-07 17:00:43 -07001972
Larry Hastings1df0b352015-08-24 19:53:56 -07001973 return PyModule_ExecDef(mod, def);
1974}
1975
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001976#ifdef HAVE_DYNAMIC_LOADING
1977
Brett Cannon4caa61d2014-01-09 19:03:32 -05001978/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10001979_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05001980
Nick Coghland5cacbb2015-05-23 22:24:10 +10001981 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05001982 file: object = NULL
1983 /
1984
Nick Coghland5cacbb2015-05-23 22:24:10 +10001985Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05001986[clinic start generated code]*/
1987
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001989_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
1990/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001991{
Nick Coghland5cacbb2015-05-23 22:24:10 +10001992 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001993 FILE *fp;
1994
Nick Coghland5cacbb2015-05-23 22:24:10 +10001995 name = PyObject_GetAttrString(spec, "name");
1996 if (name == NULL) {
1997 return NULL;
1998 }
1999
2000 path = PyObject_GetAttrString(spec, "origin");
2001 if (path == NULL) {
2002 Py_DECREF(name);
2003 return NULL;
2004 }
2005
Serhiy Storchaka4db89882021-01-12 16:43:32 +02002006 PyThreadState *tstate = _PyThreadState_GET();
2007 mod = import_find_extension(tstate, name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002008 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002009 Py_DECREF(name);
2010 Py_DECREF(path);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002011 return mod;
2012 }
2013
Brett Cannon4caa61d2014-01-09 19:03:32 -05002014 if (file != NULL) {
2015 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002016 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002017 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002018 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002020 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002022 else
2023 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002024
2025 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2026
2027 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002028 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (fp)
2030 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002031 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002032}
2033
Nick Coghland5cacbb2015-05-23 22:24:10 +10002034/*[clinic input]
2035_imp.exec_dynamic -> int
2036
2037 mod: object
2038 /
2039
2040Initialize an extension module.
2041[clinic start generated code]*/
2042
2043static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002044_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2045/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002046{
Larry Hastings1df0b352015-08-24 19:53:56 -07002047 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002048}
2049
2050
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002051#endif /* HAVE_DYNAMIC_LOADING */
2052
Larry Hastings7726ac92014-01-31 22:03:12 -08002053/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002054_imp.exec_builtin -> int
2055
2056 mod: object
2057 /
2058
2059Initialize a built-in module.
2060[clinic start generated code]*/
2061
2062static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002063_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2064/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002065{
2066 return exec_builtin_or_dynamic(mod);
2067}
2068
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002069/*[clinic input]
2070_imp.source_hash
2071
2072 key: long
2073 source: Py_buffer
2074[clinic start generated code]*/
2075
2076static PyObject *
2077_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2078/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2079{
Benjamin Peterson83620772017-12-09 12:18:56 -08002080 union {
2081 uint64_t x;
2082 char data[sizeof(uint64_t)];
2083 } hash;
2084 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002085#if !PY_LITTLE_ENDIAN
2086 // Force to little-endian. There really ought to be a succinct standard way
2087 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002088 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2089 char tmp = hash.data[i];
2090 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2091 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002092 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002093#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002094 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002095}
2096
Barry Warsaw28a691b2010-04-17 00:19:56 +00002097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002098PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002099"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002100
Guido van Rossum79f25d91997-04-29 20:08:16 +00002101static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002102 _IMP_EXTENSION_SUFFIXES_METHODDEF
2103 _IMP_LOCK_HELD_METHODDEF
2104 _IMP_ACQUIRE_LOCK_METHODDEF
2105 _IMP_RELEASE_LOCK_METHODDEF
2106 _IMP_GET_FROZEN_OBJECT_METHODDEF
2107 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002108 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002109 _IMP_INIT_FROZEN_METHODDEF
2110 _IMP_IS_BUILTIN_METHODDEF
2111 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002112 _IMP_CREATE_DYNAMIC_METHODDEF
2113 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002114 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002115 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002116 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002117 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002118};
2119
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002120
Victor Stinner62230712020-11-18 23:18:29 +01002121static int
2122imp_module_exec(PyObject *module)
2123{
2124 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
2125 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
2126 if (pyc_mode == NULL) {
2127 return -1;
2128 }
2129 if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
2130 Py_DECREF(pyc_mode);
2131 return -1;
2132 }
2133 Py_DECREF(pyc_mode);
2134
2135 return 0;
2136}
2137
2138
2139static PyModuleDef_Slot imp_slots[] = {
2140 {Py_mod_exec, imp_module_exec},
2141 {0, NULL}
2142};
2143
2144static struct PyModuleDef imp_module = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyModuleDef_HEAD_INIT,
Victor Stinner62230712020-11-18 23:18:29 +01002146 .m_name = "_imp",
2147 .m_doc = doc_imp,
2148 .m_size = 0,
2149 .m_methods = imp_methods,
2150 .m_slots = imp_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00002151};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002152
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002153PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002154PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002155{
Victor Stinner62230712020-11-18 23:18:29 +01002156 return PyModuleDef_Init(&imp_module);
2157}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002158
Victor Stinner62230712020-11-18 23:18:29 +01002159
2160// Import the _imp extension by calling manually _imp.create_builtin() and
2161// _imp.exec_builtin() since importlib is not initialized yet. Initializing
2162// importlib requires the _imp module: this function fix the bootstrap issue.
2163PyObject*
2164_PyImport_BootstrapImp(PyThreadState *tstate)
2165{
2166 PyObject *name = PyUnicode_FromString("_imp");
2167 if (name == NULL) {
2168 return NULL;
Victor Stinner410b85a2019-05-13 17:12:45 +02002169 }
2170
Victor Stinner62230712020-11-18 23:18:29 +01002171 // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
2172 // an object with just a name attribute.
2173 //
2174 // _imp.__spec__ is overriden by importlib._bootstrap._instal() anyway.
2175 PyObject *attrs = Py_BuildValue("{sO}", "name", name);
2176 if (attrs == NULL) {
2177 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002178 }
Victor Stinner62230712020-11-18 23:18:29 +01002179 PyObject *spec = _PyNamespace_New(attrs);
2180 Py_DECREF(attrs);
2181 if (spec == NULL) {
2182 goto error;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002183 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002184
Victor Stinner62230712020-11-18 23:18:29 +01002185 // Create the _imp module from its definition.
2186 PyObject *mod = create_builtin(tstate, name, spec);
2187 Py_CLEAR(name);
2188 Py_DECREF(spec);
2189 if (mod == NULL) {
2190 goto error;
2191 }
2192 assert(mod != Py_None); // not found
2193
2194 // Execute the _imp module: call imp_module_exec().
2195 if (exec_builtin_or_dynamic(mod) < 0) {
2196 Py_DECREF(mod);
2197 goto error;
2198 }
2199 return mod;
2200
2201error:
2202 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002204}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002205
2206
Guido van Rossumb18618d2000-05-03 23:44:39 +00002207/* API for embedding applications that want to add their own entries
2208 to the table of built-in modules. This should normally be called
2209 *before* Py_Initialize(). When the table resize fails, -1 is
2210 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002211
2212 After a similar function by Just van Rossum. */
2213
2214int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002215PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002218 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002219 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 /* Count the number of entries in both tables */
2222 for (n = 0; newtab[n].name != NULL; n++)
2223 ;
2224 if (n == 0)
2225 return 0; /* Nothing to do */
2226 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2227 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002228
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002229 /* Force default raw memory allocator to get a known allocator to be able
2230 to release the memory in _PyImport_Fini2() */
2231 PyMemAllocatorEx old_alloc;
2232 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002235 p = NULL;
2236 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002237 size_t size = sizeof(struct _inittab) * (i + n + 1);
2238 p = PyMem_RawRealloc(inittab_copy, size);
2239 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002240 if (p == NULL) {
2241 res = -1;
2242 goto done;
2243 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002244
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002245 /* Copy the tables into the new memory at the first call
2246 to PyImport_ExtendInittab(). */
2247 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002249 }
2250 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2251 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002252
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002253done:
2254 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2255 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002256}
2257
2258/* Shorthand to add a single entry given a name and a function */
2259
2260int
Brett Cannona826f322009-04-02 03:41:46 +00002261PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002266
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002267 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002271}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002272
2273#ifdef __cplusplus
2274}
2275#endif