blob: 77e6baef011e39031e69faa60b94446db8ff6376 [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 Stinnerb45d2592019-06-20 00:05:23 +020055_PyImportHooks_Init(PyThreadState *tstate)
Just van Rossum52e14d62002-12-30 22:08:05 +000056{
Brett Cannonfd074152012-04-14 14:10:13 -040057 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000059
Brett Cannonfd074152012-04-14 14:10:13 -040060 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 v = PyList_New(0);
62 if (v == NULL)
63 goto error;
64 err = PySys_SetObject("meta_path", v);
65 Py_DECREF(v);
66 if (err)
67 goto error;
68 v = PyDict_New();
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("path_importer_cache", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 path_hooks = PyList_New(0);
76 if (path_hooks == NULL)
77 goto error;
78 err = PySys_SetObject("path_hooks", path_hooks);
79 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 }
Brett Cannonfd074152012-04-14 14:10:13 -040082 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020083 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084
85 error:
Victor Stinnerb45d2592019-06-20 00:05:23 +020086 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020087 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080088 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040089}
90
Victor Stinner331a6a52019-05-27 16:39:22 +020091PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020092_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040093{
ukwksk5e6312c2018-05-15 04:10:52 +090094 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040095 int err = 0;
96
97 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020098 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020099 _PyErr_SetString(tstate, PyExc_RuntimeError,
100 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400101 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200102 }
Brett Cannonfd074152012-04-14 14:10:13 -0400103
Victor Stinnerda7933e2020-04-13 03:04:28 +0200104 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200105 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400106 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200107 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108
ukwksk5e6312c2018-05-15 04:10:52 +0900109 zipimport = PyImport_ImportModule("zipimport");
110 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200111 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200112 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 }
116 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200117 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900118 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200119 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900120 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200122 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200123 if (verbose) {
124 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
127 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400128 /* sys.path_hooks.insert(0, zipimporter) */
129 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400131 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400133 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200134 if (verbose) {
135 PySys_WriteStderr("# installed zipimport hook\n");
136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 }
138 }
Brett Cannonfd074152012-04-14 14:10:13 -0400139
Victor Stinner331a6a52019-05-27 16:39:22 +0200140 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400141
142 error:
143 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200144 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000145}
146
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147/* Locking primitives to prevent parallel imports of the same module
148 in different threads to return with a partially loaded module.
149 These calls are serialized by the global interpreter lock. */
150
Victor Stinner26881c82020-06-02 15:51:37 +0200151static PyThread_type_lock import_lock = NULL;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200152static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153static int import_lock_level = 0;
154
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000155void
156_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000157{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200158 unsigned long me = PyThread_get_thread_ident();
159 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 return; /* Too bad */
161 if (import_lock == NULL) {
162 import_lock = PyThread_allocate_lock();
163 if (import_lock == NULL)
164 return; /* Nothing much we can do. */
165 }
166 if (import_lock_thread == me) {
167 import_lock_level++;
168 return;
169 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200170 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
171 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 {
173 PyThreadState *tstate = PyEval_SaveThread();
Victor Stinner26881c82020-06-02 15:51:37 +0200174 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyEval_RestoreThread(tstate);
176 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100177 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 import_lock_thread = me;
179 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000180}
181
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000182int
183_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000184{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200185 unsigned long me = PyThread_get_thread_ident();
186 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return 0; /* Too bad */
188 if (import_lock_thread != me)
189 return -1;
190 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100191 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200193 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyThread_release_lock(import_lock);
195 }
196 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000197}
198
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900199#ifdef HAVE_FORK
Victor Stinner26881c82020-06-02 15:51:37 +0200200/* This function is called from PyOS_AfterFork_Child() to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000201 created child processes do not share locks with the parent.
202 We now acquire the import lock around fork() calls but on some platforms
203 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Victor Stinner26881c82020-06-02 15:51:37 +0200204PyStatus
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000205_PyImport_ReInitLock(void)
206{
Christian Heimes418fd742015-04-19 21:08:42 +0200207 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900208 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner26881c82020-06-02 15:51:37 +0200209 return _PyStatus_ERR("failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200210 }
211 }
Victor Stinner26881c82020-06-02 15:51:37 +0200212
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000213 if (import_lock_level > 1) {
214 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200215 unsigned long me = PyThread_get_thread_ident();
Victor Stinner45b34a02020-06-02 17:13:49 +0200216 PyThread_acquire_lock(import_lock, WAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000217 import_lock_thread = me;
218 import_lock_level--;
219 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200220 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000221 import_lock_level = 0;
222 }
Victor Stinner26881c82020-06-02 15:51:37 +0200223 return _PyStatus_OK();
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000224}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900225#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000226
Brett Cannon4caa61d2014-01-09 19:03:32 -0500227/*[clinic input]
228_imp.lock_held
229
230Return True if the import lock is currently held, else False.
231
232On platforms without threads, return False.
233[clinic start generated code]*/
234
Brett Cannon4caa61d2014-01-09 19:03:32 -0500235static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300236_imp_lock_held_impl(PyObject *module)
237/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000238{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200239 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000240}
241
Brett Cannon4caa61d2014-01-09 19:03:32 -0500242/*[clinic input]
243_imp.acquire_lock
244
245Acquires the interpreter's import lock for the current thread.
246
247This lock should be used by import hooks to ensure thread-safety when importing
248modules. On platforms without threads, this function does nothing.
249[clinic start generated code]*/
250
Brett Cannon4caa61d2014-01-09 19:03:32 -0500251static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300252_imp_acquire_lock_impl(PyObject *module)
253/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200256 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000257}
258
Brett Cannon4caa61d2014-01-09 19:03:32 -0500259/*[clinic input]
260_imp.release_lock
261
262Release the interpreter's import lock.
263
264On platforms without threads, this function does nothing.
265[clinic start generated code]*/
266
Brett Cannon4caa61d2014-01-09 19:03:32 -0500267static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300268_imp_release_lock_impl(PyObject *module)
269/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (_PyImport_ReleaseLock() < 0) {
272 PyErr_SetString(PyExc_RuntimeError,
273 "not holding the import lock");
274 return NULL;
275 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200276 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000277}
278
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100279void
280_PyImport_Fini(void)
281{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200282 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100283 if (import_lock != NULL) {
284 PyThread_free_lock(import_lock);
285 import_lock = NULL;
286 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100287}
288
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100289void
290_PyImport_Fini2(void)
291{
292 /* Use the same memory allocator than PyImport_ExtendInittab(). */
293 PyMemAllocatorEx old_alloc;
294 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
295
296 /* Free memory allocated by PyImport_ExtendInittab() */
297 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700298 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100299
300 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
301}
302
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303/* Helper for sys */
304
305PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000306PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307{
Victor Stinner81a7be32020-04-14 15:14:01 +0200308 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600309 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100310 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600311 }
Eric Snow93c92f72017-09-13 23:46:04 -0700312 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313}
314
Eric Snowd393c1b2017-09-14 12:18:12 -0600315/* In some corner cases it is important to be sure that the import
316 machinery has been initialized (or not cleaned up yet). For
317 example, see issue #4236 and PyModule_Create2(). */
318
319int
320_PyImport_IsInitialized(PyInterpreterState *interp)
321{
322 if (interp->modules == NULL)
323 return 0;
324 return 1;
325}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000326
Eric Snow3f9eee62017-09-15 16:35:20 -0600327PyObject *
328_PyImport_GetModuleId(struct _Py_Identifier *nameid)
329{
330 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
331 if (name == NULL) {
332 return NULL;
333 }
334 return PyImport_GetModule(name);
335}
336
337int
338_PyImport_SetModule(PyObject *name, PyObject *m)
339{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200340 PyThreadState *tstate = _PyThreadState_GET();
341 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600342 return PyObject_SetItem(modules, name, m);
343}
344
345int
346_PyImport_SetModuleString(const char *name, PyObject *m)
347{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200348 PyThreadState *tstate = _PyThreadState_GET();
349 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600350 return PyMapping_SetItemString(modules, name, m);
351}
352
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200353static PyObject *
354import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600355{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200356 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600357 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200358 _PyErr_SetString(tstate, PyExc_RuntimeError,
359 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600360 return NULL;
361 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200362
363 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600364 Py_INCREF(modules);
365 if (PyDict_CheckExact(modules)) {
366 m = PyDict_GetItemWithError(modules, name); /* borrowed */
367 Py_XINCREF(m);
368 }
369 else {
370 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200371 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
372 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600373 }
374 }
375 Py_DECREF(modules);
376 return m;
377}
378
379
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100380static int
381import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200382{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100383 PyInterpreterState *interp = tstate->interp;
384 PyObject *spec;
385
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100386 _Py_IDENTIFIER(_lock_unlock_module);
387
388 /* Optimization: only call _bootstrap._lock_unlock_module() if
389 __spec__._initializing is true.
390 NOTE: because of this, initializing must be set *before*
391 stuffing the new module in sys.modules.
392 */
393 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
394 int busy = _PyModuleSpec_IsInitializing(spec);
395 Py_XDECREF(spec);
396 if (busy) {
397 /* Wait until module is done importing. */
398 PyObject *value = _PyObject_CallMethodIdOneArg(
399 interp->importlib, &PyId__lock_unlock_module, name);
400 if (value == NULL) {
401 return -1;
402 }
403 Py_DECREF(value);
404 }
405 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200406}
407
408
Barry Warsaw28a691b2010-04-17 00:19:56 +0000409/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000410
411long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000412PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000413{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200414 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200415 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600416 PyObject *external, *pyc_magic;
417
418 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
419 if (external == NULL)
420 return -1;
421 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
422 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400423 if (pyc_magic == NULL)
424 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200425 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700426 Py_DECREF(pyc_magic);
427 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000428}
429
430
Brett Cannon3adc7b72012-07-09 14:22:12 -0400431extern const char * _PySys_ImplCacheTag;
432
Barry Warsaw28a691b2010-04-17 00:19:56 +0000433const char *
434PyImport_GetMagicTag(void)
435{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400436 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000437}
438
Brett Cannon98979b82012-07-02 15:13:11 -0400439
Guido van Rossum25ce5661997-08-02 03:10:38 +0000440/* Magic for extension modules (built-in as well as dynamically
441 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200442 once, we keep a static dictionary 'extensions' keyed by the tuple
443 (module name, module name) (for built-in modules) or by
444 (filename, module name) (for dynamically loaded modules), containing these
445 modules. A copy of the module's dictionary is stored by calling
446 _PyImport_FixupExtensionObject() immediately after the module initialization
447 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100448 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000449
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000450 Modules which do support multiple initialization set their m_size
451 field to a non-negative number (indicating the size of the
452 module-specific state). They are still recorded in the extensions
453 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000454*/
455
456int
Victor Stinner95872862011-03-07 18:20:56 +0100457_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200458 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (mod == NULL || !PyModule_Check(mod)) {
461 PyErr_BadInternalCall();
462 return -1;
463 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100464
465 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (!def) {
467 PyErr_BadInternalCall();
468 return -1;
469 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100470
471 PyThreadState *tstate = _PyThreadState_GET();
472 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100474 }
475 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600476 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return -1;
478 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100479
480 if (_Py_IsMainInterpreter(tstate)) {
481 if (def->m_size == -1) {
482 if (def->m_base.m_copy) {
483 /* Somebody already imported the module,
484 likely under a different name.
485 XXX this should really not happen. */
486 Py_CLEAR(def->m_base.m_copy);
487 }
488 PyObject *dict = PyModule_GetDict(mod);
489 if (dict == NULL) {
490 return -1;
491 }
492 def->m_base.m_copy = PyDict_Copy(dict);
493 if (def->m_base.m_copy == NULL) {
494 return -1;
495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100497
498 if (extensions == NULL) {
499 extensions = PyDict_New();
500 if (extensions == NULL) {
501 return -1;
502 }
503 }
504
505 PyObject *key = PyTuple_Pack(2, filename, name);
506 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100508 }
509 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
510 Py_DECREF(key);
511 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000517}
518
Victor Stinner49d3f252010-10-17 01:24:53 +0000519int
Eric Snowd393c1b2017-09-14 12:18:12 -0600520_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000521{
522 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100523 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100524 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100525 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000526 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600527 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100528 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000529 return res;
530}
531
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200532static PyObject *
533import_find_extension(PyThreadState *tstate, PyObject *name,
534 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200536 if (extensions == NULL) {
537 return NULL;
538 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600539
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200540 PyObject *key = PyTuple_Pack(2, filename, name);
541 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200543 }
544 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500545 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200546 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200548 }
549
550 PyObject *mod, *mdict;
551 PyObject *modules = tstate->interp->modules;
552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (def->m_size == -1) {
554 /* Module does not support repeated initialization */
555 if (def->m_base.m_copy == NULL)
556 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200557 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (mod == NULL)
559 return NULL;
560 mdict = PyModule_GetDict(mod);
561 if (mdict == NULL)
562 return NULL;
563 if (PyDict_Update(mdict, def->m_base.m_copy))
564 return NULL;
565 }
566 else {
567 if (def->m_base.m_init == NULL)
568 return NULL;
569 mod = def->m_base.m_init();
570 if (mod == NULL)
571 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600572 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200573 Py_DECREF(mod);
574 return NULL;
575 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_DECREF(mod);
577 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100578 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600579 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return NULL;
581 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200582
Victor Stinnerda7933e2020-04-13 03:04:28 +0200583 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200584 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100585 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200586 name, filename);
587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000589}
590
Victor Stinner49d3f252010-10-17 01:24:53 +0000591PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200592_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
593{
594 PyThreadState *tstate = _PyThreadState_GET();
595 return import_find_extension(tstate, name, filename);
596}
597
598
599PyObject *
600_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000601{
Victor Stinner95872862011-03-07 18:20:56 +0100602 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100603 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100604 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000605 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200606 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100607 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000608 return res;
609}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610
611/* Get the module object corresponding to a module name.
612 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000613 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000614 Because the former action is most common, THIS DOES NOT RETURN A
615 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000616
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200617static PyObject *
618import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000619{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200620 PyObject *modules = tstate->interp->modules;
621 if (modules == NULL) {
622 _PyErr_SetString(tstate, PyExc_RuntimeError,
623 "no import module dictionary");
624 return NULL;
625 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600626
Eric Snow86b7afd2017-09-04 17:54:09 -0600627 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600628 if (PyDict_CheckExact(modules)) {
629 m = PyDict_GetItemWithError(modules, name);
630 }
631 else {
632 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000633 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600634 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200635 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
636 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600637 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200638 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200639 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200640 return NULL;
641 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600642 if (m != NULL && PyModule_Check(m)) {
643 return m;
644 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000645 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (m == NULL)
647 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600648 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 Py_DECREF(m);
650 return NULL;
651 }
652 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000655}
656
Victor Stinner27ee0892011-03-04 12:57:09 +0000657PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200658PyImport_AddModuleObject(PyObject *name)
659{
660 PyThreadState *tstate = _PyThreadState_GET();
661 return import_add_module(tstate, name);
662}
663
664
665PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000666PyImport_AddModule(const char *name)
667{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200668 PyObject *nameobj = PyUnicode_FromString(name);
669 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000670 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200671 }
672 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000673 Py_DECREF(nameobj);
674 return module;
675}
676
677
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300678/* Remove name from sys.modules, if it's there.
679 * Can be called with an exception raised.
680 * If fail to remove name a new exception will be chained with the old
681 * exception, otherwise the old exception is preserved.
682 */
Tim Peters1cd70172004-08-02 03:52:12 +0000683static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200684remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000685{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600686 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200687 _PyErr_Fetch(tstate, &type, &value, &traceback);
688
689 PyObject *modules = tstate->interp->modules;
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300690 if (PyDict_CheckExact(modules)) {
691 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
692 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600693 }
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300694 else if (PyMapping_DelItem(modules, name) < 0) {
695 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
696 _PyErr_Clear(tstate);
697 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600698 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200699
Serhiy Storchaka8287aad2020-10-11 16:51:07 +0300700 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000701}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702
Christian Heimes3b06e532008-01-07 20:12:44 +0000703
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000704/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000705 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
706 * removed from sys.modules, to avoid leaving damaged module objects
707 * in sys.modules. The caller may wish to restore the original
708 * module object (if any) in this case; PyImport_ReloadModule is an
709 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000710 *
711 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
712 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000713 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000714PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300715PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return PyImport_ExecCodeModuleWithPathnames(
718 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000719}
720
721PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300722PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 return PyImport_ExecCodeModuleWithPathnames(
725 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000726}
727
728PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300729PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
730 const char *pathname,
731 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000732{
Victor Stinner27ee0892011-03-04 12:57:09 +0000733 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600734 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000735
736 nameobj = PyUnicode_FromString(name);
737 if (nameobj == NULL)
738 return NULL;
739
Victor Stinner27ee0892011-03-04 12:57:09 +0000740 if (cpathname != NULL) {
741 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
742 if (cpathobj == NULL)
743 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400744 }
745 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000746 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400747
748 if (pathname != NULL) {
749 pathobj = PyUnicode_DecodeFSDefault(pathname);
750 if (pathobj == NULL)
751 goto error;
752 }
753 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200754 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400755 _Py_IDENTIFIER(_get_sourcefile);
756
757 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100758 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400759 }
760
Eric Snow32439d62015-05-02 19:15:18 -0600761 external= PyObject_GetAttrString(interp->importlib,
762 "_bootstrap_external");
763 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200764 pathobj = _PyObject_CallMethodIdOneArg(
765 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600766 Py_DECREF(external);
767 }
Brett Cannona6473f92012-07-13 13:57:03 -0400768 if (pathobj == NULL)
769 PyErr_Clear();
770 }
771 else
772 pathobj = NULL;
773
Victor Stinner27ee0892011-03-04 12:57:09 +0000774 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
775error:
776 Py_DECREF(nameobj);
777 Py_XDECREF(pathobj);
778 Py_XDECREF(cpathobj);
779 return m;
780}
781
Brett Cannon18fc4e72014-04-04 10:01:46 -0400782static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200783module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000784{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200785 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400786 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000787
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200788 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (m == NULL)
790 return NULL;
791 /* If the module is being reloaded, we get the old module back
792 and re-use its dict to exec the new code. */
793 d = PyModule_GetDict(m);
Serhiy Storchakab510e102020-10-26 12:47:57 +0200794 int r = _PyDict_ContainsId(d, &PyId___builtins__);
795 if (r == 0) {
796 r = _PyDict_SetItemId(d, &PyId___builtins__,
797 PyEval_GetBuiltins());
798 }
799 if (r < 0) {
800 remove_module(tstate, name);
801 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400803
Eric Snow08197a42014-05-12 17:54:55 -0600804 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400805}
806
807static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200808exec_code_in_module(PyThreadState *tstate, PyObject *name,
809 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -0400810{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400811 PyObject *v, *m;
812
813 v = PyEval_EvalCode(code_object, module_dict, module_dict);
814 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200815 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400816 return NULL;
817 }
818 Py_DECREF(v);
819
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200820 m = import_get_module(tstate, name);
821 if (m == NULL && !_PyErr_Occurred(tstate)) {
822 _PyErr_Format(tstate, PyExc_ImportError,
823 "Loaded module %R not found in sys.modules",
824 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400825 }
826
Brett Cannon18fc4e72014-04-04 10:01:46 -0400827 return m;
828}
829
830PyObject*
831PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
832 PyObject *cpathname)
833{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200834 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600835 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600836 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400837
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200838 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400839 if (d == NULL) {
840 return NULL;
841 }
842
Eric Snow08197a42014-05-12 17:54:55 -0600843 if (pathname == NULL) {
844 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200846 external = PyObject_GetAttrString(tstate->interp->importlib,
847 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -0600848 if (external == NULL)
849 return NULL;
850 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600851 &PyId__fix_up_module,
852 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600853 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600854 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600855 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200856 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 }
Eric Snow08197a42014-05-12 17:54:55 -0600858 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000859}
860
861
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000862static void
863update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyObject *constants, *tmp;
866 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (PyUnicode_Compare(co->co_filename, oldname))
869 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000870
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200871 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300872 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 constants = co->co_consts;
875 n = PyTuple_GET_SIZE(constants);
876 for (i = 0; i < n; i++) {
877 tmp = PyTuple_GET_ITEM(constants, i);
878 if (PyCode_Check(tmp))
879 update_code_filenames((PyCodeObject *)tmp,
880 oldname, newname);
881 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000882}
883
Victor Stinner2f42ae52011-03-20 00:41:24 +0100884static void
885update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000886{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100887 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000888
Victor Stinner2f42ae52011-03-20 00:41:24 +0100889 if (PyUnicode_Compare(co->co_filename, newname) == 0)
890 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 oldname = co->co_filename;
893 Py_INCREF(oldname);
894 update_code_filenames(co, oldname, newname);
895 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000896}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000897
Brett Cannon4caa61d2014-01-09 19:03:32 -0500898/*[clinic input]
899_imp._fix_co_filename
900
901 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
902 Code object to change.
903
904 path: unicode
905 File path to use.
906 /
907
908Changes code.co_filename to specify the passed-in file path.
909[clinic start generated code]*/
910
Brett Cannon4caa61d2014-01-09 19:03:32 -0500911static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300912_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -0400913 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300914/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700915
Brett Cannon4caa61d2014-01-09 19:03:32 -0500916{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500917 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700918
919 Py_RETURN_NONE;
920}
921
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000922
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000923/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700924static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000925
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000926
927/* Helper to test for built-in module */
928
929static int
Victor Stinner95872862011-03-07 18:20:56 +0100930is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000931{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200932 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200934 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (PyImport_Inittab[i].initfunc == NULL)
936 return -1;
937 else
938 return 1;
939 }
940 }
941 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000942}
943
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000944
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700945/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +0000946 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000947 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000948 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -0700949 this tells our caller that the path based finder could not find
950 a finder for this path item. Cache the result in
951 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +0000952 Returns a borrowed reference. */
953
954static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200955get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
956 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 PyObject *importer;
959 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* These conditions are the caller's responsibility: */
962 assert(PyList_Check(path_hooks));
963 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 nhooks = PyList_Size(path_hooks);
966 if (nhooks < 0)
967 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000968
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200969 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200970 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 /* set path_importer_cache[p] to None to avoid recursion */
974 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
975 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 for (j = 0; j < nhooks; j++) {
978 PyObject *hook = PyList_GetItem(path_hooks, j);
979 if (hook == NULL)
980 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +0100981 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (importer != NULL)
983 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000984
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200985 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return NULL;
987 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200988 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 }
990 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400991 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 }
993 if (importer != NULL) {
994 int err = PyDict_SetItem(path_importer_cache, p, importer);
995 Py_DECREF(importer);
996 if (err != 0)
997 return NULL;
998 }
999 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001000}
1001
Benjamin Petersone5024512018-09-12 12:06:42 -07001002PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001003PyImport_GetImporter(PyObject *path)
1004{
1005 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001007
Victor Stinner1e53bba2013-07-16 22:26:05 +02001008 path_importer_cache = PySys_GetObject("path_importer_cache");
1009 path_hooks = PySys_GetObject("path_hooks");
1010 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001011 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001012 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 }
1014 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1015 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001016}
1017
Nick Coghland5cacbb2015-05-23 22:24:10 +10001018/*[clinic input]
1019_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001020
Nick Coghland5cacbb2015-05-23 22:24:10 +10001021 spec: object
1022 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001023
Nick Coghland5cacbb2015-05-23 22:24:10 +10001024Create an extension module.
1025[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001026
Nick Coghland5cacbb2015-05-23 22:24:10 +10001027static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001028_imp_create_builtin(PyObject *module, PyObject *spec)
1029/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001030{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001031 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001033 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001034 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001035 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001036
Nick Coghland5cacbb2015-05-23 22:24:10 +10001037 name = PyObject_GetAttrString(spec, "name");
1038 if (name == NULL) {
1039 return NULL;
1040 }
1041
Victor Stinner5eb4f592013-11-14 22:38:52 +01001042 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001043 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001044 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001045 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001046 return mod;
1047 }
1048
1049 namestr = PyUnicode_AsUTF8(name);
1050 if (namestr == NULL) {
1051 Py_DECREF(name);
1052 return NULL;
1053 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001054
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001055 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001057 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001058 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001060 /* Cannot re-init internal module ("sys" or "builtins") */
1061 mod = PyImport_AddModule(namestr);
1062 Py_DECREF(name);
1063 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001066 if (mod == NULL) {
1067 Py_DECREF(name);
1068 return NULL;
1069 }
1070 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1071 Py_DECREF(name);
1072 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1073 } else {
1074 /* Remember pointer to module init function. */
1075 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001076 if (def == NULL) {
1077 Py_DECREF(name);
1078 return NULL;
1079 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001080 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001081 if (_PyImport_FixupExtensionObject(mod, name, name,
1082 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001083 Py_DECREF(name);
1084 return NULL;
1085 }
1086 Py_DECREF(name);
1087 return mod;
1088 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 }
1090 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001091 Py_DECREF(name);
1092 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001093}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001094
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001095
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001096/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001097
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001098static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001099find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001100{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001101 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001102
Victor Stinner53dc7352011-03-20 01:50:21 +01001103 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 for (p = PyImport_FrozenModules; ; p++) {
1107 if (p->name == NULL)
1108 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001109 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 break;
1111 }
1112 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001113}
1114
Guido van Rossum79f25d91997-04-29 20:08:16 +00001115static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001116get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001117{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001118 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (p == NULL) {
1122 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001123 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 name);
1125 return NULL;
1126 }
1127 if (p->code == NULL) {
1128 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001129 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 name);
1131 return NULL;
1132 }
1133 size = p->size;
1134 if (size < 0)
1135 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001136 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001137}
1138
Brett Cannon8d110132009-03-15 02:20:16 +00001139static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001140is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001141{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001142 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (p == NULL) {
1146 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001147 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 name);
1149 return NULL;
1150 }
Brett Cannon8d110132009-03-15 02:20:16 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (size < 0)
1155 Py_RETURN_TRUE;
1156 else
1157 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001158}
1159
1160
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001161/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001162 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001163 an exception set if the initialization failed.
1164 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001165
1166int
Victor Stinner53dc7352011-03-20 01:50:21 +01001167PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001168{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001169 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001170 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001171 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 int ispackage;
1173 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001174
Victor Stinner53dc7352011-03-20 01:50:21 +01001175 p = find_frozen(name);
1176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (p == NULL)
1178 return 0;
1179 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001180 _PyErr_Format(tstate, PyExc_ImportError,
1181 "Excluded frozen object named %R",
1182 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return -1;
1184 }
1185 size = p->size;
1186 ispackage = (size < 0);
1187 if (ispackage)
1188 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001189 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (co == NULL)
1191 return -1;
1192 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001193 _PyErr_Format(tstate, PyExc_TypeError,
1194 "frozen object %R is not a code object",
1195 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 goto err_return;
1197 }
1198 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001199 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001200 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001202 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (m == NULL)
1204 goto err_return;
1205 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001206 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 goto err_return;
1209 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 err = PyDict_SetItemString(d, "__path__", l);
1211 Py_DECREF(l);
1212 if (err != 0)
1213 goto err_return;
1214 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001215 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001216 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001217 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001218 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001219 m = exec_code_in_module(tstate, name, d, co);
1220 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001222 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 Py_DECREF(co);
1224 Py_DECREF(m);
1225 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001226
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001227err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 Py_DECREF(co);
1229 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001230}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001231
Victor Stinner53dc7352011-03-20 01:50:21 +01001232int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001233PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001234{
1235 PyObject *nameobj;
1236 int ret;
1237 nameobj = PyUnicode_InternFromString(name);
1238 if (nameobj == NULL)
1239 return -1;
1240 ret = PyImport_ImportFrozenModuleObject(nameobj);
1241 Py_DECREF(nameobj);
1242 return ret;
1243}
1244
Guido van Rossum74e6a111994-08-29 12:54:38 +00001245
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001247 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001248
Guido van Rossum79f25d91997-04-29 20:08:16 +00001249PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001250PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PyObject *pname;
1253 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 pname = PyUnicode_FromString(name);
1256 if (pname == NULL)
1257 return NULL;
1258 result = PyImport_Import(pname);
1259 Py_DECREF(pname);
1260 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001261}
1262
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001263
Christian Heimes072c0f12008-01-03 23:01:04 +00001264/* Import a module without blocking
1265 *
1266 * At first it tries to fetch the module from sys.modules. If the module was
1267 * never loaded before it loads it with PyImport_ImportModule() unless another
1268 * thread holds the import lock. In the latter case the function raises an
1269 * ImportError instead of blocking.
1270 *
1271 * Returns the module object with incremented ref count.
1272 */
1273PyObject *
1274PyImport_ImportModuleNoBlock(const char *name)
1275{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001276 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001277}
1278
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001279
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001280/* Remove importlib frames from the traceback,
1281 * except in Verbose mode. */
1282static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001283remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001284{
1285 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001286 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001287 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001288 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001289 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001290 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001291 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001292
1293 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001294 from the traceback. We always trim chunks
1295 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001296
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001297 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001298 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001299 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001300 }
1301
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001302 if (PyType_IsSubtype((PyTypeObject *) exception,
1303 (PyTypeObject *) PyExc_ImportError))
1304 always_trim = 1;
1305
1306 prev_link = &base_tb;
1307 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001308 while (tb != NULL) {
1309 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1310 PyObject *next = (PyObject *) traceback->tb_next;
1311 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001312 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001313 int now_in_importlib;
1314
1315 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001316 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1317 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001318 if (now_in_importlib && !in_importlib) {
1319 /* This is the link to this chunk of importlib tracebacks */
1320 outer_link = prev_link;
1321 }
1322 in_importlib = now_in_importlib;
1323
1324 if (in_importlib &&
1325 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001326 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001327 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001328 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001329 prev_link = outer_link;
1330 }
1331 else {
1332 prev_link = (PyObject **) &traceback->tb_next;
1333 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001334 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001335 tb = next;
1336 }
1337done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001338 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001339}
1340
1341
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001342static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001343resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001344{
Brett Cannonfd074152012-04-14 14:10:13 -04001345 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001346 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001347 _Py_IDENTIFIER(parent);
1348 PyObject *abs_name;
1349 PyObject *package = NULL;
1350 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001351 Py_ssize_t last_dot;
1352 PyObject *base;
1353 int level_up;
1354
1355 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001356 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001357 goto error;
1358 }
1359 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001360 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001361 goto error;
1362 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001363 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001364 if (package == Py_None) {
1365 package = NULL;
1366 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001367 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001368 goto error;
1369 }
1370 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001371 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001372 goto error;
1373 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001374
1375 if (package != NULL) {
1376 Py_INCREF(package);
1377 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001378 _PyErr_SetString(tstate, PyExc_TypeError,
1379 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001380 goto error;
1381 }
1382 else if (spec != NULL && spec != Py_None) {
1383 int equal;
1384 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1385 if (parent == NULL) {
1386 goto error;
1387 }
1388
1389 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1390 Py_DECREF(parent);
1391 if (equal < 0) {
1392 goto error;
1393 }
1394 else if (equal == 0) {
1395 if (PyErr_WarnEx(PyExc_ImportWarning,
1396 "__package__ != __spec__.parent", 1) < 0) {
1397 goto error;
1398 }
1399 }
1400 }
1401 }
1402 else if (spec != NULL && spec != Py_None) {
1403 package = _PyObject_GetAttrId(spec, &PyId_parent);
1404 if (package == NULL) {
1405 goto error;
1406 }
1407 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001408 _PyErr_SetString(tstate, PyExc_TypeError,
1409 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001410 goto error;
1411 }
1412 }
1413 else {
1414 if (PyErr_WarnEx(PyExc_ImportWarning,
1415 "can't resolve package from __spec__ or __package__, "
1416 "falling back on __name__ and __path__", 1) < 0) {
1417 goto error;
1418 }
1419
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001420 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001421 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001422 if (!_PyErr_Occurred(tstate)) {
1423 _PyErr_SetString(tstate, PyExc_KeyError,
1424 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001425 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001426 goto error;
1427 }
1428
1429 Py_INCREF(package);
1430 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001431 _PyErr_SetString(tstate, PyExc_TypeError,
1432 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001433 goto error;
1434 }
1435
Serhiy Storchakab510e102020-10-26 12:47:57 +02001436 int haspath = _PyDict_ContainsId(globals, &PyId___path__);
1437 if (haspath < 0) {
1438 goto error;
1439 }
1440 if (!haspath) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001441 Py_ssize_t dot;
1442
Serhiy Storchakab510e102020-10-26 12:47:57 +02001443 if (PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001444 goto error;
1445 }
1446
1447 dot = PyUnicode_FindChar(package, '.',
1448 0, PyUnicode_GET_LENGTH(package), -1);
1449 if (dot == -2) {
1450 goto error;
1451 }
Ben Lewis92420b32019-09-11 20:09:47 +10001452 else if (dot == -1) {
1453 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001454 }
Ben Lewis92420b32019-09-11 20:09:47 +10001455 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1456 if (substr == NULL) {
1457 goto error;
1458 }
1459 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001460 }
1461 }
1462
1463 last_dot = PyUnicode_GET_LENGTH(package);
1464 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001465 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001466 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001467
1468 for (level_up = 1; level_up < level; level_up += 1) {
1469 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1470 if (last_dot == -2) {
1471 goto error;
1472 }
1473 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001474 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001475 "attempted relative import beyond top-level "
1476 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001477 goto error;
1478 }
1479 }
1480
1481 base = PyUnicode_Substring(package, 0, last_dot);
1482 Py_DECREF(package);
1483 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1484 return base;
1485 }
1486
1487 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1488 Py_DECREF(base);
1489 return abs_name;
1490
Ben Lewis92420b32019-09-11 20:09:47 +10001491 no_parent_error:
1492 _PyErr_SetString(tstate, PyExc_ImportError,
1493 "attempted relative import "
1494 "with no known parent package");
1495
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001496 error:
1497 Py_XDECREF(package);
1498 return NULL;
1499}
1500
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001501static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001502import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001503{
1504 _Py_IDENTIFIER(_find_and_load);
1505 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001506 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001507 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001508 static int import_level;
1509 static _PyTime_t accumulated;
1510
1511 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1512
Steve Dowerb82e17e2019-05-23 08:45:22 -07001513 PyObject *sys_path = PySys_GetObject("path");
1514 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1515 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001516 if (_PySys_Audit(tstate, "import", "OOOOO",
1517 abs_name, Py_None, sys_path ? sys_path : Py_None,
1518 sys_meta_path ? sys_meta_path : Py_None,
1519 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001520 return NULL;
1521 }
1522
1523
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001524 /* XOptions is initialized after first some imports.
1525 * So we can't have negative cache before completed initialization.
1526 * Anyway, importlib._find_and_load is much slower than
1527 * _PyDict_GetItemIdWithError().
1528 */
1529 if (import_time) {
1530 static int header = 1;
1531 if (header) {
1532 fputs("import time: self [us] | cumulative | imported package\n",
1533 stderr);
1534 header = 0;
1535 }
1536
1537 import_level++;
1538 t1 = _PyTime_GetPerfCounter();
1539 accumulated = 0;
1540 }
1541
1542 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001543 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001544
1545 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1546 &PyId__find_and_load, abs_name,
1547 interp->import_func, NULL);
1548
1549 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001550 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001551 mod != NULL);
1552
1553 if (import_time) {
1554 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1555
1556 import_level--;
1557 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1558 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1559 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1560 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1561
1562 accumulated = accumulated_copy + cum;
1563 }
1564
1565 return mod;
1566}
1567
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001568PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001569PyImport_GetModule(PyObject *name)
1570{
1571 PyThreadState *tstate = _PyThreadState_GET();
1572 PyObject *mod;
1573
1574 mod = import_get_module(tstate, name);
1575 if (mod != NULL && mod != Py_None) {
1576 if (import_ensure_initialized(tstate, mod, name) < 0) {
1577 Py_DECREF(mod);
1578 remove_importlib_frames(tstate);
1579 return NULL;
1580 }
1581 }
1582 return mod;
1583}
1584
1585PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001586PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1587 PyObject *locals, PyObject *fromlist,
1588 int level)
1589{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001590 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001591 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001592 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001593 PyObject *final_mod = NULL;
1594 PyObject *mod = NULL;
1595 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001596 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001597 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001598
Brett Cannonfd074152012-04-14 14:10:13 -04001599 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001600 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001601 goto error;
1602 }
1603
1604 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1605 for added performance. */
1606
1607 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001608 _PyErr_SetString(tstate, PyExc_TypeError,
1609 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001610 goto error;
1611 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001612 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001613 goto error;
1614 }
1615 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001616 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001617 goto error;
1618 }
Brett Cannon849113a2016-01-22 15:25:50 -08001619
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001620 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001621 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001622 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001623 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001624 }
1625 else { /* level == 0 */
1626 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001627 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001628 goto error;
1629 }
Brett Cannonfd074152012-04-14 14:10:13 -04001630 abs_name = name;
1631 Py_INCREF(abs_name);
1632 }
1633
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001634 mod = import_get_module(tstate, abs_name);
1635 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001636 goto error;
1637 }
1638
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001639 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001640 if (import_ensure_initialized(tstate, mod, name) < 0) {
1641 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001642 }
Brett Cannonfd074152012-04-14 14:10:13 -04001643 }
1644 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001645 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001646 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001647 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001648 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001649 }
1650 }
1651
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001652 has_from = 0;
1653 if (fromlist != NULL && fromlist != Py_None) {
1654 has_from = PyObject_IsTrue(fromlist);
1655 if (has_from < 0)
1656 goto error;
1657 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001658 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001659 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1660 if (level == 0 || len > 0) {
1661 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001662
Victor Stinner744c34e2016-05-20 11:36:13 +02001663 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1664 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001665 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001666 }
1667
Victor Stinner744c34e2016-05-20 11:36:13 +02001668 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001669 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001670 final_mod = mod;
1671 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001672 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001673 }
1674
Brett Cannonfd074152012-04-14 14:10:13 -04001675 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001676 PyObject *front = PyUnicode_Substring(name, 0, dot);
1677 if (front == NULL) {
1678 goto error;
1679 }
1680
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001681 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001682 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001683 }
1684 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001685 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001686 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001687 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001688 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001689 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001690 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001691 }
Brett Cannonfd074152012-04-14 14:10:13 -04001692
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001693 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001694 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001695 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001696 if (!_PyErr_Occurred(tstate)) {
1697 _PyErr_Format(tstate, PyExc_KeyError,
1698 "%R not in sys.modules as expected",
1699 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001700 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001701 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001702 }
Brett Cannonfd074152012-04-14 14:10:13 -04001703 }
1704 }
1705 else {
1706 final_mod = mod;
1707 Py_INCREF(mod);
1708 }
1709 }
1710 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001711 PyObject *path;
1712 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1713 goto error;
1714 }
1715 if (path) {
1716 Py_DECREF(path);
1717 final_mod = _PyObject_CallMethodIdObjArgs(
1718 interp->importlib, &PyId__handle_fromlist,
1719 mod, fromlist, interp->import_func, NULL);
1720 }
1721 else {
1722 final_mod = mod;
1723 Py_INCREF(mod);
1724 }
Brett Cannonfd074152012-04-14 14:10:13 -04001725 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001726
Brett Cannonfd074152012-04-14 14:10:13 -04001727 error:
1728 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001729 Py_XDECREF(mod);
1730 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001731 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001732 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001733 }
Brett Cannonfd074152012-04-14 14:10:13 -04001734 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001735}
1736
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001737PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001738PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001739 PyObject *fromlist, int level)
1740{
1741 PyObject *nameobj, *mod;
1742 nameobj = PyUnicode_FromString(name);
1743 if (nameobj == NULL)
1744 return NULL;
1745 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1746 fromlist, level);
1747 Py_DECREF(nameobj);
1748 return mod;
1749}
1750
1751
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001752/* Re-import a module of any kind and return its module object, WITH
1753 INCREMENTED REFERENCE COUNT */
1754
Guido van Rossum79f25d91997-04-29 20:08:16 +00001755PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001756PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001757{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001758 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001759 _Py_IDENTIFIER(reload);
1760 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001761 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1762 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001763 if (PyErr_Occurred()) {
1764 return NULL;
1765 }
1766
Robert Rouhanif40bd462020-05-01 16:28:06 -07001767 importlib = PyImport_ImportModule("importlib");
1768 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001769 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001772
Robert Rouhanif40bd462020-05-01 16:28:06 -07001773 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
1774 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001775 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776}
1777
1778
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001779/* Higher-level import emulator which emulates the "import" statement
1780 more accurately -- it invokes the __import__() function from the
1781 builtins of the current globals. This means that the import is
1782 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001783 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001784 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001785 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001786 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001787
1788PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001789PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001790{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001791 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 static PyObject *silly_list = NULL;
1793 static PyObject *builtins_str = NULL;
1794 static PyObject *import_str = NULL;
1795 PyObject *globals = NULL;
1796 PyObject *import = NULL;
1797 PyObject *builtins = NULL;
1798 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 /* Initialize constant string objects */
1801 if (silly_list == NULL) {
1802 import_str = PyUnicode_InternFromString("__import__");
1803 if (import_str == NULL)
1804 return NULL;
1805 builtins_str = PyUnicode_InternFromString("__builtins__");
1806 if (builtins_str == NULL)
1807 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001808 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (silly_list == NULL)
1810 return NULL;
1811 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 /* Get the builtins from current globals */
1814 globals = PyEval_GetGlobals();
1815 if (globals != NULL) {
1816 Py_INCREF(globals);
1817 builtins = PyObject_GetItem(globals, builtins_str);
1818 if (builtins == NULL)
1819 goto err;
1820 }
1821 else {
1822 /* No globals -- use standard builtins, and fake globals */
1823 builtins = PyImport_ImportModuleLevel("builtins",
1824 NULL, NULL, NULL, 0);
1825 if (builtins == NULL)
1826 return NULL;
1827 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1828 if (globals == NULL)
1829 goto err;
1830 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 /* Get the __import__ function from the builtins */
1833 if (PyDict_Check(builtins)) {
1834 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001835 if (import == NULL) {
1836 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
1837 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 }
1839 else
1840 import = PyObject_GetAttr(builtins, import_str);
1841 if (import == NULL)
1842 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001845 Always use absolute import here.
1846 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1848 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001849 if (r == NULL)
1850 goto err;
1851 Py_DECREF(r);
1852
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001853 r = import_get_module(tstate, module_name);
1854 if (r == NULL && !_PyErr_Occurred(tstate)) {
1855 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001856 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001857
1858 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 Py_XDECREF(globals);
1860 Py_XDECREF(builtins);
1861 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001864}
1865
Brett Cannon4caa61d2014-01-09 19:03:32 -05001866/*[clinic input]
1867_imp.extension_suffixes
1868
1869Returns the list of file suffixes used to identify extension modules.
1870[clinic start generated code]*/
1871
Brett Cannon4caa61d2014-01-09 19:03:32 -05001872static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001873_imp_extension_suffixes_impl(PyObject *module)
1874/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 list = PyList_New(0);
1879 if (list == NULL)
1880 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001881#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01001882 const char *suffix;
1883 unsigned int index = 0;
1884
Brett Cannon2657df42012-05-04 15:20:40 -04001885 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1886 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (item == NULL) {
1888 Py_DECREF(list);
1889 return NULL;
1890 }
1891 if (PyList_Append(list, item) < 0) {
1892 Py_DECREF(list);
1893 Py_DECREF(item);
1894 return NULL;
1895 }
1896 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001897 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 }
Brett Cannon2657df42012-05-04 15:20:40 -04001899#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001901}
1902
Brett Cannon4caa61d2014-01-09 19:03:32 -05001903/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001904_imp.init_frozen
1905
1906 name: unicode
1907 /
1908
1909Initializes a frozen module.
1910[clinic start generated code]*/
1911
Brett Cannon4caa61d2014-01-09 19:03:32 -05001912static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001913_imp_init_frozen_impl(PyObject *module, PyObject *name)
1914/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001915{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001916 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 int ret;
1918 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001919
Victor Stinner53dc7352011-03-20 01:50:21 +01001920 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 if (ret < 0)
1922 return NULL;
1923 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001924 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001926 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 Py_XINCREF(m);
1928 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001929}
1930
Brett Cannon4caa61d2014-01-09 19:03:32 -05001931/*[clinic input]
1932_imp.get_frozen_object
1933
1934 name: unicode
1935 /
1936
1937Create a code object for a frozen module.
1938[clinic start generated code]*/
1939
Brett Cannon4caa61d2014-01-09 19:03:32 -05001940static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001941_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1942/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001945}
1946
Brett Cannon4caa61d2014-01-09 19:03:32 -05001947/*[clinic input]
1948_imp.is_frozen_package
1949
1950 name: unicode
1951 /
1952
1953Returns True if the module name is of a frozen package.
1954[clinic start generated code]*/
1955
Brett Cannon4caa61d2014-01-09 19:03:32 -05001956static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001957_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1958/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001961}
1962
Brett Cannon4caa61d2014-01-09 19:03:32 -05001963/*[clinic input]
1964_imp.is_builtin
1965
1966 name: unicode
1967 /
1968
1969Returns True if the module name corresponds to a built-in module.
1970[clinic start generated code]*/
1971
Guido van Rossum79f25d91997-04-29 20:08:16 +00001972static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001973_imp_is_builtin_impl(PyObject *module, PyObject *name)
1974/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001975{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001976 return PyLong_FromLong(is_builtin(name));
1977}
1978
1979/*[clinic input]
1980_imp.is_frozen
1981
1982 name: unicode
1983 /
1984
1985Returns True if the module name corresponds to a frozen module.
1986[clinic start generated code]*/
1987
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001989_imp_is_frozen_impl(PyObject *module, PyObject *name)
1990/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001991{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001992 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 p = find_frozen(name);
1995 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001996}
1997
Larry Hastings1df0b352015-08-24 19:53:56 -07001998/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
1999static int
2000exec_builtin_or_dynamic(PyObject *mod) {
2001 PyModuleDef *def;
2002 void *state;
2003
2004 if (!PyModule_Check(mod)) {
2005 return 0;
2006 }
2007
2008 def = PyModule_GetDef(mod);
2009 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002010 return 0;
2011 }
Brett Cannon52794db2016-09-07 17:00:43 -07002012
Larry Hastings1df0b352015-08-24 19:53:56 -07002013 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002014 if (state) {
2015 /* Already initialized; skip reload */
2016 return 0;
2017 }
Brett Cannon52794db2016-09-07 17:00:43 -07002018
Larry Hastings1df0b352015-08-24 19:53:56 -07002019 return PyModule_ExecDef(mod, def);
2020}
2021
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002022#ifdef HAVE_DYNAMIC_LOADING
2023
Brett Cannon4caa61d2014-01-09 19:03:32 -05002024/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002025_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002026
Nick Coghland5cacbb2015-05-23 22:24:10 +10002027 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002028 file: object = NULL
2029 /
2030
Nick Coghland5cacbb2015-05-23 22:24:10 +10002031Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002032[clinic start generated code]*/
2033
Brett Cannon4caa61d2014-01-09 19:03:32 -05002034static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002035_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2036/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002037{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002038 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002039 FILE *fp;
2040
Nick Coghland5cacbb2015-05-23 22:24:10 +10002041 name = PyObject_GetAttrString(spec, "name");
2042 if (name == NULL) {
2043 return NULL;
2044 }
2045
2046 path = PyObject_GetAttrString(spec, "origin");
2047 if (path == NULL) {
2048 Py_DECREF(name);
2049 return NULL;
2050 }
2051
2052 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002053 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002054 Py_DECREF(name);
2055 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002056 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002057 return mod;
2058 }
2059
Brett Cannon4caa61d2014-01-09 19:03:32 -05002060 if (file != NULL) {
2061 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002062 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002063 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002064 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002066 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002068 else
2069 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002070
2071 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2072
2073 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002074 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (fp)
2076 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002077 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002078}
2079
Nick Coghland5cacbb2015-05-23 22:24:10 +10002080/*[clinic input]
2081_imp.exec_dynamic -> int
2082
2083 mod: object
2084 /
2085
2086Initialize an extension module.
2087[clinic start generated code]*/
2088
2089static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002090_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2091/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002092{
Larry Hastings1df0b352015-08-24 19:53:56 -07002093 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002094}
2095
2096
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002097#endif /* HAVE_DYNAMIC_LOADING */
2098
Larry Hastings7726ac92014-01-31 22:03:12 -08002099/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002100_imp.exec_builtin -> int
2101
2102 mod: object
2103 /
2104
2105Initialize a built-in module.
2106[clinic start generated code]*/
2107
2108static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002109_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2110/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002111{
2112 return exec_builtin_or_dynamic(mod);
2113}
2114
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002115/*[clinic input]
2116_imp.source_hash
2117
2118 key: long
2119 source: Py_buffer
2120[clinic start generated code]*/
2121
2122static PyObject *
2123_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2124/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2125{
Benjamin Peterson83620772017-12-09 12:18:56 -08002126 union {
2127 uint64_t x;
2128 char data[sizeof(uint64_t)];
2129 } hash;
2130 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002131#if !PY_LITTLE_ENDIAN
2132 // Force to little-endian. There really ought to be a succinct standard way
2133 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002134 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2135 char tmp = hash.data[i];
2136 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2137 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002138 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002139#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002140 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002141}
2142
Barry Warsaw28a691b2010-04-17 00:19:56 +00002143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002144PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002145"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002146
Guido van Rossum79f25d91997-04-29 20:08:16 +00002147static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002148 _IMP_EXTENSION_SUFFIXES_METHODDEF
2149 _IMP_LOCK_HELD_METHODDEF
2150 _IMP_ACQUIRE_LOCK_METHODDEF
2151 _IMP_RELEASE_LOCK_METHODDEF
2152 _IMP_GET_FROZEN_OBJECT_METHODDEF
2153 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002154 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002155 _IMP_INIT_FROZEN_METHODDEF
2156 _IMP_IS_BUILTIN_METHODDEF
2157 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002158 _IMP_CREATE_DYNAMIC_METHODDEF
2159 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002160 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002161 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002162 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002163 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002164};
2165
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002166
Martin v. Löwis1a214512008-06-11 05:26:20 +00002167static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002169 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 doc_imp,
2171 0,
2172 imp_methods,
2173 NULL,
2174 NULL,
2175 NULL,
2176 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002177};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002178
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002179PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002180PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002185 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002189 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002191 }
2192
Victor Stinnerda7933e2020-04-13 03:04:28 +02002193 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002194 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002195 if (pyc_mode == NULL) {
2196 goto failure;
2197 }
2198 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2199 Py_DECREF(pyc_mode);
2200 goto failure;
2201 }
2202 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002205 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 Py_XDECREF(m);
2207 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002208}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002209
2210
Guido van Rossumb18618d2000-05-03 23:44:39 +00002211/* API for embedding applications that want to add their own entries
2212 to the table of built-in modules. This should normally be called
2213 *before* Py_Initialize(). When the table resize fails, -1 is
2214 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002215
2216 After a similar function by Just van Rossum. */
2217
2218int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002219PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002222 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002223 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Count the number of entries in both tables */
2226 for (n = 0; newtab[n].name != NULL; n++)
2227 ;
2228 if (n == 0)
2229 return 0; /* Nothing to do */
2230 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2231 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002232
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002233 /* Force default raw memory allocator to get a known allocator to be able
2234 to release the memory in _PyImport_Fini2() */
2235 PyMemAllocatorEx old_alloc;
2236 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002239 p = NULL;
2240 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002241 size_t size = sizeof(struct _inittab) * (i + n + 1);
2242 p = PyMem_RawRealloc(inittab_copy, size);
2243 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002244 if (p == NULL) {
2245 res = -1;
2246 goto done;
2247 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002248
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002249 /* Copy the tables into the new memory at the first call
2250 to PyImport_ExtendInittab(). */
2251 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002253 }
2254 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2255 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002256
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002257done:
2258 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2259 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002260}
2261
2262/* Shorthand to add a single entry given a name and a function */
2263
2264int
Brett Cannona826f322009-04-02 03:41:46 +00002265PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002270
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002271 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002275}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002276
2277#ifdef __cplusplus
2278}
2279#endif