blob: 042691d30b0de9382e7d9ca3d54c08fb4845edaa [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"
11#include "pycore_pymem.h"
Victor Stinner4a3fe082020-04-14 14:26:24 +020012#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
Victor Stinner621cebe2018-11-12 16:53:38 +010013#include "pycore_pystate.h"
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"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020018#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000019#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000020#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020021#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000022
Guido van Rossum55a83382000-09-20 20:31:38 +000023#ifdef HAVE_FCNTL_H
24#include <fcntl.h>
25#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000027extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000028#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000029
Barry Warsaw28a691b2010-04-17 00:19:56 +000030#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000031
Victor Stinner0a28f8d2019-06-19 02:54:39 +020032/* Forward references */
33static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
34
Victor Stinner95872862011-03-07 18:20:56 +010035/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000036static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000037
Guido van Rossum771c6c81997-10-31 18:37:24 +000038/* This table is defined in config.c: */
39extern struct _inittab _PyImport_Inittab[];
40
41struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010042static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000043
Hai Shi46874c22020-01-30 17:20:25 -060044_Py_IDENTIFIER(__path__);
45_Py_IDENTIFIER(__spec__);
46
Brett Cannon4caa61d2014-01-09 19:03:32 -050047/*[clinic input]
48module _imp
49[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030050/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040051
52#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050053
Guido van Rossum1ae940a1995-01-02 19:04:15 +000054/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055
Victor Stinner331a6a52019-05-27 16:39:22 +020056PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020057_PyImportHooks_Init(PyThreadState *tstate)
Just van Rossum52e14d62002-12-30 22:08:05 +000058{
Brett Cannonfd074152012-04-14 14:10:13 -040059 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000061
Brett Cannonfd074152012-04-14 14:10:13 -040062 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 v = PyList_New(0);
64 if (v == NULL)
65 goto error;
66 err = PySys_SetObject("meta_path", v);
67 Py_DECREF(v);
68 if (err)
69 goto error;
70 v = PyDict_New();
71 if (v == NULL)
72 goto error;
73 err = PySys_SetObject("path_importer_cache", v);
74 Py_DECREF(v);
75 if (err)
76 goto error;
77 path_hooks = PyList_New(0);
78 if (path_hooks == NULL)
79 goto error;
80 err = PySys_SetObject("path_hooks", path_hooks);
81 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080082 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 }
Brett Cannonfd074152012-04-14 14:10:13 -040084 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020085 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086
87 error:
Victor Stinnerb45d2592019-06-20 00:05:23 +020088 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020089 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080090 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040091}
92
Victor Stinner331a6a52019-05-27 16:39:22 +020093PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020094_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040095{
ukwksk5e6312c2018-05-15 04:10:52 +090096 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040097 int err = 0;
98
99 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200100 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200101 _PyErr_SetString(tstate, PyExc_RuntimeError,
102 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400103 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200104 }
Brett Cannonfd074152012-04-14 14:10:13 -0400105
Victor Stinnerda7933e2020-04-13 03:04:28 +0200106 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200107 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400108 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200109 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000110
ukwksk5e6312c2018-05-15 04:10:52 +0900111 zipimport = PyImport_ImportModule("zipimport");
112 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200113 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200114 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 }
118 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200119 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900120 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200121 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900122 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200124 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200125 if (verbose) {
126 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
129 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400130 /* sys.path_hooks.insert(0, zipimporter) */
131 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400133 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400135 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200136 if (verbose) {
137 PySys_WriteStderr("# installed zipimport hook\n");
138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 }
140 }
Brett Cannonfd074152012-04-14 14:10:13 -0400141
Victor Stinner331a6a52019-05-27 16:39:22 +0200142 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400143
144 error:
145 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200146 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000147}
148
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000149/* Locking primitives to prevent parallel imports of the same module
150 in different threads to return with a partially loaded module.
151 These calls are serialized by the global interpreter lock. */
152
Guido van Rossum49b56061998-10-01 20:42:43 +0000153#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154
Guido van Rossum65d5b571998-12-21 19:32:43 +0000155static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200156static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000157static int import_lock_level = 0;
158
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000159void
160_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000161{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200162 unsigned long me = PyThread_get_thread_ident();
163 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 return; /* Too bad */
165 if (import_lock == NULL) {
166 import_lock = PyThread_allocate_lock();
167 if (import_lock == NULL)
168 return; /* Nothing much we can do. */
169 }
170 if (import_lock_thread == me) {
171 import_lock_level++;
172 return;
173 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200174 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
175 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 {
177 PyThreadState *tstate = PyEval_SaveThread();
178 PyThread_acquire_lock(import_lock, 1);
179 PyEval_RestoreThread(tstate);
180 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100181 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 import_lock_thread = me;
183 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000184}
185
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000186int
187_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000188{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200189 unsigned long me = PyThread_get_thread_ident();
190 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 return 0; /* Too bad */
192 if (import_lock_thread != me)
193 return -1;
194 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100195 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200197 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 PyThread_release_lock(import_lock);
199 }
200 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000201}
202
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200203/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000204 created child processes do not share locks with the parent.
205 We now acquire the import lock around fork() calls but on some platforms
206 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000207
208void
209_PyImport_ReInitLock(void)
210{
Christian Heimes418fd742015-04-19 21:08:42 +0200211 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200213 if (import_lock == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100214 _Py_FatalErrorFunc(__func__, "failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200215 }
216 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000217 if (import_lock_level > 1) {
218 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200219 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500220 /* The following could fail if the lock is already held, but forking as
221 a side-effect of an import is a) rare, b) nuts, and c) difficult to
222 do thanks to the lock only being held when doing individual module
223 locks per import. */
224 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000225 import_lock_thread = me;
226 import_lock_level--;
227 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200228 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000229 import_lock_level = 0;
230 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000231}
232
Brett Cannon4caa61d2014-01-09 19:03:32 -0500233/*[clinic input]
234_imp.lock_held
235
236Return True if the import lock is currently held, else False.
237
238On platforms without threads, return False.
239[clinic start generated code]*/
240
Brett Cannon4caa61d2014-01-09 19:03:32 -0500241static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300242_imp_lock_held_impl(PyObject *module)
243/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000244{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200245 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000246}
247
Brett Cannon4caa61d2014-01-09 19:03:32 -0500248/*[clinic input]
249_imp.acquire_lock
250
251Acquires the interpreter's import lock for the current thread.
252
253This lock should be used by import hooks to ensure thread-safety when importing
254modules. On platforms without threads, this function does nothing.
255[clinic start generated code]*/
256
Brett Cannon4caa61d2014-01-09 19:03:32 -0500257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300258_imp_acquire_lock_impl(PyObject *module)
259/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200262 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000263}
264
Brett Cannon4caa61d2014-01-09 19:03:32 -0500265/*[clinic input]
266_imp.release_lock
267
268Release the interpreter's import lock.
269
270On platforms without threads, this function does nothing.
271[clinic start generated code]*/
272
Brett Cannon4caa61d2014-01-09 19:03:32 -0500273static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300274_imp_release_lock_impl(PyObject *module)
275/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (_PyImport_ReleaseLock() < 0) {
278 PyErr_SetString(PyExc_RuntimeError,
279 "not holding the import lock");
280 return NULL;
281 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200282 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000283}
284
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100285void
286_PyImport_Fini(void)
287{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200288 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100289 if (import_lock != NULL) {
290 PyThread_free_lock(import_lock);
291 import_lock = NULL;
292 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100293}
294
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100295void
296_PyImport_Fini2(void)
297{
298 /* Use the same memory allocator than PyImport_ExtendInittab(). */
299 PyMemAllocatorEx old_alloc;
300 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
301
302 /* Free memory allocated by PyImport_ExtendInittab() */
303 PyMem_RawFree(inittab_copy);
304
305 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
306}
307
Guido van Rossum25ce5661997-08-02 03:10:38 +0000308/* Helper for sys */
309
310PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000311PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000312{
Victor Stinner81a7be32020-04-14 15:14:01 +0200313 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600314 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100315 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600316 }
Eric Snow93c92f72017-09-13 23:46:04 -0700317 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318}
319
Eric Snowd393c1b2017-09-14 12:18:12 -0600320/* In some corner cases it is important to be sure that the import
321 machinery has been initialized (or not cleaned up yet). For
322 example, see issue #4236 and PyModule_Create2(). */
323
324int
325_PyImport_IsInitialized(PyInterpreterState *interp)
326{
327 if (interp->modules == NULL)
328 return 0;
329 return 1;
330}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000331
Eric Snow3f9eee62017-09-15 16:35:20 -0600332PyObject *
333_PyImport_GetModuleId(struct _Py_Identifier *nameid)
334{
335 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
336 if (name == NULL) {
337 return NULL;
338 }
339 return PyImport_GetModule(name);
340}
341
342int
343_PyImport_SetModule(PyObject *name, PyObject *m)
344{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200345 PyThreadState *tstate = _PyThreadState_GET();
346 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600347 return PyObject_SetItem(modules, name, m);
348}
349
350int
351_PyImport_SetModuleString(const char *name, PyObject *m)
352{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200353 PyThreadState *tstate = _PyThreadState_GET();
354 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600355 return PyMapping_SetItemString(modules, name, m);
356}
357
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200358static PyObject *
359import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600360{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200361 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600362 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200363 _PyErr_SetString(tstate, PyExc_RuntimeError,
364 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600365 return NULL;
366 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200367
368 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600369 Py_INCREF(modules);
370 if (PyDict_CheckExact(modules)) {
371 m = PyDict_GetItemWithError(modules, name); /* borrowed */
372 Py_XINCREF(m);
373 }
374 else {
375 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200376 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
377 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600378 }
379 }
380 Py_DECREF(modules);
381 return m;
382}
383
384
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100385static int
386import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200387{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100388 PyInterpreterState *interp = tstate->interp;
389 PyObject *spec;
390
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100391 _Py_IDENTIFIER(_lock_unlock_module);
392
393 /* Optimization: only call _bootstrap._lock_unlock_module() if
394 __spec__._initializing is true.
395 NOTE: because of this, initializing must be set *before*
396 stuffing the new module in sys.modules.
397 */
398 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
399 int busy = _PyModuleSpec_IsInitializing(spec);
400 Py_XDECREF(spec);
401 if (busy) {
402 /* Wait until module is done importing. */
403 PyObject *value = _PyObject_CallMethodIdOneArg(
404 interp->importlib, &PyId__lock_unlock_module, name);
405 if (value == NULL) {
406 return -1;
407 }
408 Py_DECREF(value);
409 }
410 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200411}
412
413
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000414/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200415static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 "path", "argv", "ps1", "ps2",
417 "last_type", "last_value", "last_traceback",
418 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200419 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000421};
422
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200423static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 "stdin", "__stdin__",
425 "stdout", "__stdout__",
426 "stderr", "__stderr__",
427 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000428};
429
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000430/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000431
Guido van Rossum3f5da241990-12-20 15:06:42 +0000432void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200433_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000434{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200435 PyInterpreterState *interp = tstate->interp;
436 PyObject *modules = interp->modules;
437 if (modules == NULL) {
438 /* Already done */
439 return;
440 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* Delete some special variables first. These are common
443 places where user values hide and people complain when their
444 destructors fail. Since the modules containing them are
445 deleted *last* of all, they would come too late in the normal
446 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000447
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200448 /* XXX Perhaps these precautions are obsolete. Who knows? */
449
Victor Stinnerda7933e2020-04-13 03:04:28 +0200450 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200451 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200452 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200453 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300454 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300455 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300456 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200457
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200458 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200459 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200460 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200461 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200462 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300463 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300464 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200467 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200468 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200469 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200470 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200471 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
472 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200473 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200474 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200475 PyErr_WriteUnraisable(NULL);
476 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200477 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200478 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300479 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300480 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000483
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200484 /* We prepare a list which will receive (name, weakref) tuples of
485 modules when they are removed from sys.modules. The name is used
486 for diagnosis messages (in verbose mode), while the weakref helps
487 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200488 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300489 if (weaklist == NULL) {
490 PyErr_WriteUnraisable(NULL);
491 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200492
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200493#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200494 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200495 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300496 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200497 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300498 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300499 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300500 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200501 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300502 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200503 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300504 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300505 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300506 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600508#define CLEAR_MODULE(name, mod) \
509 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200510 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600511 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200512 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600513 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300514 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300515 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300516 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600517 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000518
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200519 /* Remove all modules from sys.modules, hoping that garbage collection
520 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600521 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200522 Py_ssize_t pos = 0;
523 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600524 while (PyDict_Next(modules, &pos, &key, &value)) {
525 CLEAR_MODULE(key, value);
526 }
527 }
528 else {
529 PyObject *iterator = PyObject_GetIter(modules);
530 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300531 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600532 }
533 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200534 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600535 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200536 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600537 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300538 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600539 continue;
540 }
541 CLEAR_MODULE(key, value);
542 Py_DECREF(value);
543 Py_DECREF(key);
544 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300545 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300546 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300547 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600548 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 }
550 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000551
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200552 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600553 if (PyDict_CheckExact(modules)) {
554 PyDict_Clear(modules);
555 }
556 else {
557 _Py_IDENTIFIER(clear);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200558 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300559 PyErr_WriteUnraisable(NULL);
560 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600561 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200562 /* Restore the original builtins dict, to ensure that any
563 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200564 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300565 if (dict == NULL) {
566 PyErr_WriteUnraisable(NULL);
567 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200568 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300569 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200570 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300571 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200572 Py_XDECREF(dict);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200573 /* Collect references */
574 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200575 /* Dump GC stats before it's too late, since it uses the warnings
576 machinery. */
Victor Stinner67e0de62019-11-20 11:48:18 +0100577 _PyGC_DumpShutdownStats(tstate);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200578
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200579 /* Now, if there are any modules left alive, clear their globals to
580 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200581 up here, since they are kept alive in the interpreter state.
582
583 The special treatment of "builtins" here is because even
584 when it's not referenced as a module, its dictionary is
585 referenced by almost every module's __builtins__. Since
586 deleting a module clears its dictionary (even if there are
587 references left to it), we need to delete the "builtins"
588 module last. Likewise, we don't delete sys until the very
589 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200590 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200591 Py_ssize_t i;
592 /* Since dict is ordered in CPython 3.6+, modules are saved in
593 importing order. First clear modules imported later. */
594 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200595 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200596 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200597 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
598 if (mod == Py_None)
599 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200600 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200601 dict = PyModule_GetDict(mod);
602 if (dict == interp->builtins || dict == interp->sysdict)
603 continue;
604 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200605 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200606 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200607 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200608 _PyModule_Clear(mod);
609 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200610 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200611 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000613
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200614 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200615 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200616 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200617 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200618 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200619 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200620 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200621 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200622 _PyModule_ClearDict(interp->builtins);
623
Eddie Elizondo4590f722020-02-04 02:29:25 -0800624 /* Clear module dict copies stored in the interpreter state */
625 _PyInterpreterState_ClearModules(interp);
626
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200627 /* Clear and delete the modules directory. Actual modules will
628 still be there only if imported during the execution of some
629 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700630 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200632
633 /* Once more */
634 _PyGC_CollectNoFail();
635
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300636#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200637#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000638}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000639
640
Barry Warsaw28a691b2010-04-17 00:19:56 +0000641/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000642
643long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000645{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200646 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200647 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600648 PyObject *external, *pyc_magic;
649
650 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
651 if (external == NULL)
652 return -1;
653 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
654 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400655 if (pyc_magic == NULL)
656 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200657 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700658 Py_DECREF(pyc_magic);
659 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000660}
661
662
Brett Cannon3adc7b72012-07-09 14:22:12 -0400663extern const char * _PySys_ImplCacheTag;
664
Barry Warsaw28a691b2010-04-17 00:19:56 +0000665const char *
666PyImport_GetMagicTag(void)
667{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400668 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000669}
670
Brett Cannon98979b82012-07-02 15:13:11 -0400671
Guido van Rossum25ce5661997-08-02 03:10:38 +0000672/* Magic for extension modules (built-in as well as dynamically
673 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200674 once, we keep a static dictionary 'extensions' keyed by the tuple
675 (module name, module name) (for built-in modules) or by
676 (filename, module name) (for dynamically loaded modules), containing these
677 modules. A copy of the module's dictionary is stored by calling
678 _PyImport_FixupExtensionObject() immediately after the module initialization
679 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100680 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000681
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000682 Modules which do support multiple initialization set their m_size
683 field to a non-negative number (indicating the size of the
684 module-specific state). They are still recorded in the extensions
685 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000686*/
687
688int
Victor Stinner95872862011-03-07 18:20:56 +0100689_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200690 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (mod == NULL || !PyModule_Check(mod)) {
693 PyErr_BadInternalCall();
694 return -1;
695 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100696
697 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (!def) {
699 PyErr_BadInternalCall();
700 return -1;
701 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100702
703 PyThreadState *tstate = _PyThreadState_GET();
704 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100706 }
707 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600708 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 return -1;
710 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100711
712 if (_Py_IsMainInterpreter(tstate)) {
713 if (def->m_size == -1) {
714 if (def->m_base.m_copy) {
715 /* Somebody already imported the module,
716 likely under a different name.
717 XXX this should really not happen. */
718 Py_CLEAR(def->m_base.m_copy);
719 }
720 PyObject *dict = PyModule_GetDict(mod);
721 if (dict == NULL) {
722 return -1;
723 }
724 def->m_base.m_copy = PyDict_Copy(dict);
725 if (def->m_base.m_copy == NULL) {
726 return -1;
727 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100729
730 if (extensions == NULL) {
731 extensions = PyDict_New();
732 if (extensions == NULL) {
733 return -1;
734 }
735 }
736
737 PyObject *key = PyTuple_Pack(2, filename, name);
738 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100740 }
741 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
742 Py_DECREF(key);
743 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100745 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000749}
750
Victor Stinner49d3f252010-10-17 01:24:53 +0000751int
Eric Snowd393c1b2017-09-14 12:18:12 -0600752_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000753{
754 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100755 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100756 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100757 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000758 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600759 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100760 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000761 return res;
762}
763
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200764static PyObject *
765import_find_extension(PyThreadState *tstate, PyObject *name,
766 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000767{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200768 if (extensions == NULL) {
769 return NULL;
770 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600771
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200772 PyObject *key = PyTuple_Pack(2, filename, name);
773 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200775 }
776 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500777 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200778 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200780 }
781
782 PyObject *mod, *mdict;
783 PyObject *modules = tstate->interp->modules;
784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (def->m_size == -1) {
786 /* Module does not support repeated initialization */
787 if (def->m_base.m_copy == NULL)
788 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200789 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (mod == NULL)
791 return NULL;
792 mdict = PyModule_GetDict(mod);
793 if (mdict == NULL)
794 return NULL;
795 if (PyDict_Update(mdict, def->m_base.m_copy))
796 return NULL;
797 }
798 else {
799 if (def->m_base.m_init == NULL)
800 return NULL;
801 mod = def->m_base.m_init();
802 if (mod == NULL)
803 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600804 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200805 Py_DECREF(mod);
806 return NULL;
807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_DECREF(mod);
809 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100810 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600811 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return NULL;
813 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200814
Victor Stinnerda7933e2020-04-13 03:04:28 +0200815 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200816 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100817 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200818 name, filename);
819 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000821}
822
Victor Stinner49d3f252010-10-17 01:24:53 +0000823PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200824_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
825{
826 PyThreadState *tstate = _PyThreadState_GET();
827 return import_find_extension(tstate, name, filename);
828}
829
830
831PyObject *
832_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000833{
Victor Stinner95872862011-03-07 18:20:56 +0100834 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100835 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100836 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000837 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200838 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100839 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000840 return res;
841}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000842
843/* Get the module object corresponding to a module name.
844 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000845 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000846 Because the former action is most common, THIS DOES NOT RETURN A
847 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000848
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200849static PyObject *
850import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000851{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200852 PyObject *modules = tstate->interp->modules;
853 if (modules == NULL) {
854 _PyErr_SetString(tstate, PyExc_RuntimeError,
855 "no import module dictionary");
856 return NULL;
857 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600858
Eric Snow86b7afd2017-09-04 17:54:09 -0600859 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600860 if (PyDict_CheckExact(modules)) {
861 m = PyDict_GetItemWithError(modules, name);
862 }
863 else {
864 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000865 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600866 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200867 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
868 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600869 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200870 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200871 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200872 return NULL;
873 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600874 if (m != NULL && PyModule_Check(m)) {
875 return m;
876 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000877 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (m == NULL)
879 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600880 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 Py_DECREF(m);
882 return NULL;
883 }
884 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000887}
888
Victor Stinner27ee0892011-03-04 12:57:09 +0000889PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200890PyImport_AddModuleObject(PyObject *name)
891{
892 PyThreadState *tstate = _PyThreadState_GET();
893 return import_add_module(tstate, name);
894}
895
896
897PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000898PyImport_AddModule(const char *name)
899{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200900 PyObject *nameobj = PyUnicode_FromString(name);
901 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000902 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200903 }
904 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000905 Py_DECREF(nameobj);
906 return module;
907}
908
909
Tim Peters1cd70172004-08-02 03:52:12 +0000910/* Remove name from sys.modules, if it's there. */
911static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200912remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000913{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600914 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200915 _PyErr_Fetch(tstate, &type, &value, &traceback);
916
917 PyObject *modules = tstate->interp->modules;
Zackery Spytz94a64e92019-05-08 10:31:23 -0600918 if (!PyMapping_HasKey(modules, name)) {
919 goto out;
920 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600921 if (PyMapping_DelItem(modules, name) < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200922 _PyErr_SetString(tstate, PyExc_RuntimeError,
923 "deleting key in sys.modules failed");
924 _PyErr_ChainExceptions(type, value, traceback);
925 return;
Eric Snow3f9eee62017-09-15 16:35:20 -0600926 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200927
Zackery Spytz94a64e92019-05-08 10:31:23 -0600928out:
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200929 _PyErr_Restore(tstate, type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000930}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931
Christian Heimes3b06e532008-01-07 20:12:44 +0000932
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000933/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000934 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
935 * removed from sys.modules, to avoid leaving damaged module objects
936 * in sys.modules. The caller may wish to restore the original
937 * module object (if any) in this case; PyImport_ReloadModule is an
938 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000939 *
940 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
941 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000942 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000943PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300944PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 return PyImport_ExecCodeModuleWithPathnames(
947 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000948}
949
950PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300951PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return PyImport_ExecCodeModuleWithPathnames(
954 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000955}
956
957PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300958PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
959 const char *pathname,
960 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000961{
Victor Stinner27ee0892011-03-04 12:57:09 +0000962 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600963 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000964
965 nameobj = PyUnicode_FromString(name);
966 if (nameobj == NULL)
967 return NULL;
968
Victor Stinner27ee0892011-03-04 12:57:09 +0000969 if (cpathname != NULL) {
970 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
971 if (cpathobj == NULL)
972 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400973 }
974 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000975 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400976
977 if (pathname != NULL) {
978 pathobj = PyUnicode_DecodeFSDefault(pathname);
979 if (pathobj == NULL)
980 goto error;
981 }
982 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200983 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400984 _Py_IDENTIFIER(_get_sourcefile);
985
986 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100987 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400988 }
989
Eric Snow32439d62015-05-02 19:15:18 -0600990 external= PyObject_GetAttrString(interp->importlib,
991 "_bootstrap_external");
992 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200993 pathobj = _PyObject_CallMethodIdOneArg(
994 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600995 Py_DECREF(external);
996 }
Brett Cannona6473f92012-07-13 13:57:03 -0400997 if (pathobj == NULL)
998 PyErr_Clear();
999 }
1000 else
1001 pathobj = NULL;
1002
Victor Stinner27ee0892011-03-04 12:57:09 +00001003 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
1004error:
1005 Py_DECREF(nameobj);
1006 Py_XDECREF(pathobj);
1007 Py_XDECREF(cpathobj);
1008 return m;
1009}
1010
Brett Cannon18fc4e72014-04-04 10:01:46 -04001011static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001012module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +00001013{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001014 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001015 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001016
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001017 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 if (m == NULL)
1019 return NULL;
1020 /* If the module is being reloaded, we get the old module back
1021 and re-use its dict to exec the new code. */
1022 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001023 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001024 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001025 _PyDict_SetItemId(d, &PyId___builtins__,
1026 PyEval_GetBuiltins()) != 0)
1027 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001028 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001029 return NULL;
1030 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001032
Eric Snow08197a42014-05-12 17:54:55 -06001033 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001034}
1035
1036static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001037exec_code_in_module(PyThreadState *tstate, PyObject *name,
1038 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001039{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001040 PyObject *v, *m;
1041
1042 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1043 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001044 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001045 return NULL;
1046 }
1047 Py_DECREF(v);
1048
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001049 m = import_get_module(tstate, name);
1050 if (m == NULL && !_PyErr_Occurred(tstate)) {
1051 _PyErr_Format(tstate, PyExc_ImportError,
1052 "Loaded module %R not found in sys.modules",
1053 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001054 }
1055
Brett Cannon18fc4e72014-04-04 10:01:46 -04001056 return m;
1057}
1058
1059PyObject*
1060PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1061 PyObject *cpathname)
1062{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001063 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001064 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001065 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001066
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001067 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001068 if (d == NULL) {
1069 return NULL;
1070 }
1071
Eric Snow08197a42014-05-12 17:54:55 -06001072 if (pathname == NULL) {
1073 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001075 external = PyObject_GetAttrString(tstate->interp->importlib,
1076 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001077 if (external == NULL)
1078 return NULL;
1079 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001080 &PyId__fix_up_module,
1081 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001082 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001083 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001084 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001085 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
Eric Snow08197a42014-05-12 17:54:55 -06001087 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001088}
1089
1090
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001091static void
1092update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *constants, *tmp;
1095 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (PyUnicode_Compare(co->co_filename, oldname))
1098 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001099
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001100 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001101 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 constants = co->co_consts;
1104 n = PyTuple_GET_SIZE(constants);
1105 for (i = 0; i < n; i++) {
1106 tmp = PyTuple_GET_ITEM(constants, i);
1107 if (PyCode_Check(tmp))
1108 update_code_filenames((PyCodeObject *)tmp,
1109 oldname, newname);
1110 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001111}
1112
Victor Stinner2f42ae52011-03-20 00:41:24 +01001113static void
1114update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001115{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001116 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001117
Victor Stinner2f42ae52011-03-20 00:41:24 +01001118 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1119 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 oldname = co->co_filename;
1122 Py_INCREF(oldname);
1123 update_code_filenames(co, oldname, newname);
1124 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001125}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001126
Brett Cannon4caa61d2014-01-09 19:03:32 -05001127/*[clinic input]
1128_imp._fix_co_filename
1129
1130 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1131 Code object to change.
1132
1133 path: unicode
1134 File path to use.
1135 /
1136
1137Changes code.co_filename to specify the passed-in file path.
1138[clinic start generated code]*/
1139
Brett Cannon4caa61d2014-01-09 19:03:32 -05001140static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001141_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001142 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001143/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001144
Brett Cannon4caa61d2014-01-09 19:03:32 -05001145{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001146 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001147
1148 Py_RETURN_NONE;
1149}
1150
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001151
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001152/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001153static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001154
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001155
1156/* Helper to test for built-in module */
1157
1158static int
Victor Stinner95872862011-03-07 18:20:56 +01001159is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001160{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001161 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001163 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (PyImport_Inittab[i].initfunc == NULL)
1165 return -1;
1166 else
1167 return 1;
1168 }
1169 }
1170 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001171}
1172
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001173
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001174/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001175 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001176 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001177 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001178 this tells our caller that the path based finder could not find
1179 a finder for this path item. Cache the result in
1180 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001181 Returns a borrowed reference. */
1182
1183static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001184get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1185 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 PyObject *importer;
1188 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 /* These conditions are the caller's responsibility: */
1191 assert(PyList_Check(path_hooks));
1192 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 nhooks = PyList_Size(path_hooks);
1195 if (nhooks < 0)
1196 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001197
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001198 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001199 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 /* set path_importer_cache[p] to None to avoid recursion */
1203 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1204 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 for (j = 0; j < nhooks; j++) {
1207 PyObject *hook = PyList_GetItem(path_hooks, j);
1208 if (hook == NULL)
1209 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +01001210 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (importer != NULL)
1212 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001213
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001214 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 return NULL;
1216 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001217 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 }
1219 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001220 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 }
1222 if (importer != NULL) {
1223 int err = PyDict_SetItem(path_importer_cache, p, importer);
1224 Py_DECREF(importer);
1225 if (err != 0)
1226 return NULL;
1227 }
1228 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001229}
1230
Benjamin Petersone5024512018-09-12 12:06:42 -07001231PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001232PyImport_GetImporter(PyObject *path)
1233{
1234 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001236
Victor Stinner1e53bba2013-07-16 22:26:05 +02001237 path_importer_cache = PySys_GetObject("path_importer_cache");
1238 path_hooks = PySys_GetObject("path_hooks");
1239 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001240 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001241 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 }
1243 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1244 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001245}
1246
Nick Coghland5cacbb2015-05-23 22:24:10 +10001247/*[clinic input]
1248_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001249
Nick Coghland5cacbb2015-05-23 22:24:10 +10001250 spec: object
1251 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001252
Nick Coghland5cacbb2015-05-23 22:24:10 +10001253Create an extension module.
1254[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001255
Nick Coghland5cacbb2015-05-23 22:24:10 +10001256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001257_imp_create_builtin(PyObject *module, PyObject *spec)
1258/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001259{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001260 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001262 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001263 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001264 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001265
Nick Coghland5cacbb2015-05-23 22:24:10 +10001266 name = PyObject_GetAttrString(spec, "name");
1267 if (name == NULL) {
1268 return NULL;
1269 }
1270
Victor Stinner5eb4f592013-11-14 22:38:52 +01001271 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001272 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001273 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001274 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001275 return mod;
1276 }
1277
1278 namestr = PyUnicode_AsUTF8(name);
1279 if (namestr == NULL) {
1280 Py_DECREF(name);
1281 return NULL;
1282 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001283
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001284 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001286 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001287 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001289 /* Cannot re-init internal module ("sys" or "builtins") */
1290 mod = PyImport_AddModule(namestr);
1291 Py_DECREF(name);
1292 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001295 if (mod == NULL) {
1296 Py_DECREF(name);
1297 return NULL;
1298 }
1299 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1300 Py_DECREF(name);
1301 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1302 } else {
1303 /* Remember pointer to module init function. */
1304 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001305 if (def == NULL) {
1306 Py_DECREF(name);
1307 return NULL;
1308 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001309 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001310 if (_PyImport_FixupExtensionObject(mod, name, name,
1311 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001312 Py_DECREF(name);
1313 return NULL;
1314 }
1315 Py_DECREF(name);
1316 return mod;
1317 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 }
1319 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001320 Py_DECREF(name);
1321 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001322}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001323
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001324
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001325/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001326
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001327static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001328find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001329{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001330 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001331
Victor Stinner53dc7352011-03-20 01:50:21 +01001332 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 for (p = PyImport_FrozenModules; ; p++) {
1336 if (p->name == NULL)
1337 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001338 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 break;
1340 }
1341 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001342}
1343
Guido van Rossum79f25d91997-04-29 20:08:16 +00001344static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001345get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001346{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001347 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 if (p == NULL) {
1351 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001352 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 name);
1354 return NULL;
1355 }
1356 if (p->code == NULL) {
1357 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001358 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 name);
1360 return NULL;
1361 }
1362 size = p->size;
1363 if (size < 0)
1364 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001365 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001366}
1367
Brett Cannon8d110132009-03-15 02:20:16 +00001368static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001369is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001370{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001371 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (p == NULL) {
1375 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001376 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 name);
1378 return NULL;
1379 }
Brett Cannon8d110132009-03-15 02:20:16 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (size < 0)
1384 Py_RETURN_TRUE;
1385 else
1386 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001387}
1388
1389
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001390/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001391 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001392 an exception set if the initialization failed.
1393 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001394
1395int
Victor Stinner53dc7352011-03-20 01:50:21 +01001396PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001397{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001398 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001399 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001400 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 int ispackage;
1402 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001403
Victor Stinner53dc7352011-03-20 01:50:21 +01001404 p = find_frozen(name);
1405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (p == NULL)
1407 return 0;
1408 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001409 _PyErr_Format(tstate, PyExc_ImportError,
1410 "Excluded frozen object named %R",
1411 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 return -1;
1413 }
1414 size = p->size;
1415 ispackage = (size < 0);
1416 if (ispackage)
1417 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001418 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (co == NULL)
1420 return -1;
1421 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001422 _PyErr_Format(tstate, PyExc_TypeError,
1423 "frozen object %R is not a code object",
1424 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 goto err_return;
1426 }
1427 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001428 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001429 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001431 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (m == NULL)
1433 goto err_return;
1434 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001435 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 goto err_return;
1438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 err = PyDict_SetItemString(d, "__path__", l);
1440 Py_DECREF(l);
1441 if (err != 0)
1442 goto err_return;
1443 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001444 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001445 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001446 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001447 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001448 m = exec_code_in_module(tstate, name, d, co);
1449 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_DECREF(co);
1453 Py_DECREF(m);
1454 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001455
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001456err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 Py_DECREF(co);
1458 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001459}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001460
Victor Stinner53dc7352011-03-20 01:50:21 +01001461int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001462PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001463{
1464 PyObject *nameobj;
1465 int ret;
1466 nameobj = PyUnicode_InternFromString(name);
1467 if (nameobj == NULL)
1468 return -1;
1469 ret = PyImport_ImportFrozenModuleObject(nameobj);
1470 Py_DECREF(nameobj);
1471 return ret;
1472}
1473
Guido van Rossum74e6a111994-08-29 12:54:38 +00001474
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001475/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001476 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001477
Guido van Rossum79f25d91997-04-29 20:08:16 +00001478PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001479PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyObject *pname;
1482 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 pname = PyUnicode_FromString(name);
1485 if (pname == NULL)
1486 return NULL;
1487 result = PyImport_Import(pname);
1488 Py_DECREF(pname);
1489 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001490}
1491
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001492
Christian Heimes072c0f12008-01-03 23:01:04 +00001493/* Import a module without blocking
1494 *
1495 * At first it tries to fetch the module from sys.modules. If the module was
1496 * never loaded before it loads it with PyImport_ImportModule() unless another
1497 * thread holds the import lock. In the latter case the function raises an
1498 * ImportError instead of blocking.
1499 *
1500 * Returns the module object with incremented ref count.
1501 */
1502PyObject *
1503PyImport_ImportModuleNoBlock(const char *name)
1504{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001505 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001506}
1507
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001508
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001509/* Remove importlib frames from the traceback,
1510 * except in Verbose mode. */
1511static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001512remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001513{
1514 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001515 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001516 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001517 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001518 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001519 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001520 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001521
1522 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001523 from the traceback. We always trim chunks
1524 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001525
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001526 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001527 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001528 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001529 }
1530
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001531 if (PyType_IsSubtype((PyTypeObject *) exception,
1532 (PyTypeObject *) PyExc_ImportError))
1533 always_trim = 1;
1534
1535 prev_link = &base_tb;
1536 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001537 while (tb != NULL) {
1538 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1539 PyObject *next = (PyObject *) traceback->tb_next;
1540 PyFrameObject *frame = traceback->tb_frame;
1541 PyCodeObject *code = frame->f_code;
1542 int now_in_importlib;
1543
1544 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001545 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1546 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001547 if (now_in_importlib && !in_importlib) {
1548 /* This is the link to this chunk of importlib tracebacks */
1549 outer_link = prev_link;
1550 }
1551 in_importlib = now_in_importlib;
1552
1553 if (in_importlib &&
1554 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001555 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001556 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001557 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001558 prev_link = outer_link;
1559 }
1560 else {
1561 prev_link = (PyObject **) &traceback->tb_next;
1562 }
1563 tb = next;
1564 }
1565done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001566 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001567}
1568
1569
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001570static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001571resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001572{
Brett Cannonfd074152012-04-14 14:10:13 -04001573 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001574 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001575 _Py_IDENTIFIER(parent);
1576 PyObject *abs_name;
1577 PyObject *package = NULL;
1578 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001579 Py_ssize_t last_dot;
1580 PyObject *base;
1581 int level_up;
1582
1583 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001584 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001585 goto error;
1586 }
1587 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001588 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001589 goto error;
1590 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001591 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001592 if (package == Py_None) {
1593 package = NULL;
1594 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001595 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001596 goto error;
1597 }
1598 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001599 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001600 goto error;
1601 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001602
1603 if (package != NULL) {
1604 Py_INCREF(package);
1605 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001606 _PyErr_SetString(tstate, PyExc_TypeError,
1607 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001608 goto error;
1609 }
1610 else if (spec != NULL && spec != Py_None) {
1611 int equal;
1612 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1613 if (parent == NULL) {
1614 goto error;
1615 }
1616
1617 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1618 Py_DECREF(parent);
1619 if (equal < 0) {
1620 goto error;
1621 }
1622 else if (equal == 0) {
1623 if (PyErr_WarnEx(PyExc_ImportWarning,
1624 "__package__ != __spec__.parent", 1) < 0) {
1625 goto error;
1626 }
1627 }
1628 }
1629 }
1630 else if (spec != NULL && spec != Py_None) {
1631 package = _PyObject_GetAttrId(spec, &PyId_parent);
1632 if (package == NULL) {
1633 goto error;
1634 }
1635 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001636 _PyErr_SetString(tstate, PyExc_TypeError,
1637 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001638 goto error;
1639 }
1640 }
1641 else {
1642 if (PyErr_WarnEx(PyExc_ImportWarning,
1643 "can't resolve package from __spec__ or __package__, "
1644 "falling back on __name__ and __path__", 1) < 0) {
1645 goto error;
1646 }
1647
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001648 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001649 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001650 if (!_PyErr_Occurred(tstate)) {
1651 _PyErr_SetString(tstate, PyExc_KeyError,
1652 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001653 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001654 goto error;
1655 }
1656
1657 Py_INCREF(package);
1658 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001659 _PyErr_SetString(tstate, PyExc_TypeError,
1660 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001661 goto error;
1662 }
1663
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001664 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001665 Py_ssize_t dot;
1666
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001667 if (_PyErr_Occurred(tstate) || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001668 goto error;
1669 }
1670
1671 dot = PyUnicode_FindChar(package, '.',
1672 0, PyUnicode_GET_LENGTH(package), -1);
1673 if (dot == -2) {
1674 goto error;
1675 }
Ben Lewis92420b32019-09-11 20:09:47 +10001676 else if (dot == -1) {
1677 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001678 }
Ben Lewis92420b32019-09-11 20:09:47 +10001679 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1680 if (substr == NULL) {
1681 goto error;
1682 }
1683 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001684 }
1685 }
1686
1687 last_dot = PyUnicode_GET_LENGTH(package);
1688 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001689 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001690 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001691
1692 for (level_up = 1; level_up < level; level_up += 1) {
1693 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1694 if (last_dot == -2) {
1695 goto error;
1696 }
1697 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001698 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001699 "attempted relative import beyond top-level "
1700 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001701 goto error;
1702 }
1703 }
1704
1705 base = PyUnicode_Substring(package, 0, last_dot);
1706 Py_DECREF(package);
1707 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1708 return base;
1709 }
1710
1711 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1712 Py_DECREF(base);
1713 return abs_name;
1714
Ben Lewis92420b32019-09-11 20:09:47 +10001715 no_parent_error:
1716 _PyErr_SetString(tstate, PyExc_ImportError,
1717 "attempted relative import "
1718 "with no known parent package");
1719
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001720 error:
1721 Py_XDECREF(package);
1722 return NULL;
1723}
1724
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001725static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001726import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001727{
1728 _Py_IDENTIFIER(_find_and_load);
1729 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001730 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001731 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001732 static int import_level;
1733 static _PyTime_t accumulated;
1734
1735 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1736
Steve Dowerb82e17e2019-05-23 08:45:22 -07001737 PyObject *sys_path = PySys_GetObject("path");
1738 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1739 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001740 if (_PySys_Audit(tstate, "import", "OOOOO",
1741 abs_name, Py_None, sys_path ? sys_path : Py_None,
1742 sys_meta_path ? sys_meta_path : Py_None,
1743 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001744 return NULL;
1745 }
1746
1747
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001748 /* XOptions is initialized after first some imports.
1749 * So we can't have negative cache before completed initialization.
1750 * Anyway, importlib._find_and_load is much slower than
1751 * _PyDict_GetItemIdWithError().
1752 */
1753 if (import_time) {
1754 static int header = 1;
1755 if (header) {
1756 fputs("import time: self [us] | cumulative | imported package\n",
1757 stderr);
1758 header = 0;
1759 }
1760
1761 import_level++;
1762 t1 = _PyTime_GetPerfCounter();
1763 accumulated = 0;
1764 }
1765
1766 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001767 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001768
1769 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1770 &PyId__find_and_load, abs_name,
1771 interp->import_func, NULL);
1772
1773 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001774 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001775 mod != NULL);
1776
1777 if (import_time) {
1778 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1779
1780 import_level--;
1781 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1782 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1783 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1784 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1785
1786 accumulated = accumulated_copy + cum;
1787 }
1788
1789 return mod;
1790}
1791
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001792PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001793PyImport_GetModule(PyObject *name)
1794{
1795 PyThreadState *tstate = _PyThreadState_GET();
1796 PyObject *mod;
1797
1798 mod = import_get_module(tstate, name);
1799 if (mod != NULL && mod != Py_None) {
1800 if (import_ensure_initialized(tstate, mod, name) < 0) {
1801 Py_DECREF(mod);
1802 remove_importlib_frames(tstate);
1803 return NULL;
1804 }
1805 }
1806 return mod;
1807}
1808
1809PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001810PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1811 PyObject *locals, PyObject *fromlist,
1812 int level)
1813{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001814 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001815 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001816 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001817 PyObject *final_mod = NULL;
1818 PyObject *mod = NULL;
1819 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001820 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001821 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001822
Brett Cannonfd074152012-04-14 14:10:13 -04001823 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001824 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001825 goto error;
1826 }
1827
1828 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1829 for added performance. */
1830
1831 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001832 _PyErr_SetString(tstate, PyExc_TypeError,
1833 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001834 goto error;
1835 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001836 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001837 goto error;
1838 }
1839 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001840 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001841 goto error;
1842 }
Brett Cannon849113a2016-01-22 15:25:50 -08001843
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001844 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001845 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001846 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001847 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001848 }
1849 else { /* level == 0 */
1850 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001851 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001852 goto error;
1853 }
Brett Cannonfd074152012-04-14 14:10:13 -04001854 abs_name = name;
1855 Py_INCREF(abs_name);
1856 }
1857
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001858 mod = import_get_module(tstate, abs_name);
1859 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001860 goto error;
1861 }
1862
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001863 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001864 if (import_ensure_initialized(tstate, mod, name) < 0) {
1865 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001866 }
Brett Cannonfd074152012-04-14 14:10:13 -04001867 }
1868 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001869 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001870 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001871 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001872 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001873 }
1874 }
1875
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001876 has_from = 0;
1877 if (fromlist != NULL && fromlist != Py_None) {
1878 has_from = PyObject_IsTrue(fromlist);
1879 if (has_from < 0)
1880 goto error;
1881 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001882 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001883 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1884 if (level == 0 || len > 0) {
1885 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001886
Victor Stinner744c34e2016-05-20 11:36:13 +02001887 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1888 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001889 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001890 }
1891
Victor Stinner744c34e2016-05-20 11:36:13 +02001892 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001893 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001894 final_mod = mod;
1895 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001896 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001897 }
1898
Brett Cannonfd074152012-04-14 14:10:13 -04001899 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001900 PyObject *front = PyUnicode_Substring(name, 0, dot);
1901 if (front == NULL) {
1902 goto error;
1903 }
1904
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001905 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001906 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001907 }
1908 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001909 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001910 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001911 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001912 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001913 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001914 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001915 }
Brett Cannonfd074152012-04-14 14:10:13 -04001916
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001917 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001918 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001919 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001920 if (!_PyErr_Occurred(tstate)) {
1921 _PyErr_Format(tstate, PyExc_KeyError,
1922 "%R not in sys.modules as expected",
1923 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001924 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001925 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001926 }
Brett Cannonfd074152012-04-14 14:10:13 -04001927 }
1928 }
1929 else {
1930 final_mod = mod;
1931 Py_INCREF(mod);
1932 }
1933 }
1934 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001935 PyObject *path;
1936 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1937 goto error;
1938 }
1939 if (path) {
1940 Py_DECREF(path);
1941 final_mod = _PyObject_CallMethodIdObjArgs(
1942 interp->importlib, &PyId__handle_fromlist,
1943 mod, fromlist, interp->import_func, NULL);
1944 }
1945 else {
1946 final_mod = mod;
1947 Py_INCREF(mod);
1948 }
Brett Cannonfd074152012-04-14 14:10:13 -04001949 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001950
Brett Cannonfd074152012-04-14 14:10:13 -04001951 error:
1952 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001953 Py_XDECREF(mod);
1954 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001955 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001956 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001957 }
Brett Cannonfd074152012-04-14 14:10:13 -04001958 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001959}
1960
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001961PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001962PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001963 PyObject *fromlist, int level)
1964{
1965 PyObject *nameobj, *mod;
1966 nameobj = PyUnicode_FromString(name);
1967 if (nameobj == NULL)
1968 return NULL;
1969 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1970 fromlist, level);
1971 Py_DECREF(nameobj);
1972 return mod;
1973}
1974
1975
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001976/* Re-import a module of any kind and return its module object, WITH
1977 INCREMENTED REFERENCE COUNT */
1978
Guido van Rossum79f25d91997-04-29 20:08:16 +00001979PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001980PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001981{
Eric Snow3f9eee62017-09-15 16:35:20 -06001982 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001983 _Py_IDENTIFIER(reload);
1984 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001985 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001986 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001987 if (PyErr_Occurred()) {
1988 return NULL;
1989 }
1990
Brett Cannon62228db2012-04-29 14:38:11 -04001991 imp = PyImport_ImportModule("imp");
1992 if (imp == NULL) {
1993 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001996
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001997 reloaded_module = _PyObject_CallMethodIdOneArg(imp, &PyId_reload, m);
Brett Cannon62228db2012-04-29 14:38:11 -04001998 Py_DECREF(imp);
1999 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002000}
2001
2002
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002003/* Higher-level import emulator which emulates the "import" statement
2004 more accurately -- it invokes the __import__() function from the
2005 builtins of the current globals. This means that the import is
2006 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002007 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002008 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002009 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002010 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002011
2012PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002013PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002014{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002015 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 static PyObject *silly_list = NULL;
2017 static PyObject *builtins_str = NULL;
2018 static PyObject *import_str = NULL;
2019 PyObject *globals = NULL;
2020 PyObject *import = NULL;
2021 PyObject *builtins = NULL;
2022 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* Initialize constant string objects */
2025 if (silly_list == NULL) {
2026 import_str = PyUnicode_InternFromString("__import__");
2027 if (import_str == NULL)
2028 return NULL;
2029 builtins_str = PyUnicode_InternFromString("__builtins__");
2030 if (builtins_str == NULL)
2031 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002032 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (silly_list == NULL)
2034 return NULL;
2035 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 /* Get the builtins from current globals */
2038 globals = PyEval_GetGlobals();
2039 if (globals != NULL) {
2040 Py_INCREF(globals);
2041 builtins = PyObject_GetItem(globals, builtins_str);
2042 if (builtins == NULL)
2043 goto err;
2044 }
2045 else {
2046 /* No globals -- use standard builtins, and fake globals */
2047 builtins = PyImport_ImportModuleLevel("builtins",
2048 NULL, NULL, NULL, 0);
2049 if (builtins == NULL)
2050 return NULL;
2051 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2052 if (globals == NULL)
2053 goto err;
2054 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* Get the __import__ function from the builtins */
2057 if (PyDict_Check(builtins)) {
2058 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002059 if (import == NULL) {
2060 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2061 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 }
2063 else
2064 import = PyObject_GetAttr(builtins, import_str);
2065 if (import == NULL)
2066 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002069 Always use absolute import here.
2070 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2072 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002073 if (r == NULL)
2074 goto err;
2075 Py_DECREF(r);
2076
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002077 r = import_get_module(tstate, module_name);
2078 if (r == NULL && !_PyErr_Occurred(tstate)) {
2079 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002080 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002081
2082 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 Py_XDECREF(globals);
2084 Py_XDECREF(builtins);
2085 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002088}
2089
Brett Cannon4caa61d2014-01-09 19:03:32 -05002090/*[clinic input]
2091_imp.extension_suffixes
2092
2093Returns the list of file suffixes used to identify extension modules.
2094[clinic start generated code]*/
2095
Brett Cannon4caa61d2014-01-09 19:03:32 -05002096static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002097_imp_extension_suffixes_impl(PyObject *module)
2098/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 list = PyList_New(0);
2103 if (list == NULL)
2104 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002105#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002106 const char *suffix;
2107 unsigned int index = 0;
2108
Brett Cannon2657df42012-05-04 15:20:40 -04002109 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2110 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (item == NULL) {
2112 Py_DECREF(list);
2113 return NULL;
2114 }
2115 if (PyList_Append(list, item) < 0) {
2116 Py_DECREF(list);
2117 Py_DECREF(item);
2118 return NULL;
2119 }
2120 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002121 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 }
Brett Cannon2657df42012-05-04 15:20:40 -04002123#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002125}
2126
Brett Cannon4caa61d2014-01-09 19:03:32 -05002127/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002128_imp.init_frozen
2129
2130 name: unicode
2131 /
2132
2133Initializes a frozen module.
2134[clinic start generated code]*/
2135
Brett Cannon4caa61d2014-01-09 19:03:32 -05002136static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002137_imp_init_frozen_impl(PyObject *module, PyObject *name)
2138/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002139{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002140 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 int ret;
2142 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002143
Victor Stinner53dc7352011-03-20 01:50:21 +01002144 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (ret < 0)
2146 return NULL;
2147 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002148 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002150 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 Py_XINCREF(m);
2152 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002153}
2154
Brett Cannon4caa61d2014-01-09 19:03:32 -05002155/*[clinic input]
2156_imp.get_frozen_object
2157
2158 name: unicode
2159 /
2160
2161Create a code object for a frozen module.
2162[clinic start generated code]*/
2163
Brett Cannon4caa61d2014-01-09 19:03:32 -05002164static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002165_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2166/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002169}
2170
Brett Cannon4caa61d2014-01-09 19:03:32 -05002171/*[clinic input]
2172_imp.is_frozen_package
2173
2174 name: unicode
2175 /
2176
2177Returns True if the module name is of a frozen package.
2178[clinic start generated code]*/
2179
Brett Cannon4caa61d2014-01-09 19:03:32 -05002180static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002181_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2182/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002185}
2186
Brett Cannon4caa61d2014-01-09 19:03:32 -05002187/*[clinic input]
2188_imp.is_builtin
2189
2190 name: unicode
2191 /
2192
2193Returns True if the module name corresponds to a built-in module.
2194[clinic start generated code]*/
2195
Guido van Rossum79f25d91997-04-29 20:08:16 +00002196static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002197_imp_is_builtin_impl(PyObject *module, PyObject *name)
2198/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002199{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002200 return PyLong_FromLong(is_builtin(name));
2201}
2202
2203/*[clinic input]
2204_imp.is_frozen
2205
2206 name: unicode
2207 /
2208
2209Returns True if the module name corresponds to a frozen module.
2210[clinic start generated code]*/
2211
Brett Cannon4caa61d2014-01-09 19:03:32 -05002212static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002213_imp_is_frozen_impl(PyObject *module, PyObject *name)
2214/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002215{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002216 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 p = find_frozen(name);
2219 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002220}
2221
Larry Hastings1df0b352015-08-24 19:53:56 -07002222/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2223static int
2224exec_builtin_or_dynamic(PyObject *mod) {
2225 PyModuleDef *def;
2226 void *state;
2227
2228 if (!PyModule_Check(mod)) {
2229 return 0;
2230 }
2231
2232 def = PyModule_GetDef(mod);
2233 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002234 return 0;
2235 }
Brett Cannon52794db2016-09-07 17:00:43 -07002236
Larry Hastings1df0b352015-08-24 19:53:56 -07002237 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002238 if (state) {
2239 /* Already initialized; skip reload */
2240 return 0;
2241 }
Brett Cannon52794db2016-09-07 17:00:43 -07002242
Larry Hastings1df0b352015-08-24 19:53:56 -07002243 return PyModule_ExecDef(mod, def);
2244}
2245
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002246#ifdef HAVE_DYNAMIC_LOADING
2247
Brett Cannon4caa61d2014-01-09 19:03:32 -05002248/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002249_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002250
Nick Coghland5cacbb2015-05-23 22:24:10 +10002251 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002252 file: object = NULL
2253 /
2254
Nick Coghland5cacbb2015-05-23 22:24:10 +10002255Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002256[clinic start generated code]*/
2257
Brett Cannon4caa61d2014-01-09 19:03:32 -05002258static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002259_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2260/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002261{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002262 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002263 FILE *fp;
2264
Nick Coghland5cacbb2015-05-23 22:24:10 +10002265 name = PyObject_GetAttrString(spec, "name");
2266 if (name == NULL) {
2267 return NULL;
2268 }
2269
2270 path = PyObject_GetAttrString(spec, "origin");
2271 if (path == NULL) {
2272 Py_DECREF(name);
2273 return NULL;
2274 }
2275
2276 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002277 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002278 Py_DECREF(name);
2279 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002280 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002281 return mod;
2282 }
2283
Brett Cannon4caa61d2014-01-09 19:03:32 -05002284 if (file != NULL) {
2285 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002286 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002287 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002288 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002292 else
2293 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002294
2295 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2296
2297 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002298 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 if (fp)
2300 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002301 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002302}
2303
Nick Coghland5cacbb2015-05-23 22:24:10 +10002304/*[clinic input]
2305_imp.exec_dynamic -> int
2306
2307 mod: object
2308 /
2309
2310Initialize an extension module.
2311[clinic start generated code]*/
2312
2313static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002314_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2315/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002316{
Larry Hastings1df0b352015-08-24 19:53:56 -07002317 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002318}
2319
2320
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002321#endif /* HAVE_DYNAMIC_LOADING */
2322
Larry Hastings7726ac92014-01-31 22:03:12 -08002323/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002324_imp.exec_builtin -> int
2325
2326 mod: object
2327 /
2328
2329Initialize a built-in module.
2330[clinic start generated code]*/
2331
2332static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002333_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2334/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002335{
2336 return exec_builtin_or_dynamic(mod);
2337}
2338
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002339/*[clinic input]
2340_imp.source_hash
2341
2342 key: long
2343 source: Py_buffer
2344[clinic start generated code]*/
2345
2346static PyObject *
2347_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2348/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2349{
Benjamin Peterson83620772017-12-09 12:18:56 -08002350 union {
2351 uint64_t x;
2352 char data[sizeof(uint64_t)];
2353 } hash;
2354 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002355#if !PY_LITTLE_ENDIAN
2356 // Force to little-endian. There really ought to be a succinct standard way
2357 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002358 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2359 char tmp = hash.data[i];
2360 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2361 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002362 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002363#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002364 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002365}
2366
Barry Warsaw28a691b2010-04-17 00:19:56 +00002367
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002368PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002369"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002370
Guido van Rossum79f25d91997-04-29 20:08:16 +00002371static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002372 _IMP_EXTENSION_SUFFIXES_METHODDEF
2373 _IMP_LOCK_HELD_METHODDEF
2374 _IMP_ACQUIRE_LOCK_METHODDEF
2375 _IMP_RELEASE_LOCK_METHODDEF
2376 _IMP_GET_FROZEN_OBJECT_METHODDEF
2377 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002378 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002379 _IMP_INIT_FROZEN_METHODDEF
2380 _IMP_IS_BUILTIN_METHODDEF
2381 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002382 _IMP_CREATE_DYNAMIC_METHODDEF
2383 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002384 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002385 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002386 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002387 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002388};
2389
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002390
Martin v. Löwis1a214512008-06-11 05:26:20 +00002391static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002393 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 doc_imp,
2395 0,
2396 imp_methods,
2397 NULL,
2398 NULL,
2399 NULL,
2400 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002401};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002402
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002403PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002404PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002409 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002411 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002413 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002415 }
2416
Victor Stinnerda7933e2020-04-13 03:04:28 +02002417 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002418 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002419 if (pyc_mode == NULL) {
2420 goto failure;
2421 }
2422 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2423 Py_DECREF(pyc_mode);
2424 goto failure;
2425 }
2426 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002429 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 Py_XDECREF(m);
2431 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002432}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002433
2434
Guido van Rossumb18618d2000-05-03 23:44:39 +00002435/* API for embedding applications that want to add their own entries
2436 to the table of built-in modules. This should normally be called
2437 *before* Py_Initialize(). When the table resize fails, -1 is
2438 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002439
2440 After a similar function by Just van Rossum. */
2441
2442int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002443PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002446 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002447 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* Count the number of entries in both tables */
2450 for (n = 0; newtab[n].name != NULL; n++)
2451 ;
2452 if (n == 0)
2453 return 0; /* Nothing to do */
2454 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2455 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002456
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002457 /* Force default raw memory allocator to get a known allocator to be able
2458 to release the memory in _PyImport_Fini2() */
2459 PyMemAllocatorEx old_alloc;
2460 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002463 p = NULL;
2464 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002465 size_t size = sizeof(struct _inittab) * (i + n + 1);
2466 p = PyMem_RawRealloc(inittab_copy, size);
2467 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002468 if (p == NULL) {
2469 res = -1;
2470 goto done;
2471 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002472
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002473 /* Copy the tables into the new memory at the first call
2474 to PyImport_ExtendInittab(). */
2475 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002477 }
2478 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2479 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002480
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002481done:
2482 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2483 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002484}
2485
2486/* Shorthand to add a single entry given a name and a function */
2487
2488int
Brett Cannona826f322009-04-02 03:41:46 +00002489PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002494
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002495 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002499}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002500
2501#ifdef __cplusplus
2502}
2503#endif