blob: 51630c3486af6196213adad132f0e08a09d55beb [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 Stinner61691d82019-10-02 23:51:20 +02007#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02008#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pyhash.h"
10#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020011#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020012#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
13#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010014#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000018#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020019#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000020
Guido van Rossum55a83382000-09-20 20:31:38 +000021#ifdef HAVE_FCNTL_H
22#include <fcntl.h>
23#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000025extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000027
Barry Warsaw28a691b2010-04-17 00:19:56 +000028#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000029
Victor Stinner0a28f8d2019-06-19 02:54:39 +020030/* Forward references */
31static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
32
Victor Stinner95872862011-03-07 18:20:56 +010033/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000034static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000035
Guido van Rossum771c6c81997-10-31 18:37:24 +000036/* This table is defined in config.c: */
37extern struct _inittab _PyImport_Inittab[];
38
39struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010040static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000041
Hai Shi46874c22020-01-30 17:20:25 -060042_Py_IDENTIFIER(__path__);
43_Py_IDENTIFIER(__spec__);
44
Brett Cannon4caa61d2014-01-09 19:03:32 -050045/*[clinic input]
46module _imp
47[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030048/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040049
50#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050051
Guido van Rossum1ae940a1995-01-02 19:04:15 +000052/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053
Victor Stinner331a6a52019-05-27 16:39:22 +020054PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020055_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040056{
ukwksk5e6312c2018-05-15 04:10:52 +090057 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040058 int err = 0;
59
60 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020061 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020062 _PyErr_SetString(tstate, PyExc_RuntimeError,
63 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040064 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020065 }
Brett Cannonfd074152012-04-14 14:10:13 -040066
Victor Stinnerda7933e2020-04-13 03:04:28 +020067 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +020068 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -040069 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020070 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071
ukwksk5e6312c2018-05-15 04:10:52 +090072 zipimport = PyImport_ImportModule("zipimport");
73 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020074 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020075 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +020077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 }
79 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020080 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090081 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020082 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +090083 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020085 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +020086 if (verbose) {
87 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
88 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 }
90 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -040091 /* sys.path_hooks.insert(0, zipimporter) */
92 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -040094 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -040096 }
Victor Stinner410b85a2019-05-13 17:12:45 +020097 if (verbose) {
98 PySys_WriteStderr("# installed zipimport hook\n");
99 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 }
101 }
Brett Cannonfd074152012-04-14 14:10:13 -0400102
Victor Stinner331a6a52019-05-27 16:39:22 +0200103 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400104
105 error:
106 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200107 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000108}
109
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000110/* Locking primitives to prevent parallel imports of the same module
111 in different threads to return with a partially loaded module.
112 These calls are serialized by the global interpreter lock. */
113
Victor Stinner26881c82020-06-02 15:51:37 +0200114static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200115static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000116static int import_lock_level = 0;
117
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000118void
119_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000120{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200121 unsigned long me = PyThread_get_thread_ident();
122 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 return; /* Too bad */
124 if (import_lock == NULL) {
125 import_lock = PyThread_allocate_lock();
126 if (import_lock == NULL)
127 return; /* Nothing much we can do. */
128 }
129 if (import_lock_thread == me) {
130 import_lock_level++;
131 return;
132 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200133 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
134 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {
136 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200137 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 PyEval_RestoreThread(tstate);
139 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100140 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 import_lock_thread = me;
142 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000143}
144
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000145int
146_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200148 unsigned long me = PyThread_get_thread_ident();
149 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 return 0; /* Too bad */
151 if (import_lock_thread != me)
152 return -1;
153 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100154 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200156 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyThread_release_lock(import_lock);
158 }
159 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000160}
161
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900162#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200163/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000164 created child processes do not share locks with the parent.
165 We now acquire the import lock around fork() calls but on some platforms
166 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200167PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000168_PyImport_ReInitLock(void)
169{
Christian Heimes418fd742015-04-19 21:08:42 +0200170 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900171 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200172 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200173 }
174 }
Victor Stinner26881c82020-06-02 15:51:37 +0200175
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000176 if (import_lock_level > 1) {
177 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200178 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200179 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000180 import_lock_thread = me;
181 import_lock_level--;
182 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200183 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000184 import_lock_level = 0;
185 }
Victor Stinner26881c82020-06-02 15:51:37 +0200186 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000187}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900188#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000189
Brett Cannon4caa61d2014-01-09 19:03:32 -0500190/*[clinic input]
191_imp.lock_held
192
193Return True if the import lock is currently held, else False.
194
195On platforms without threads, return False.
196[clinic start generated code]*/
197
Brett Cannon4caa61d2014-01-09 19:03:32 -0500198static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300199_imp_lock_held_impl(PyObject *module)
200/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000201{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200202 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000203}
204
Brett Cannon4caa61d2014-01-09 19:03:32 -0500205/*[clinic input]
206_imp.acquire_lock
207
208Acquires the interpreter's import lock for the current thread.
209
210This lock should be used by import hooks to ensure thread-safety when importing
211modules. On platforms without threads, this function does nothing.
212[clinic start generated code]*/
213
Brett Cannon4caa61d2014-01-09 19:03:32 -0500214static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300215_imp_acquire_lock_impl(PyObject *module)
216/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200219 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000220}
221
Brett Cannon4caa61d2014-01-09 19:03:32 -0500222/*[clinic input]
223_imp.release_lock
224
225Release the interpreter's import lock.
226
227On platforms without threads, this function does nothing.
228[clinic start generated code]*/
229
Brett Cannon4caa61d2014-01-09 19:03:32 -0500230static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300231_imp_release_lock_impl(PyObject *module)
232/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (_PyImport_ReleaseLock() < 0) {
235 PyErr_SetString(PyExc_RuntimeError,
236 "not holding the import lock");
237 return NULL;
238 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200239 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000240}
241
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100242void
243_PyImport_Fini(void)
244{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200245 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100246 if (import_lock != NULL) {
247 PyThread_free_lock(import_lock);
248 import_lock = NULL;
249 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100250}
251
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100252void
253_PyImport_Fini2(void)
254{
255 /* Use the same memory allocator than PyImport_ExtendInittab(). */
256 PyMemAllocatorEx old_alloc;
257 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
258
259 /* Free memory allocated by PyImport_ExtendInittab() */
260 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700261 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100262
263 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
264}
265
Guido van Rossum25ce5661997-08-02 03:10:38 +0000266/* Helper for sys */
267
268PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000269PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000270{
Victor Stinner81a7be32020-04-14 15:14:01 +0200271 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600272 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100273 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600274 }
Eric Snow93c92f72017-09-13 23:46:04 -0700275 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000276}
277
Eric Snowd393c1b2017-09-14 12:18:12 -0600278/* In some corner cases it is important to be sure that the import
279 machinery has been initialized (or not cleaned up yet). For
280 example, see issue #4236 and PyModule_Create2(). */
281
282int
283_PyImport_IsInitialized(PyInterpreterState *interp)
284{
285 if (interp->modules == NULL)
286 return 0;
287 return 1;
288}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000289
Eric Snow3f9eee62017-09-15 16:35:20 -0600290PyObject *
291_PyImport_GetModuleId(struct _Py_Identifier *nameid)
292{
293 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
294 if (name == NULL) {
295 return NULL;
296 }
297 return PyImport_GetModule(name);
298}
299
300int
301_PyImport_SetModule(PyObject *name, PyObject *m)
302{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200303 PyThreadState *tstate = _PyThreadState_GET();
304 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600305 return PyObject_SetItem(modules, name, m);
306}
307
308int
309_PyImport_SetModuleString(const char *name, PyObject *m)
310{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200311 PyThreadState *tstate = _PyThreadState_GET();
312 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600313 return PyMapping_SetItemString(modules, name, m);
314}
315
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200316static PyObject *
317import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600318{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200319 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600320 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200321 _PyErr_SetString(tstate, PyExc_RuntimeError,
322 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600323 return NULL;
324 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200325
326 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600327 Py_INCREF(modules);
328 if (PyDict_CheckExact(modules)) {
329 m = PyDict_GetItemWithError(modules, name); /* borrowed */
330 Py_XINCREF(m);
331 }
332 else {
333 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200334 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
335 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600336 }
337 }
338 Py_DECREF(modules);
339 return m;
340}
341
342
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100343static int
344import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200345{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100346 PyInterpreterState *interp = tstate->interp;
347 PyObject *spec;
348
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100349 _Py_IDENTIFIER(_lock_unlock_module);
350
351 /* Optimization: only call _bootstrap._lock_unlock_module() if
352 __spec__._initializing is true.
353 NOTE: because of this, initializing must be set *before*
354 stuffing the new module in sys.modules.
355 */
356 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
357 int busy = _PyModuleSpec_IsInitializing(spec);
358 Py_XDECREF(spec);
359 if (busy) {
360 /* Wait until module is done importing. */
361 PyObject *value = _PyObject_CallMethodIdOneArg(
362 interp->importlib, &PyId__lock_unlock_module, name);
363 if (value == NULL) {
364 return -1;
365 }
366 Py_DECREF(value);
367 }
368 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200369}
370
371
Barry Warsaw28a691b2010-04-17 00:19:56 +0000372/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000373
374long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000376{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200377 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200378 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600379 PyObject *external, *pyc_magic;
380
381 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
382 if (external == NULL)
383 return -1;
384 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
385 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400386 if (pyc_magic == NULL)
387 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200388 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700389 Py_DECREF(pyc_magic);
390 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000391}
392
393
Brett Cannon3adc7b72012-07-09 14:22:12 -0400394extern const char * _PySys_ImplCacheTag;
395
Barry Warsaw28a691b2010-04-17 00:19:56 +0000396const char *
397PyImport_GetMagicTag(void)
398{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400399 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000400}
401
Brett Cannon98979b82012-07-02 15:13:11 -0400402
Guido van Rossum25ce5661997-08-02 03:10:38 +0000403/* Magic for extension modules (built-in as well as dynamically
404 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200405 once, we keep a static dictionary 'extensions' keyed by the tuple
406 (module name, module name) (for built-in modules) or by
407 (filename, module name) (for dynamically loaded modules), containing these
408 modules. A copy of the module's dictionary is stored by calling
409 _PyImport_FixupExtensionObject() immediately after the module initialization
410 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100411 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000412
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000413 Modules which do support multiple initialization set their m_size
414 field to a non-negative number (indicating the size of the
415 module-specific state). They are still recorded in the extensions
416 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000417*/
418
419int
Victor Stinner95872862011-03-07 18:20:56 +0100420_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200421 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (mod == NULL || !PyModule_Check(mod)) {
424 PyErr_BadInternalCall();
425 return -1;
426 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100427
428 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (!def) {
430 PyErr_BadInternalCall();
431 return -1;
432 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100433
434 PyThreadState *tstate = _PyThreadState_GET();
435 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100437 }
438 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600439 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 return -1;
441 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100442
443 if (_Py_IsMainInterpreter(tstate)) {
444 if (def->m_size == -1) {
445 if (def->m_base.m_copy) {
446 /* Somebody already imported the module,
447 likely under a different name.
448 XXX this should really not happen. */
449 Py_CLEAR(def->m_base.m_copy);
450 }
451 PyObject *dict = PyModule_GetDict(mod);
452 if (dict == NULL) {
453 return -1;
454 }
455 def->m_base.m_copy = PyDict_Copy(dict);
456 if (def->m_base.m_copy == NULL) {
457 return -1;
458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100460
461 if (extensions == NULL) {
462 extensions = PyDict_New();
463 if (extensions == NULL) {
464 return -1;
465 }
466 }
467
468 PyObject *key = PyTuple_Pack(2, filename, name);
469 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100471 }
472 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
473 Py_DECREF(key);
474 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000480}
481
Victor Stinner49d3f252010-10-17 01:24:53 +0000482int
Eric Snowd393c1b2017-09-14 12:18:12 -0600483_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000484{
485 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100486 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100487 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100488 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000489 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600490 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100491 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000492 return res;
493}
494
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200495static PyObject *
496import_find_extension(PyThreadState *tstate, PyObject *name,
497 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200499 if (extensions == NULL) {
500 return NULL;
501 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600502
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200503 PyObject *key = PyTuple_Pack(2, filename, name);
504 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200506 }
507 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500508 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200509 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200511 }
512
513 PyObject *mod, *mdict;
514 PyObject *modules = tstate->interp->modules;
515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (def->m_size == -1) {
517 /* Module does not support repeated initialization */
518 if (def->m_base.m_copy == NULL)
519 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200520 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (mod == NULL)
522 return NULL;
523 mdict = PyModule_GetDict(mod);
524 if (mdict == NULL)
525 return NULL;
526 if (PyDict_Update(mdict, def->m_base.m_copy))
527 return NULL;
528 }
529 else {
530 if (def->m_base.m_init == NULL)
531 return NULL;
532 mod = def->m_base.m_init();
533 if (mod == NULL)
534 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600535 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200536 Py_DECREF(mod);
537 return NULL;
538 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 Py_DECREF(mod);
540 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100541 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600542 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 return NULL;
544 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200545
Victor Stinnerda7933e2020-04-13 03:04:28 +0200546 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200547 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100548 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200549 name, filename);
550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000552}
553
Victor Stinner49d3f252010-10-17 01:24:53 +0000554PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200555_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
556{
557 PyThreadState *tstate = _PyThreadState_GET();
558 return import_find_extension(tstate, name, filename);
559}
560
561
562PyObject *
563_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000564{
Victor Stinner95872862011-03-07 18:20:56 +0100565 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100566 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100567 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000568 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200569 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100570 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000571 return res;
572}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573
574/* Get the module object corresponding to a module name.
575 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000576 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000577 Because the former action is most common, THIS DOES NOT RETURN A
578 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000579
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200580static PyObject *
581import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000582{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200583 PyObject *modules = tstate->interp->modules;
584 if (modules == NULL) {
585 _PyErr_SetString(tstate, PyExc_RuntimeError,
586 "no import module dictionary");
587 return NULL;
588 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600589
Eric Snow86b7afd2017-09-04 17:54:09 -0600590 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600591 if (PyDict_CheckExact(modules)) {
592 m = PyDict_GetItemWithError(modules, name);
593 }
594 else {
595 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000596 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600597 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200598 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
599 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600600 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200601 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200602 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200603 return NULL;
604 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600605 if (m != NULL && PyModule_Check(m)) {
606 return m;
607 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000608 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (m == NULL)
610 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600611 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 Py_DECREF(m);
613 return NULL;
614 }
615 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000618}
619
Victor Stinner27ee0892011-03-04 12:57:09 +0000620PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200621PyImport_AddModuleObject(PyObject *name)
622{
623 PyThreadState *tstate = _PyThreadState_GET();
624 return import_add_module(tstate, name);
625}
626
627
628PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000629PyImport_AddModule(const char *name)
630{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200631 PyObject *nameobj = PyUnicode_FromString(name);
632 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000633 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200634 }
635 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000636 Py_DECREF(nameobj);
637 return module;
638}
639
640
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300641/* Remove name from sys.modules, if it's there.
642 * Can be called with an exception raised.
643 * If fail to remove name a new exception will be chained with the old
644 * exception, otherwise the old exception is preserved.
645 */
Tim Peters1cd70172004-08-02 03:52:12 +0000646static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200647remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000648{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600649 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200650 _PyErr_Fetch(tstate, &type, &value, &traceback);
651
652 PyObject *modules = tstate->interp->modules;
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300653 if (PyDict_CheckExact(modules)) {
654 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
655 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600656 }
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300657 else if (PyMapping_DelItem(modules, name) < 0) {
658 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
659 _PyErr_Clear(tstate);
660 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600661 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200662
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300663 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000664}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000665
Christian Heimes3b06e532008-01-07 20:12:44 +0000666
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000667/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000668 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
669 * removed from sys.modules, to avoid leaving damaged module objects
670 * in sys.modules. The caller may wish to restore the original
671 * module object (if any) in this case; PyImport_ReloadModule is an
672 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000673 *
674 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
675 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000676 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000677PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300678PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return PyImport_ExecCodeModuleWithPathnames(
681 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000682}
683
684PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300685PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return PyImport_ExecCodeModuleWithPathnames(
688 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000689}
690
691PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300692PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
693 const char *pathname,
694 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000695{
Victor Stinner27ee0892011-03-04 12:57:09 +0000696 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600697 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000698
699 nameobj = PyUnicode_FromString(name);
700 if (nameobj == NULL)
701 return NULL;
702
Victor Stinner27ee0892011-03-04 12:57:09 +0000703 if (cpathname != NULL) {
704 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
705 if (cpathobj == NULL)
706 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400707 }
708 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000709 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400710
711 if (pathname != NULL) {
712 pathobj = PyUnicode_DecodeFSDefault(pathname);
713 if (pathobj == NULL)
714 goto error;
715 }
716 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200717 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400718 _Py_IDENTIFIER(_get_sourcefile);
719
720 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100721 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400722 }
723
Eric Snow32439d62015-05-02 19:15:18 -0600724 external= PyObject_GetAttrString(interp->importlib,
725 "_bootstrap_external");
726 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200727 pathobj = _PyObject_CallMethodIdOneArg(
728 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600729 Py_DECREF(external);
730 }
Brett Cannona6473f92012-07-13 13:57:03 -0400731 if (pathobj == NULL)
732 PyErr_Clear();
733 }
734 else
735 pathobj = NULL;
736
Victor Stinner27ee0892011-03-04 12:57:09 +0000737 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
738error:
739 Py_DECREF(nameobj);
740 Py_XDECREF(pathobj);
741 Py_XDECREF(cpathobj);
742 return m;
743}
744
Brett Cannon18fc4e72014-04-04 10:01:46 -0400745static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200746module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000747{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200748 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400749 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000750
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200751 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (m == NULL)
753 return NULL;
754 /* If the module is being reloaded, we get the old module back
755 and re-use its dict to exec the new code. */
756 d = PyModule_GetDict(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200757 int r = _PyDict_ContainsId(d, &PyId___builtins__);
758 if (r == 0) {
759 r = _PyDict_SetItemId(d, &PyId___builtins__,
760 PyEval_GetBuiltins());
761 }
762 if (r < 0) {
763 remove_module(tstate, name);
764 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400766
Eric Snow08197a42014-05-12 17:54:55 -0600767 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400768}
769
770static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200771exec_code_in_module(PyThreadState *tstate, PyObject *name,
772 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -0400773{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400774 PyObject *v, *m;
775
776 v = PyEval_EvalCode(code_object, module_dict, module_dict);
777 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200778 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400779 return NULL;
780 }
781 Py_DECREF(v);
782
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200783 m = import_get_module(tstate, name);
784 if (m == NULL && !_PyErr_Occurred(tstate)) {
785 _PyErr_Format(tstate, PyExc_ImportError,
786 "Loaded module %R not found in sys.modules",
787 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400788 }
789
Brett Cannon18fc4e72014-04-04 10:01:46 -0400790 return m;
791}
792
793PyObject*
794PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
795 PyObject *cpathname)
796{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200797 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600798 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600799 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400800
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200801 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400802 if (d == NULL) {
803 return NULL;
804 }
805
Eric Snow08197a42014-05-12 17:54:55 -0600806 if (pathname == NULL) {
807 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200809 external = PyObject_GetAttrString(tstate->interp->importlib,
810 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -0600811 if (external == NULL)
812 return NULL;
813 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 }
Eric Snow08197a42014-05-12 17:54:55 -0600821 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000822}
823
824
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000825static void
826update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyObject *constants, *tmp;
829 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (PyUnicode_Compare(co->co_filename, oldname))
832 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000833
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200834 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300835 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 constants = co->co_consts;
838 n = PyTuple_GET_SIZE(constants);
839 for (i = 0; i < n; i++) {
840 tmp = PyTuple_GET_ITEM(constants, i);
841 if (PyCode_Check(tmp))
842 update_code_filenames((PyCodeObject *)tmp,
843 oldname, newname);
844 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000845}
846
Victor Stinner2f42ae52011-03-20 00:41:24 +0100847static void
848update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000849{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100850 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000851
Victor Stinner2f42ae52011-03-20 00:41:24 +0100852 if (PyUnicode_Compare(co->co_filename, newname) == 0)
853 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 oldname = co->co_filename;
856 Py_INCREF(oldname);
857 update_code_filenames(co, oldname, newname);
858 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000859}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000860
Brett Cannon4caa61d2014-01-09 19:03:32 -0500861/*[clinic input]
862_imp._fix_co_filename
863
864 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
865 Code object to change.
866
867 path: unicode
868 File path to use.
869 /
870
871Changes code.co_filename to specify the passed-in file path.
872[clinic start generated code]*/
873
Brett Cannon4caa61d2014-01-09 19:03:32 -0500874static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300875_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400876 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300877/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700878
Brett Cannon4caa61d2014-01-09 19:03:32 -0500879{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500880 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700881
882 Py_RETURN_NONE;
883}
884
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000886/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700887static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000888
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000889
890/* Helper to test for built-in module */
891
892static int
Victor Stinner95872862011-03-07 18:20:56 +0100893is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000894{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200895 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200897 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (PyImport_Inittab[i].initfunc == NULL)
899 return -1;
900 else
901 return 1;
902 }
903 }
904 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000905}
906
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000907
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700908/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000909 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000910 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000911 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700912 this tells our caller that the path based finder could not find
913 a finder for this path item. Cache the result in
914 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +0000915 Returns a borrowed reference. */
916
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);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200933 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* set path_importer_cache[p] to None to avoid recursion */
937 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
938 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 for (j = 0; j < nhooks; j++) {
941 PyObject *hook = PyList_GetItem(path_hooks, j);
942 if (hook == NULL)
943 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +0100944 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (importer != NULL)
946 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000947
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200948 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return NULL;
950 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200951 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
953 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400954 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 }
956 if (importer != NULL) {
957 int err = PyDict_SetItem(path_importer_cache, p, importer);
958 Py_DECREF(importer);
959 if (err != 0)
960 return NULL;
961 }
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();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +0000970
Victor Stinner1e53bba2013-07-16 22:26:05 +0200971 path_importer_cache = PySys_GetObject("path_importer_cache");
972 path_hooks = PySys_GetObject("path_hooks");
973 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200974 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +0200975 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 }
977 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
978 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +0000979}
980
Nick Coghland5cacbb2015-05-23 22:24:10 +1000981/*[clinic input]
982_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000983
Nick Coghland5cacbb2015-05-23 22:24:10 +1000984 spec: object
985 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000986
Nick Coghland5cacbb2015-05-23 22:24:10 +1000987Create an extension module.
988[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000989
Nick Coghland5cacbb2015-05-23 22:24:10 +1000990static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300991_imp_create_builtin(PyObject *module, PyObject *spec)
992/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000993{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200994 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000996 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200997 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +0100998 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000999
Nick Coghland5cacbb2015-05-23 22:24:10 +10001000 name = PyObject_GetAttrString(spec, "name");
1001 if (name == NULL) {
1002 return NULL;
1003 }
1004
Victor Stinner5eb4f592013-11-14 22:38:52 +01001005 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001006 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001007 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001008 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001009 return mod;
1010 }
1011
1012 namestr = PyUnicode_AsUTF8(name);
1013 if (namestr == NULL) {
1014 Py_DECREF(name);
1015 return NULL;
1016 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001017
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001018 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001020 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001021 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001023 /* Cannot re-init internal module ("sys" or "builtins") */
1024 mod = PyImport_AddModule(namestr);
1025 Py_DECREF(name);
1026 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001029 if (mod == NULL) {
1030 Py_DECREF(name);
1031 return NULL;
1032 }
1033 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1034 Py_DECREF(name);
1035 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1036 } else {
1037 /* Remember pointer to module init function. */
1038 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001039 if (def == NULL) {
1040 Py_DECREF(name);
1041 return NULL;
1042 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001043 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001044 if (_PyImport_FixupExtensionObject(mod, name, name,
1045 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001046 Py_DECREF(name);
1047 return NULL;
1048 }
1049 Py_DECREF(name);
1050 return mod;
1051 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 }
1053 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001054 Py_DECREF(name);
1055 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001056}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001057
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001058
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001059/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001060
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001061static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001062find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001063{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001064 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001065
Victor Stinner53dc7352011-03-20 01:50:21 +01001066 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 for (p = PyImport_FrozenModules; ; p++) {
1070 if (p->name == NULL)
1071 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001072 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 break;
1074 }
1075 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001076}
1077
Guido van Rossum79f25d91997-04-29 20:08:16 +00001078static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001079get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001080{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001081 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (p == NULL) {
1085 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001086 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 name);
1088 return NULL;
1089 }
1090 if (p->code == NULL) {
1091 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001092 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 name);
1094 return NULL;
1095 }
1096 size = p->size;
1097 if (size < 0)
1098 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001099 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001100}
1101
Brett Cannon8d110132009-03-15 02:20:16 +00001102static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001103is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001104{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001105 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 if (p == NULL) {
1109 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001110 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 name);
1112 return NULL;
1113 }
Brett Cannon8d110132009-03-15 02:20:16 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (size < 0)
1118 Py_RETURN_TRUE;
1119 else
1120 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001121}
1122
1123
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001124/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001125 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001126 an exception set if the initialization failed.
1127 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001128
1129int
Victor Stinner53dc7352011-03-20 01:50:21 +01001130PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001131{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001132 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001133 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001134 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 int ispackage;
1136 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001137
Victor Stinner53dc7352011-03-20 01:50:21 +01001138 p = find_frozen(name);
1139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 if (p == NULL)
1141 return 0;
1142 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001143 _PyErr_Format(tstate, PyExc_ImportError,
1144 "Excluded frozen object named %R",
1145 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return -1;
1147 }
1148 size = p->size;
1149 ispackage = (size < 0);
1150 if (ispackage)
1151 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001152 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (co == NULL)
1154 return -1;
1155 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001156 _PyErr_Format(tstate, PyExc_TypeError,
1157 "frozen object %R is not a code object",
1158 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 goto err_return;
1160 }
1161 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001162 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001163 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001165 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (m == NULL)
1167 goto err_return;
1168 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001169 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 goto err_return;
1172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 err = PyDict_SetItemString(d, "__path__", l);
1174 Py_DECREF(l);
1175 if (err != 0)
1176 goto err_return;
1177 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001178 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001179 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001180 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001181 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001182 m = exec_code_in_module(tstate, name, d, co);
1183 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001185 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 Py_DECREF(co);
1187 Py_DECREF(m);
1188 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001189
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001190err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 Py_DECREF(co);
1192 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001193}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001194
Victor Stinner53dc7352011-03-20 01:50:21 +01001195int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001196PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001197{
1198 PyObject *nameobj;
1199 int ret;
1200 nameobj = PyUnicode_InternFromString(name);
1201 if (nameobj == NULL)
1202 return -1;
1203 ret = PyImport_ImportFrozenModuleObject(nameobj);
1204 Py_DECREF(nameobj);
1205 return ret;
1206}
1207
Guido van Rossum74e6a111994-08-29 12:54:38 +00001208
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001209/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001210 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001211
Guido van Rossum79f25d91997-04-29 20:08:16 +00001212PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001213PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyObject *pname;
1216 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 pname = PyUnicode_FromString(name);
1219 if (pname == NULL)
1220 return NULL;
1221 result = PyImport_Import(pname);
1222 Py_DECREF(pname);
1223 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001224}
1225
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001226
Christian Heimes072c0f12008-01-03 23:01:04 +00001227/* Import a module without blocking
1228 *
1229 * At first it tries to fetch the module from sys.modules. If the module was
1230 * never loaded before it loads it with PyImport_ImportModule() unless another
1231 * thread holds the import lock. In the latter case the function raises an
1232 * ImportError instead of blocking.
1233 *
1234 * Returns the module object with incremented ref count.
1235 */
1236PyObject *
1237PyImport_ImportModuleNoBlock(const char *name)
1238{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001239 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001240}
1241
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001242
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001243/* Remove importlib frames from the traceback,
1244 * except in Verbose mode. */
1245static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001246remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001247{
1248 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001249 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001250 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001251 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001252 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001253 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001254 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001255
1256 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001257 from the traceback. We always trim chunks
1258 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001259
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001260 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001261 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001262 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001263 }
1264
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001265 if (PyType_IsSubtype((PyTypeObject *) exception,
1266 (PyTypeObject *) PyExc_ImportError))
1267 always_trim = 1;
1268
1269 prev_link = &base_tb;
1270 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001271 while (tb != NULL) {
1272 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1273 PyObject *next = (PyObject *) traceback->tb_next;
1274 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001275 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001276 int now_in_importlib;
1277
1278 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001279 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1280 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001281 if (now_in_importlib && !in_importlib) {
1282 /* This is the link to this chunk of importlib tracebacks */
1283 outer_link = prev_link;
1284 }
1285 in_importlib = now_in_importlib;
1286
1287 if (in_importlib &&
1288 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001289 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001290 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001291 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001292 prev_link = outer_link;
1293 }
1294 else {
1295 prev_link = (PyObject **) &traceback->tb_next;
1296 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001297 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001298 tb = next;
1299 }
1300done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001301 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001302}
1303
1304
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001305static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001306resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001307{
Brett Cannonfd074152012-04-14 14:10:13 -04001308 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001309 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001310 _Py_IDENTIFIER(parent);
1311 PyObject *abs_name;
1312 PyObject *package = NULL;
1313 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001314 Py_ssize_t last_dot;
1315 PyObject *base;
1316 int level_up;
1317
1318 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001319 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001320 goto error;
1321 }
1322 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001323 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001324 goto error;
1325 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001326 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001327 if (package == Py_None) {
1328 package = NULL;
1329 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001330 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001331 goto error;
1332 }
1333 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001334 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001335 goto error;
1336 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001337
1338 if (package != NULL) {
1339 Py_INCREF(package);
1340 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001341 _PyErr_SetString(tstate, PyExc_TypeError,
1342 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001343 goto error;
1344 }
1345 else if (spec != NULL && spec != Py_None) {
1346 int equal;
1347 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1348 if (parent == NULL) {
1349 goto error;
1350 }
1351
1352 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1353 Py_DECREF(parent);
1354 if (equal < 0) {
1355 goto error;
1356 }
1357 else if (equal == 0) {
1358 if (PyErr_WarnEx(PyExc_ImportWarning,
1359 "__package__ != __spec__.parent", 1) < 0) {
1360 goto error;
1361 }
1362 }
1363 }
1364 }
1365 else if (spec != NULL && spec != Py_None) {
1366 package = _PyObject_GetAttrId(spec, &PyId_parent);
1367 if (package == NULL) {
1368 goto error;
1369 }
1370 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001371 _PyErr_SetString(tstate, PyExc_TypeError,
1372 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001373 goto error;
1374 }
1375 }
1376 else {
1377 if (PyErr_WarnEx(PyExc_ImportWarning,
1378 "can't resolve package from __spec__ or __package__, "
1379 "falling back on __name__ and __path__", 1) < 0) {
1380 goto error;
1381 }
1382
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001383 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001384 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001385 if (!_PyErr_Occurred(tstate)) {
1386 _PyErr_SetString(tstate, PyExc_KeyError,
1387 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001388 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001389 goto error;
1390 }
1391
1392 Py_INCREF(package);
1393 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001394 _PyErr_SetString(tstate, PyExc_TypeError,
1395 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001396 goto error;
1397 }
1398
Serhiy Storchakab510e102020-10-26 12:47:57 +02001399 int haspath = _PyDict_ContainsId(globals, &PyId___path__);
1400 if (haspath < 0) {
1401 goto error;
1402 }
1403 if (!haspath) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001404 Py_ssize_t dot;
1405
Serhiy Storchakab510e102020-10-26 12:47:57 +02001406 if (PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001407 goto error;
1408 }
1409
1410 dot = PyUnicode_FindChar(package, '.',
1411 0, PyUnicode_GET_LENGTH(package), -1);
1412 if (dot == -2) {
1413 goto error;
1414 }
Ben Lewis92420b32019-09-11 20:09:47 +10001415 else if (dot == -1) {
1416 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001417 }
Ben Lewis92420b32019-09-11 20:09:47 +10001418 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1419 if (substr == NULL) {
1420 goto error;
1421 }
1422 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001423 }
1424 }
1425
1426 last_dot = PyUnicode_GET_LENGTH(package);
1427 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001428 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001429 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001430
1431 for (level_up = 1; level_up < level; level_up += 1) {
1432 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1433 if (last_dot == -2) {
1434 goto error;
1435 }
1436 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001437 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001438 "attempted relative import beyond top-level "
1439 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001440 goto error;
1441 }
1442 }
1443
1444 base = PyUnicode_Substring(package, 0, last_dot);
1445 Py_DECREF(package);
1446 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1447 return base;
1448 }
1449
1450 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1451 Py_DECREF(base);
1452 return abs_name;
1453
Ben Lewis92420b32019-09-11 20:09:47 +10001454 no_parent_error:
1455 _PyErr_SetString(tstate, PyExc_ImportError,
1456 "attempted relative import "
1457 "with no known parent package");
1458
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001459 error:
1460 Py_XDECREF(package);
1461 return NULL;
1462}
1463
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001464static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001465import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001466{
1467 _Py_IDENTIFIER(_find_and_load);
1468 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001469 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001470 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001471 static int import_level;
1472 static _PyTime_t accumulated;
1473
1474 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1475
Steve Dowerb82e17e2019-05-23 08:45:22 -07001476 PyObject *sys_path = PySys_GetObject("path");
1477 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1478 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001479 if (_PySys_Audit(tstate, "import", "OOOOO",
1480 abs_name, Py_None, sys_path ? sys_path : Py_None,
1481 sys_meta_path ? sys_meta_path : Py_None,
1482 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001483 return NULL;
1484 }
1485
1486
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001487 /* XOptions is initialized after first some imports.
1488 * So we can't have negative cache before completed initialization.
1489 * Anyway, importlib._find_and_load is much slower than
1490 * _PyDict_GetItemIdWithError().
1491 */
1492 if (import_time) {
1493 static int header = 1;
1494 if (header) {
1495 fputs("import time: self [us] | cumulative | imported package\n",
1496 stderr);
1497 header = 0;
1498 }
1499
1500 import_level++;
1501 t1 = _PyTime_GetPerfCounter();
1502 accumulated = 0;
1503 }
1504
1505 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001506 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001507
1508 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1509 &PyId__find_and_load, abs_name,
1510 interp->import_func, NULL);
1511
1512 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001513 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001514 mod != NULL);
1515
1516 if (import_time) {
1517 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1518
1519 import_level--;
1520 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1521 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1522 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1523 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1524
1525 accumulated = accumulated_copy + cum;
1526 }
1527
1528 return mod;
1529}
1530
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001531PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001532PyImport_GetModule(PyObject *name)
1533{
1534 PyThreadState *tstate = _PyThreadState_GET();
1535 PyObject *mod;
1536
1537 mod = import_get_module(tstate, name);
1538 if (mod != NULL && mod != Py_None) {
1539 if (import_ensure_initialized(tstate, mod, name) < 0) {
1540 Py_DECREF(mod);
1541 remove_importlib_frames(tstate);
1542 return NULL;
1543 }
1544 }
1545 return mod;
1546}
1547
1548PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001549PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1550 PyObject *locals, PyObject *fromlist,
1551 int level)
1552{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001553 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001554 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001555 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001556 PyObject *final_mod = NULL;
1557 PyObject *mod = NULL;
1558 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001559 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001560 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001561
Brett Cannonfd074152012-04-14 14:10:13 -04001562 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001563 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001564 goto error;
1565 }
1566
1567 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1568 for added performance. */
1569
1570 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001571 _PyErr_SetString(tstate, PyExc_TypeError,
1572 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001573 goto error;
1574 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001575 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001576 goto error;
1577 }
1578 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001579 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001580 goto error;
1581 }
Brett Cannon849113a2016-01-22 15:25:50 -08001582
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001583 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001584 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001585 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001586 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001587 }
1588 else { /* level == 0 */
1589 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001590 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001591 goto error;
1592 }
Brett Cannonfd074152012-04-14 14:10:13 -04001593 abs_name = name;
1594 Py_INCREF(abs_name);
1595 }
1596
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001597 mod = import_get_module(tstate, abs_name);
1598 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001599 goto error;
1600 }
1601
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001602 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001603 if (import_ensure_initialized(tstate, mod, name) < 0) {
1604 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001605 }
Brett Cannonfd074152012-04-14 14:10:13 -04001606 }
1607 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001608 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001609 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001610 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001611 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001612 }
1613 }
1614
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001615 has_from = 0;
1616 if (fromlist != NULL && fromlist != Py_None) {
1617 has_from = PyObject_IsTrue(fromlist);
1618 if (has_from < 0)
1619 goto error;
1620 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001621 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001622 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1623 if (level == 0 || len > 0) {
1624 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001625
Victor Stinner744c34e2016-05-20 11:36:13 +02001626 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1627 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001628 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001629 }
1630
Victor Stinner744c34e2016-05-20 11:36:13 +02001631 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001632 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001633 final_mod = mod;
1634 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001635 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001636 }
1637
Brett Cannonfd074152012-04-14 14:10:13 -04001638 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001639 PyObject *front = PyUnicode_Substring(name, 0, dot);
1640 if (front == NULL) {
1641 goto error;
1642 }
1643
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001644 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001645 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001646 }
1647 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001648 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001649 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001650 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001651 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001652 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001653 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001654 }
Brett Cannonfd074152012-04-14 14:10:13 -04001655
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001656 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001657 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001658 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001659 if (!_PyErr_Occurred(tstate)) {
1660 _PyErr_Format(tstate, PyExc_KeyError,
1661 "%R not in sys.modules as expected",
1662 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001663 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001664 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001665 }
Brett Cannonfd074152012-04-14 14:10:13 -04001666 }
1667 }
1668 else {
1669 final_mod = mod;
1670 Py_INCREF(mod);
1671 }
1672 }
1673 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001674 PyObject *path;
1675 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1676 goto error;
1677 }
1678 if (path) {
1679 Py_DECREF(path);
1680 final_mod = _PyObject_CallMethodIdObjArgs(
1681 interp->importlib, &PyId__handle_fromlist,
1682 mod, fromlist, interp->import_func, NULL);
1683 }
1684 else {
1685 final_mod = mod;
1686 Py_INCREF(mod);
1687 }
Brett Cannonfd074152012-04-14 14:10:13 -04001688 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001689
Brett Cannonfd074152012-04-14 14:10:13 -04001690 error:
1691 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001692 Py_XDECREF(mod);
1693 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001694 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001695 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001696 }
Brett Cannonfd074152012-04-14 14:10:13 -04001697 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001698}
1699
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001700PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001701PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001702 PyObject *fromlist, int level)
1703{
1704 PyObject *nameobj, *mod;
1705 nameobj = PyUnicode_FromString(name);
1706 if (nameobj == NULL)
1707 return NULL;
1708 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1709 fromlist, level);
1710 Py_DECREF(nameobj);
1711 return mod;
1712}
1713
1714
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001715/* Re-import a module of any kind and return its module object, WITH
1716 INCREMENTED REFERENCE COUNT */
1717
Guido van Rossum79f25d91997-04-29 20:08:16 +00001718PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001719PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001720{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001721 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001722 _Py_IDENTIFIER(reload);
1723 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001724 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1725 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001726 if (PyErr_Occurred()) {
1727 return NULL;
1728 }
1729
Robert Rouhanif40bd462020-05-01 16:28:06 -07001730 importlib = PyImport_ImportModule("importlib");
1731 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001732 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001735
Robert Rouhanif40bd462020-05-01 16:28:06 -07001736 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1737 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001738 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001739}
1740
1741
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001742/* Higher-level import emulator which emulates the "import" statement
1743 more accurately -- it invokes the __import__() function from the
1744 builtins of the current globals. This means that the import is
1745 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001746 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001747 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001748 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001749 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001750
1751PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001752PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001753{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001754 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 static PyObject *silly_list = NULL;
1756 static PyObject *builtins_str = NULL;
1757 static PyObject *import_str = NULL;
1758 PyObject *globals = NULL;
1759 PyObject *import = NULL;
1760 PyObject *builtins = NULL;
1761 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 /* Initialize constant string objects */
1764 if (silly_list == NULL) {
1765 import_str = PyUnicode_InternFromString("__import__");
1766 if (import_str == NULL)
1767 return NULL;
1768 builtins_str = PyUnicode_InternFromString("__builtins__");
1769 if (builtins_str == NULL)
1770 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001771 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 if (silly_list == NULL)
1773 return NULL;
1774 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* Get the builtins from current globals */
1777 globals = PyEval_GetGlobals();
1778 if (globals != NULL) {
1779 Py_INCREF(globals);
1780 builtins = PyObject_GetItem(globals, builtins_str);
1781 if (builtins == NULL)
1782 goto err;
1783 }
1784 else {
1785 /* No globals -- use standard builtins, and fake globals */
1786 builtins = PyImport_ImportModuleLevel("builtins",
1787 NULL, NULL, NULL, 0);
1788 if (builtins == NULL)
1789 return NULL;
1790 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1791 if (globals == NULL)
1792 goto err;
1793 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /* Get the __import__ function from the builtins */
1796 if (PyDict_Check(builtins)) {
1797 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001798 if (import == NULL) {
1799 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
1800 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 }
1802 else
1803 import = PyObject_GetAttr(builtins, import_str);
1804 if (import == NULL)
1805 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001808 Always use absolute import here.
1809 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1811 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001812 if (r == NULL)
1813 goto err;
1814 Py_DECREF(r);
1815
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001816 r = import_get_module(tstate, module_name);
1817 if (r == NULL && !_PyErr_Occurred(tstate)) {
1818 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001819 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001820
1821 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 Py_XDECREF(globals);
1823 Py_XDECREF(builtins);
1824 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001827}
1828
Brett Cannon4caa61d2014-01-09 19:03:32 -05001829/*[clinic input]
1830_imp.extension_suffixes
1831
1832Returns the list of file suffixes used to identify extension modules.
1833[clinic start generated code]*/
1834
Brett Cannon4caa61d2014-01-09 19:03:32 -05001835static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001836_imp_extension_suffixes_impl(PyObject *module)
1837/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 list = PyList_New(0);
1842 if (list == NULL)
1843 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001844#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01001845 const char *suffix;
1846 unsigned int index = 0;
1847
Brett Cannon2657df42012-05-04 15:20:40 -04001848 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1849 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (item == NULL) {
1851 Py_DECREF(list);
1852 return NULL;
1853 }
1854 if (PyList_Append(list, item) < 0) {
1855 Py_DECREF(list);
1856 Py_DECREF(item);
1857 return NULL;
1858 }
1859 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001860 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 }
Brett Cannon2657df42012-05-04 15:20:40 -04001862#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001864}
1865
Brett Cannon4caa61d2014-01-09 19:03:32 -05001866/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001867_imp.init_frozen
1868
1869 name: unicode
1870 /
1871
1872Initializes a frozen module.
1873[clinic start generated code]*/
1874
Brett Cannon4caa61d2014-01-09 19:03:32 -05001875static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001876_imp_init_frozen_impl(PyObject *module, PyObject *name)
1877/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001878{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001879 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 int ret;
1881 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001882
Victor Stinner53dc7352011-03-20 01:50:21 +01001883 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (ret < 0)
1885 return NULL;
1886 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001887 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001889 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 Py_XINCREF(m);
1891 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001892}
1893
Brett Cannon4caa61d2014-01-09 19:03:32 -05001894/*[clinic input]
1895_imp.get_frozen_object
1896
1897 name: unicode
1898 /
1899
1900Create a code object for a frozen module.
1901[clinic start generated code]*/
1902
Brett Cannon4caa61d2014-01-09 19:03:32 -05001903static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001904_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1905/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001908}
1909
Brett Cannon4caa61d2014-01-09 19:03:32 -05001910/*[clinic input]
1911_imp.is_frozen_package
1912
1913 name: unicode
1914 /
1915
1916Returns True if the module name is of a frozen package.
1917[clinic start generated code]*/
1918
Brett Cannon4caa61d2014-01-09 19:03:32 -05001919static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001920_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1921/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001924}
1925
Brett Cannon4caa61d2014-01-09 19:03:32 -05001926/*[clinic input]
1927_imp.is_builtin
1928
1929 name: unicode
1930 /
1931
1932Returns True if the module name corresponds to a built-in module.
1933[clinic start generated code]*/
1934
Guido van Rossum79f25d91997-04-29 20:08:16 +00001935static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001936_imp_is_builtin_impl(PyObject *module, PyObject *name)
1937/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001938{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001939 return PyLong_FromLong(is_builtin(name));
1940}
1941
1942/*[clinic input]
1943_imp.is_frozen
1944
1945 name: unicode
1946 /
1947
1948Returns True if the module name corresponds to a frozen module.
1949[clinic start generated code]*/
1950
Brett Cannon4caa61d2014-01-09 19:03:32 -05001951static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001952_imp_is_frozen_impl(PyObject *module, PyObject *name)
1953/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001954{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001955 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 p = find_frozen(name);
1958 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001959}
1960
Larry Hastings1df0b352015-08-24 19:53:56 -07001961/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1962static int
1963exec_builtin_or_dynamic(PyObject *mod) {
1964 PyModuleDef *def;
1965 void *state;
1966
1967 if (!PyModule_Check(mod)) {
1968 return 0;
1969 }
1970
1971 def = PyModule_GetDef(mod);
1972 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07001973 return 0;
1974 }
Brett Cannon52794db2016-09-07 17:00:43 -07001975
Larry Hastings1df0b352015-08-24 19:53:56 -07001976 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07001977 if (state) {
1978 /* Already initialized; skip reload */
1979 return 0;
1980 }
Brett Cannon52794db2016-09-07 17:00:43 -07001981
Larry Hastings1df0b352015-08-24 19:53:56 -07001982 return PyModule_ExecDef(mod, def);
1983}
1984
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001985#ifdef HAVE_DYNAMIC_LOADING
1986
Brett Cannon4caa61d2014-01-09 19:03:32 -05001987/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10001988_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05001989
Nick Coghland5cacbb2015-05-23 22:24:10 +10001990 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05001991 file: object = NULL
1992 /
1993
Nick Coghland5cacbb2015-05-23 22:24:10 +10001994Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05001995[clinic start generated code]*/
1996
Brett Cannon4caa61d2014-01-09 19:03:32 -05001997static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001998_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
1999/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002000{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002001 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002002 FILE *fp;
2003
Nick Coghland5cacbb2015-05-23 22:24:10 +10002004 name = PyObject_GetAttrString(spec, "name");
2005 if (name == NULL) {
2006 return NULL;
2007 }
2008
2009 path = PyObject_GetAttrString(spec, "origin");
2010 if (path == NULL) {
2011 Py_DECREF(name);
2012 return NULL;
2013 }
2014
2015 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002016 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002017 Py_DECREF(name);
2018 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002019 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002020 return mod;
2021 }
2022
Brett Cannon4caa61d2014-01-09 19:03:32 -05002023 if (file != NULL) {
2024 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002025 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002026 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002027 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002029 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002031 else
2032 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002033
2034 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2035
2036 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002037 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (fp)
2039 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002040 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002041}
2042
Nick Coghland5cacbb2015-05-23 22:24:10 +10002043/*[clinic input]
2044_imp.exec_dynamic -> int
2045
2046 mod: object
2047 /
2048
2049Initialize an extension module.
2050[clinic start generated code]*/
2051
2052static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002053_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2054/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002055{
Larry Hastings1df0b352015-08-24 19:53:56 -07002056 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002057}
2058
2059
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002060#endif /* HAVE_DYNAMIC_LOADING */
2061
Larry Hastings7726ac92014-01-31 22:03:12 -08002062/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002063_imp.exec_builtin -> int
2064
2065 mod: object
2066 /
2067
2068Initialize a built-in module.
2069[clinic start generated code]*/
2070
2071static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002072_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2073/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002074{
2075 return exec_builtin_or_dynamic(mod);
2076}
2077
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002078/*[clinic input]
2079_imp.source_hash
2080
2081 key: long
2082 source: Py_buffer
2083[clinic start generated code]*/
2084
2085static PyObject *
2086_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2087/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2088{
Benjamin Peterson83620772017-12-09 12:18:56 -08002089 union {
2090 uint64_t x;
2091 char data[sizeof(uint64_t)];
2092 } hash;
2093 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002094#if !PY_LITTLE_ENDIAN
2095 // Force to little-endian. There really ought to be a succinct standard way
2096 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002097 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2098 char tmp = hash.data[i];
2099 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2100 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002101 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002102#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002103 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002104}
2105
Barry Warsaw28a691b2010-04-17 00:19:56 +00002106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002107PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002108"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002109
Guido van Rossum79f25d91997-04-29 20:08:16 +00002110static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002111 _IMP_EXTENSION_SUFFIXES_METHODDEF
2112 _IMP_LOCK_HELD_METHODDEF
2113 _IMP_ACQUIRE_LOCK_METHODDEF
2114 _IMP_RELEASE_LOCK_METHODDEF
2115 _IMP_GET_FROZEN_OBJECT_METHODDEF
2116 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002117 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002118 _IMP_INIT_FROZEN_METHODDEF
2119 _IMP_IS_BUILTIN_METHODDEF
2120 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002121 _IMP_CREATE_DYNAMIC_METHODDEF
2122 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002123 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002124 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002125 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002126 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002127};
2128
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002129
Martin v. Löwis1a214512008-06-11 05:26:20 +00002130static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002132 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 doc_imp,
2134 0,
2135 imp_methods,
2136 NULL,
2137 NULL,
2138 NULL,
2139 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002140};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002141
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002142PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002143PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002148 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002150 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002152 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002154 }
2155
Victor Stinnerda7933e2020-04-13 03:04:28 +02002156 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002157 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002158 if (pyc_mode == NULL) {
2159 goto failure;
2160 }
2161 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2162 Py_DECREF(pyc_mode);
2163 goto failure;
2164 }
2165 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002168 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 Py_XDECREF(m);
2170 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002171}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002172
2173
Guido van Rossumb18618d2000-05-03 23:44:39 +00002174/* API for embedding applications that want to add their own entries
2175 to the table of built-in modules. This should normally be called
2176 *before* Py_Initialize(). When the table resize fails, -1 is
2177 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002178
2179 After a similar function by Just van Rossum. */
2180
2181int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002182PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002185 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002186 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 /* Count the number of entries in both tables */
2189 for (n = 0; newtab[n].name != NULL; n++)
2190 ;
2191 if (n == 0)
2192 return 0; /* Nothing to do */
2193 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2194 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002195
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002196 /* Force default raw memory allocator to get a known allocator to be able
2197 to release the memory in _PyImport_Fini2() */
2198 PyMemAllocatorEx old_alloc;
2199 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002202 p = NULL;
2203 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002204 size_t size = sizeof(struct _inittab) * (i + n + 1);
2205 p = PyMem_RawRealloc(inittab_copy, size);
2206 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002207 if (p == NULL) {
2208 res = -1;
2209 goto done;
2210 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002211
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002212 /* Copy the tables into the new memory at the first call
2213 to PyImport_ExtendInittab(). */
2214 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002216 }
2217 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2218 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002219
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002220done:
2221 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2222 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002223}
2224
2225/* Shorthand to add a single entry given a name and a function */
2226
2227int
Brett Cannona826f322009-04-02 03:41:46 +00002228PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002233
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002234 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002238}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002239
2240#ifdef __cplusplus
2241}
2242#endif