blob: 5e39a2fb9a02e587fcdaf21d3d61feda105be67d [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module definition and import implementation */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner61691d82019-10-02 23:51:20 +02007#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02008#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pyhash.h"
10#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020011#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020012#include "pycore_interp.h" // _PyInterpreterState_ClearModules()
13#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinner1c1e68c2020-03-27 15:11:45 +010014#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "code.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000018#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020019#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000020
Guido van Rossum55a83382000-09-20 20:31:38 +000021#ifdef HAVE_FCNTL_H
22#include <fcntl.h>
23#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000025extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000027
Barry Warsaw28a691b2010-04-17 00:19:56 +000028#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000029
Victor Stinner0a28f8d2019-06-19 02:54:39 +020030/* Forward references */
31static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
32
Victor Stinner95872862011-03-07 18:20:56 +010033/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000034static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000035
Guido van Rossum771c6c81997-10-31 18:37:24 +000036/* This table is defined in config.c: */
37extern struct _inittab _PyImport_Inittab[];
38
39struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010040static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000041
Hai Shi46874c22020-01-30 17:20:25 -060042_Py_IDENTIFIER(__path__);
43_Py_IDENTIFIER(__spec__);
44
Brett Cannon4caa61d2014-01-09 19:03:32 -050045/*[clinic input]
46module _imp
47[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030048/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040049
50#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050051
Guido van Rossum1ae940a1995-01-02 19:04:15 +000052/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053
Victor Stinner331a6a52019-05-27 16:39:22 +020054PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020055_PyImportHooks_Init(PyThreadState *tstate)
Just van Rossum52e14d62002-12-30 22:08:05 +000056{
Brett Cannonfd074152012-04-14 14:10:13 -040057 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000059
Brett Cannonfd074152012-04-14 14:10:13 -040060 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 v = PyList_New(0);
62 if (v == NULL)
63 goto error;
64 err = PySys_SetObject("meta_path", v);
65 Py_DECREF(v);
66 if (err)
67 goto error;
68 v = PyDict_New();
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("path_importer_cache", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 path_hooks = PyList_New(0);
76 if (path_hooks == NULL)
77 goto error;
78 err = PySys_SetObject("path_hooks", path_hooks);
79 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 }
Brett Cannonfd074152012-04-14 14:10:13 -040082 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020083 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084
85 error:
Victor Stinnerb45d2592019-06-20 00:05:23 +020086 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020087 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080088 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040089}
90
Victor Stinner331a6a52019-05-27 16:39:22 +020091PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020092_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040093{
ukwksk5e6312c2018-05-15 04:10:52 +090094 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040095 int err = 0;
96
97 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020098 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +020099 _PyErr_SetString(tstate, PyExc_RuntimeError,
100 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400101 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200102 }
Brett Cannonfd074152012-04-14 14:10:13 -0400103
Victor Stinnerda7933e2020-04-13 03:04:28 +0200104 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200105 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400106 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200107 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108
ukwksk5e6312c2018-05-15 04:10:52 +0900109 zipimport = PyImport_ImportModule("zipimport");
110 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200111 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200112 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 }
116 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200117 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900118 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200119 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900120 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200122 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200123 if (verbose) {
124 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
127 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400128 /* sys.path_hooks.insert(0, zipimporter) */
129 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400131 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400133 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200134 if (verbose) {
135 PySys_WriteStderr("# installed zipimport hook\n");
136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 }
138 }
Brett Cannonfd074152012-04-14 14:10:13 -0400139
Victor Stinner331a6a52019-05-27 16:39:22 +0200140 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400141
142 error:
143 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200144 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000145}
146
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147/* Locking primitives to prevent parallel imports of the same module
148 in different threads to return with a partially loaded module.
149 These calls are serialized by the global interpreter lock. */
150
Guido van Rossum65d5b571998-12-21 19:32:43 +0000151static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200152static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153static int import_lock_level = 0;
154
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000155void
156_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000157{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200158 unsigned long me = PyThread_get_thread_ident();
159 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 return; /* Too bad */
161 if (import_lock == NULL) {
162 import_lock = PyThread_allocate_lock();
163 if (import_lock == NULL)
164 return; /* Nothing much we can do. */
165 }
166 if (import_lock_thread == me) {
167 import_lock_level++;
168 return;
169 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200170 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
171 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 {
173 PyThreadState *tstate = PyEval_SaveThread();
174 PyThread_acquire_lock(import_lock, 1);
175 PyEval_RestoreThread(tstate);
176 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100177 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 import_lock_thread = me;
179 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000180}
181
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000182int
183_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000184{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200185 unsigned long me = PyThread_get_thread_ident();
186 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return 0; /* Too bad */
188 if (import_lock_thread != me)
189 return -1;
190 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100191 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200193 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyThread_release_lock(import_lock);
195 }
196 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000197}
198
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900199#ifdef HAVE_FORK
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200200/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000201 created child processes do not share locks with the parent.
202 We now acquire the import lock around fork() calls but on some platforms
203 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000204
205void
206_PyImport_ReInitLock(void)
207{
Christian Heimes418fd742015-04-19 21:08:42 +0200208 if (import_lock != NULL) {
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900209 if (_PyThread_at_fork_reinit(&import_lock) < 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100210 _Py_FatalErrorFunc(__func__, "failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200211 }
212 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000213 if (import_lock_level > 1) {
214 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200215 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500216 /* The following could fail if the lock is already held, but forking as
217 a side-effect of an import is a) rare, b) nuts, and c) difficult to
218 do thanks to the lock only being held when doing individual module
219 locks per import. */
220 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000221 import_lock_thread = me;
222 import_lock_level--;
223 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200224 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000225 import_lock_level = 0;
226 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000227}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900228#endif
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000229
Brett Cannon4caa61d2014-01-09 19:03:32 -0500230/*[clinic input]
231_imp.lock_held
232
233Return True if the import lock is currently held, else False.
234
235On platforms without threads, return False.
236[clinic start generated code]*/
237
Brett Cannon4caa61d2014-01-09 19:03:32 -0500238static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300239_imp_lock_held_impl(PyObject *module)
240/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000241{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200242 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000243}
244
Brett Cannon4caa61d2014-01-09 19:03:32 -0500245/*[clinic input]
246_imp.acquire_lock
247
248Acquires the interpreter's import lock for the current thread.
249
250This lock should be used by import hooks to ensure thread-safety when importing
251modules. On platforms without threads, this function does nothing.
252[clinic start generated code]*/
253
Brett Cannon4caa61d2014-01-09 19:03:32 -0500254static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300255_imp_acquire_lock_impl(PyObject *module)
256/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200259 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000260}
261
Brett Cannon4caa61d2014-01-09 19:03:32 -0500262/*[clinic input]
263_imp.release_lock
264
265Release the interpreter's import lock.
266
267On platforms without threads, this function does nothing.
268[clinic start generated code]*/
269
Brett Cannon4caa61d2014-01-09 19:03:32 -0500270static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300271_imp_release_lock_impl(PyObject *module)
272/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (_PyImport_ReleaseLock() < 0) {
275 PyErr_SetString(PyExc_RuntimeError,
276 "not holding the import lock");
277 return NULL;
278 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200279 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000280}
281
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100282void
283_PyImport_Fini(void)
284{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200285 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100286 if (import_lock != NULL) {
287 PyThread_free_lock(import_lock);
288 import_lock = NULL;
289 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100290}
291
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100292void
293_PyImport_Fini2(void)
294{
295 /* Use the same memory allocator than PyImport_ExtendInittab(). */
296 PyMemAllocatorEx old_alloc;
297 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
298
299 /* Free memory allocated by PyImport_ExtendInittab() */
300 PyMem_RawFree(inittab_copy);
Gregory Szorc64224a42020-05-01 11:07:54 -0700301 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100302
303 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
304}
305
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306/* Helper for sys */
307
308PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000309PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310{
Victor Stinner81a7be32020-04-14 15:14:01 +0200311 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600312 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100313 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600314 }
Eric Snow93c92f72017-09-13 23:46:04 -0700315 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316}
317
Eric Snowd393c1b2017-09-14 12:18:12 -0600318/* In some corner cases it is important to be sure that the import
319 machinery has been initialized (or not cleaned up yet). For
320 example, see issue #4236 and PyModule_Create2(). */
321
322int
323_PyImport_IsInitialized(PyInterpreterState *interp)
324{
325 if (interp->modules == NULL)
326 return 0;
327 return 1;
328}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000329
Eric Snow3f9eee62017-09-15 16:35:20 -0600330PyObject *
331_PyImport_GetModuleId(struct _Py_Identifier *nameid)
332{
333 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
334 if (name == NULL) {
335 return NULL;
336 }
337 return PyImport_GetModule(name);
338}
339
340int
341_PyImport_SetModule(PyObject *name, PyObject *m)
342{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200343 PyThreadState *tstate = _PyThreadState_GET();
344 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600345 return PyObject_SetItem(modules, name, m);
346}
347
348int
349_PyImport_SetModuleString(const char *name, PyObject *m)
350{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200351 PyThreadState *tstate = _PyThreadState_GET();
352 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600353 return PyMapping_SetItemString(modules, name, m);
354}
355
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200356static PyObject *
357import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600358{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200359 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600360 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200361 _PyErr_SetString(tstate, PyExc_RuntimeError,
362 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600363 return NULL;
364 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200365
366 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600367 Py_INCREF(modules);
368 if (PyDict_CheckExact(modules)) {
369 m = PyDict_GetItemWithError(modules, name); /* borrowed */
370 Py_XINCREF(m);
371 }
372 else {
373 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200374 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
375 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600376 }
377 }
378 Py_DECREF(modules);
379 return m;
380}
381
382
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100383static int
384import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200385{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100386 PyInterpreterState *interp = tstate->interp;
387 PyObject *spec;
388
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100389 _Py_IDENTIFIER(_lock_unlock_module);
390
391 /* Optimization: only call _bootstrap._lock_unlock_module() if
392 __spec__._initializing is true.
393 NOTE: because of this, initializing must be set *before*
394 stuffing the new module in sys.modules.
395 */
396 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
397 int busy = _PyModuleSpec_IsInitializing(spec);
398 Py_XDECREF(spec);
399 if (busy) {
400 /* Wait until module is done importing. */
401 PyObject *value = _PyObject_CallMethodIdOneArg(
402 interp->importlib, &PyId__lock_unlock_module, name);
403 if (value == NULL) {
404 return -1;
405 }
406 Py_DECREF(value);
407 }
408 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200409}
410
411
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000412/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200413static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 "path", "argv", "ps1", "ps2",
415 "last_type", "last_value", "last_traceback",
416 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200417 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000419};
420
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200421static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 "stdin", "__stdin__",
423 "stdout", "__stdout__",
424 "stderr", "__stderr__",
425 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000426};
427
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000428/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000429
Guido van Rossum3f5da241990-12-20 15:06:42 +0000430void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200431_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000432{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200433 PyInterpreterState *interp = tstate->interp;
434 PyObject *modules = interp->modules;
435 if (modules == NULL) {
436 /* Already done */
437 return;
438 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 /* Delete some special variables first. These are common
441 places where user values hide and people complain when their
442 destructors fail. Since the modules containing them are
443 deleted *last* of all, they would come too late in the normal
444 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000445
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200446 /* XXX Perhaps these precautions are obsolete. Who knows? */
447
Victor Stinnerda7933e2020-04-13 03:04:28 +0200448 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200449 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200450 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200451 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300452 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300453 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300454 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200455
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200456 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200457 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200458 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200459 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200460 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300461 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300462 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200465 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200466 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200467 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200468 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200469 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
470 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200471 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200472 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200473 PyErr_WriteUnraisable(NULL);
474 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200475 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200476 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300477 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300478 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300479 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000481
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200482 /* We prepare a list which will receive (name, weakref) tuples of
483 modules when they are removed from sys.modules. The name is used
484 for diagnosis messages (in verbose mode), while the weakref helps
485 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200486 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300487 if (weaklist == NULL) {
488 PyErr_WriteUnraisable(NULL);
489 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200490
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200491#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200492 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200493 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300494 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200495 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300496 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300497 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300498 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200499 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300500 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200501 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300502 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300503 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300504 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600506#define CLEAR_MODULE(name, mod) \
507 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200508 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600509 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200510 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600511 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300512 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300513 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300514 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600515 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000516
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200517 /* Remove all modules from sys.modules, hoping that garbage collection
518 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600519 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200520 Py_ssize_t pos = 0;
521 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600522 while (PyDict_Next(modules, &pos, &key, &value)) {
523 CLEAR_MODULE(key, value);
524 }
525 }
526 else {
527 PyObject *iterator = PyObject_GetIter(modules);
528 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300529 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600530 }
531 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200532 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600533 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200534 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600535 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300536 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600537 continue;
538 }
539 CLEAR_MODULE(key, value);
540 Py_DECREF(value);
541 Py_DECREF(key);
542 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300543 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300544 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300545 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600546 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 }
548 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000549
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200550 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600551 if (PyDict_CheckExact(modules)) {
552 PyDict_Clear(modules);
553 }
554 else {
555 _Py_IDENTIFIER(clear);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200556 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300557 PyErr_WriteUnraisable(NULL);
558 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600559 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200560 /* Restore the original builtins dict, to ensure that any
561 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200562 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300563 if (dict == NULL) {
564 PyErr_WriteUnraisable(NULL);
565 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200566 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300567 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200568 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300569 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200570 Py_XDECREF(dict);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200571 /* Collect references */
572 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200573 /* Dump GC stats before it's too late, since it uses the warnings
574 machinery. */
Victor Stinner67e0de62019-11-20 11:48:18 +0100575 _PyGC_DumpShutdownStats(tstate);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200576
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200577 /* Now, if there are any modules left alive, clear their globals to
578 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200579 up here, since they are kept alive in the interpreter state.
580
581 The special treatment of "builtins" here is because even
582 when it's not referenced as a module, its dictionary is
583 referenced by almost every module's __builtins__. Since
584 deleting a module clears its dictionary (even if there are
585 references left to it), we need to delete the "builtins"
586 module last. Likewise, we don't delete sys until the very
587 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200588 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200589 Py_ssize_t i;
590 /* Since dict is ordered in CPython 3.6+, modules are saved in
591 importing order. First clear modules imported later. */
592 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200593 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200594 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200595 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
596 if (mod == Py_None)
597 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200598 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200599 dict = PyModule_GetDict(mod);
600 if (dict == interp->builtins || dict == interp->sysdict)
601 continue;
602 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200603 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200604 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200605 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200606 _PyModule_Clear(mod);
607 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200608 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200609 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000611
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200612 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200613 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200614 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200615 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200616 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200617 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200618 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200619 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200620 _PyModule_ClearDict(interp->builtins);
621
Eddie Elizondo4590f722020-02-04 02:29:25 -0800622 /* Clear module dict copies stored in the interpreter state */
623 _PyInterpreterState_ClearModules(interp);
624
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200625 /* Clear and delete the modules directory. Actual modules will
626 still be there only if imported during the execution of some
627 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700628 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200630
631 /* Once more */
632 _PyGC_CollectNoFail();
633
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300634#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200635#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000636}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000637
638
Barry Warsaw28a691b2010-04-17 00:19:56 +0000639/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000640
641long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000642PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000643{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200644 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200645 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600646 PyObject *external, *pyc_magic;
647
648 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
649 if (external == NULL)
650 return -1;
651 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
652 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400653 if (pyc_magic == NULL)
654 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200655 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700656 Py_DECREF(pyc_magic);
657 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658}
659
660
Brett Cannon3adc7b72012-07-09 14:22:12 -0400661extern const char * _PySys_ImplCacheTag;
662
Barry Warsaw28a691b2010-04-17 00:19:56 +0000663const char *
664PyImport_GetMagicTag(void)
665{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400666 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000667}
668
Brett Cannon98979b82012-07-02 15:13:11 -0400669
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670/* Magic for extension modules (built-in as well as dynamically
671 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200672 once, we keep a static dictionary 'extensions' keyed by the tuple
673 (module name, module name) (for built-in modules) or by
674 (filename, module name) (for dynamically loaded modules), containing these
675 modules. A copy of the module's dictionary is stored by calling
676 _PyImport_FixupExtensionObject() immediately after the module initialization
677 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100678 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000679
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000680 Modules which do support multiple initialization set their m_size
681 field to a non-negative number (indicating the size of the
682 module-specific state). They are still recorded in the extensions
683 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000684*/
685
686int
Victor Stinner95872862011-03-07 18:20:56 +0100687_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200688 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (mod == NULL || !PyModule_Check(mod)) {
691 PyErr_BadInternalCall();
692 return -1;
693 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100694
695 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (!def) {
697 PyErr_BadInternalCall();
698 return -1;
699 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100700
701 PyThreadState *tstate = _PyThreadState_GET();
702 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100704 }
705 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600706 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return -1;
708 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100709
710 if (_Py_IsMainInterpreter(tstate)) {
711 if (def->m_size == -1) {
712 if (def->m_base.m_copy) {
713 /* Somebody already imported the module,
714 likely under a different name.
715 XXX this should really not happen. */
716 Py_CLEAR(def->m_base.m_copy);
717 }
718 PyObject *dict = PyModule_GetDict(mod);
719 if (dict == NULL) {
720 return -1;
721 }
722 def->m_base.m_copy = PyDict_Copy(dict);
723 if (def->m_base.m_copy == NULL) {
724 return -1;
725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100727
728 if (extensions == NULL) {
729 extensions = PyDict_New();
730 if (extensions == NULL) {
731 return -1;
732 }
733 }
734
735 PyObject *key = PyTuple_Pack(2, filename, name);
736 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100738 }
739 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
740 Py_DECREF(key);
741 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100743 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000747}
748
Victor Stinner49d3f252010-10-17 01:24:53 +0000749int
Eric Snowd393c1b2017-09-14 12:18:12 -0600750_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000751{
752 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100753 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100754 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100755 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000756 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600757 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100758 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000759 return res;
760}
761
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200762static PyObject *
763import_find_extension(PyThreadState *tstate, PyObject *name,
764 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000765{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200766 if (extensions == NULL) {
767 return NULL;
768 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600769
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200770 PyObject *key = PyTuple_Pack(2, filename, name);
771 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200773 }
774 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500775 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200776 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200778 }
779
780 PyObject *mod, *mdict;
781 PyObject *modules = tstate->interp->modules;
782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (def->m_size == -1) {
784 /* Module does not support repeated initialization */
785 if (def->m_base.m_copy == NULL)
786 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200787 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (mod == NULL)
789 return NULL;
790 mdict = PyModule_GetDict(mod);
791 if (mdict == NULL)
792 return NULL;
793 if (PyDict_Update(mdict, def->m_base.m_copy))
794 return NULL;
795 }
796 else {
797 if (def->m_base.m_init == NULL)
798 return NULL;
799 mod = def->m_base.m_init();
800 if (mod == NULL)
801 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600802 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200803 Py_DECREF(mod);
804 return NULL;
805 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 Py_DECREF(mod);
807 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100808 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600809 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 return NULL;
811 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200812
Victor Stinnerda7933e2020-04-13 03:04:28 +0200813 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200814 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100815 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200816 name, filename);
817 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000819}
820
Victor Stinner49d3f252010-10-17 01:24:53 +0000821PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200822_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
823{
824 PyThreadState *tstate = _PyThreadState_GET();
825 return import_find_extension(tstate, name, filename);
826}
827
828
829PyObject *
830_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000831{
Victor Stinner95872862011-03-07 18:20:56 +0100832 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100833 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100834 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000835 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200836 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100837 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000838 return res;
839}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000840
841/* Get the module object corresponding to a module name.
842 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000843 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000844 Because the former action is most common, THIS DOES NOT RETURN A
845 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000846
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200847static PyObject *
848import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000849{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200850 PyObject *modules = tstate->interp->modules;
851 if (modules == NULL) {
852 _PyErr_SetString(tstate, PyExc_RuntimeError,
853 "no import module dictionary");
854 return NULL;
855 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600856
Eric Snow86b7afd2017-09-04 17:54:09 -0600857 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600858 if (PyDict_CheckExact(modules)) {
859 m = PyDict_GetItemWithError(modules, name);
860 }
861 else {
862 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000863 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600864 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200865 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
866 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600867 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200868 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200869 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200870 return NULL;
871 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600872 if (m != NULL && PyModule_Check(m)) {
873 return m;
874 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000875 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (m == NULL)
877 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600878 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 Py_DECREF(m);
880 return NULL;
881 }
882 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885}
886
Victor Stinner27ee0892011-03-04 12:57:09 +0000887PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200888PyImport_AddModuleObject(PyObject *name)
889{
890 PyThreadState *tstate = _PyThreadState_GET();
891 return import_add_module(tstate, name);
892}
893
894
895PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000896PyImport_AddModule(const char *name)
897{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200898 PyObject *nameobj = PyUnicode_FromString(name);
899 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000900 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200901 }
902 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000903 Py_DECREF(nameobj);
904 return module;
905}
906
907
Miss Skeleton (bot)391a5442020-10-14 02:09:44 -0700908/* Remove name from sys.modules, if it's there.
909 * Can be called with an exception raised.
910 * If fail to remove name a new exception will be chained with the old
911 * exception, otherwise the old exception is preserved.
912 */
Tim Peters1cd70172004-08-02 03:52:12 +0000913static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200914remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000915{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600916 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200917 _PyErr_Fetch(tstate, &type, &value, &traceback);
918
919 PyObject *modules = tstate->interp->modules;
Miss Skeleton (bot)391a5442020-10-14 02:09:44 -0700920 if (PyDict_CheckExact(modules)) {
921 PyObject *mod = _PyDict_Pop(modules, name, Py_None);
922 Py_XDECREF(mod);
Zackery Spytz94a64e92019-05-08 10:31:23 -0600923 }
Miss Skeleton (bot)391a5442020-10-14 02:09:44 -0700924 else if (PyMapping_DelItem(modules, name) < 0) {
925 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
926 _PyErr_Clear(tstate);
927 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600928 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200929
Miss Skeleton (bot)391a5442020-10-14 02:09:44 -0700930 _PyErr_ChainExceptions(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000931}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000932
Christian Heimes3b06e532008-01-07 20:12:44 +0000933
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000934/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000935 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
936 * removed from sys.modules, to avoid leaving damaged module objects
937 * in sys.modules. The caller may wish to restore the original
938 * module object (if any) in this case; PyImport_ReloadModule is an
939 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000940 *
941 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
942 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000943 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000944PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300945PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 return PyImport_ExecCodeModuleWithPathnames(
948 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000949}
950
951PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300952PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 return PyImport_ExecCodeModuleWithPathnames(
955 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000956}
957
958PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300959PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
960 const char *pathname,
961 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000962{
Victor Stinner27ee0892011-03-04 12:57:09 +0000963 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600964 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000965
966 nameobj = PyUnicode_FromString(name);
967 if (nameobj == NULL)
968 return NULL;
969
Victor Stinner27ee0892011-03-04 12:57:09 +0000970 if (cpathname != NULL) {
971 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
972 if (cpathobj == NULL)
973 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400974 }
975 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000976 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400977
978 if (pathname != NULL) {
979 pathobj = PyUnicode_DecodeFSDefault(pathname);
980 if (pathobj == NULL)
981 goto error;
982 }
983 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200984 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400985 _Py_IDENTIFIER(_get_sourcefile);
986
987 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100988 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400989 }
990
Eric Snow32439d62015-05-02 19:15:18 -0600991 external= PyObject_GetAttrString(interp->importlib,
992 "_bootstrap_external");
993 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200994 pathobj = _PyObject_CallMethodIdOneArg(
995 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600996 Py_DECREF(external);
997 }
Brett Cannona6473f92012-07-13 13:57:03 -0400998 if (pathobj == NULL)
999 PyErr_Clear();
1000 }
1001 else
1002 pathobj = NULL;
1003
Victor Stinner27ee0892011-03-04 12:57:09 +00001004 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
1005error:
1006 Py_DECREF(nameobj);
1007 Py_XDECREF(pathobj);
1008 Py_XDECREF(cpathobj);
1009 return m;
1010}
1011
Brett Cannon18fc4e72014-04-04 10:01:46 -04001012static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001013module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +00001014{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001015 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001016 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001017
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001018 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (m == NULL)
1020 return NULL;
1021 /* If the module is being reloaded, we get the old module back
1022 and re-use its dict to exec the new code. */
1023 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001024 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001025 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001026 _PyDict_SetItemId(d, &PyId___builtins__,
1027 PyEval_GetBuiltins()) != 0)
1028 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001029 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001030 return NULL;
1031 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001033
Eric Snow08197a42014-05-12 17:54:55 -06001034 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001035}
1036
1037static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001038exec_code_in_module(PyThreadState *tstate, PyObject *name,
1039 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001040{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001041 PyObject *v, *m;
1042
1043 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1044 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001045 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001046 return NULL;
1047 }
1048 Py_DECREF(v);
1049
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001050 m = import_get_module(tstate, name);
1051 if (m == NULL && !_PyErr_Occurred(tstate)) {
1052 _PyErr_Format(tstate, PyExc_ImportError,
1053 "Loaded module %R not found in sys.modules",
1054 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001055 }
1056
Brett Cannon18fc4e72014-04-04 10:01:46 -04001057 return m;
1058}
1059
1060PyObject*
1061PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1062 PyObject *cpathname)
1063{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001064 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001065 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001066 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001067
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001068 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001069 if (d == NULL) {
1070 return NULL;
1071 }
1072
Eric Snow08197a42014-05-12 17:54:55 -06001073 if (pathname == NULL) {
1074 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001076 external = PyObject_GetAttrString(tstate->interp->importlib,
1077 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001078 if (external == NULL)
1079 return NULL;
1080 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001081 &PyId__fix_up_module,
1082 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001083 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001084 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001085 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001086 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
Eric Snow08197a42014-05-12 17:54:55 -06001088 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001089}
1090
1091
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001092static void
1093update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyObject *constants, *tmp;
1096 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (PyUnicode_Compare(co->co_filename, oldname))
1099 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001100
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001101 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001102 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 constants = co->co_consts;
1105 n = PyTuple_GET_SIZE(constants);
1106 for (i = 0; i < n; i++) {
1107 tmp = PyTuple_GET_ITEM(constants, i);
1108 if (PyCode_Check(tmp))
1109 update_code_filenames((PyCodeObject *)tmp,
1110 oldname, newname);
1111 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001112}
1113
Victor Stinner2f42ae52011-03-20 00:41:24 +01001114static void
1115update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001116{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001117 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001118
Victor Stinner2f42ae52011-03-20 00:41:24 +01001119 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1120 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 oldname = co->co_filename;
1123 Py_INCREF(oldname);
1124 update_code_filenames(co, oldname, newname);
1125 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001126}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001127
Brett Cannon4caa61d2014-01-09 19:03:32 -05001128/*[clinic input]
1129_imp._fix_co_filename
1130
1131 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1132 Code object to change.
1133
1134 path: unicode
1135 File path to use.
1136 /
1137
1138Changes code.co_filename to specify the passed-in file path.
1139[clinic start generated code]*/
1140
Brett Cannon4caa61d2014-01-09 19:03:32 -05001141static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001142_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001143 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001144/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001145
Brett Cannon4caa61d2014-01-09 19:03:32 -05001146{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001147 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001148
1149 Py_RETURN_NONE;
1150}
1151
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001153/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001154static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001155
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001156
1157/* Helper to test for built-in module */
1158
1159static int
Victor Stinner95872862011-03-07 18:20:56 +01001160is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001161{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001162 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001164 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (PyImport_Inittab[i].initfunc == NULL)
1166 return -1;
1167 else
1168 return 1;
1169 }
1170 }
1171 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001172}
1173
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001174
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001175/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001176 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001177 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001178 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001179 this tells our caller that the path based finder could not find
1180 a finder for this path item. Cache the result in
1181 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001182 Returns a borrowed reference. */
1183
1184static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001185get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1186 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyObject *importer;
1189 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 /* These conditions are the caller's responsibility: */
1192 assert(PyList_Check(path_hooks));
1193 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 nhooks = PyList_Size(path_hooks);
1196 if (nhooks < 0)
1197 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001198
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001199 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001200 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 /* set path_importer_cache[p] to None to avoid recursion */
1204 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1205 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 for (j = 0; j < nhooks; j++) {
1208 PyObject *hook = PyList_GetItem(path_hooks, j);
1209 if (hook == NULL)
1210 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +01001211 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (importer != NULL)
1213 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001214
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001215 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 return NULL;
1217 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001218 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 }
1220 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001221 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 }
1223 if (importer != NULL) {
1224 int err = PyDict_SetItem(path_importer_cache, p, importer);
1225 Py_DECREF(importer);
1226 if (err != 0)
1227 return NULL;
1228 }
1229 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001230}
1231
Benjamin Petersone5024512018-09-12 12:06:42 -07001232PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001233PyImport_GetImporter(PyObject *path)
1234{
1235 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001237
Victor Stinner1e53bba2013-07-16 22:26:05 +02001238 path_importer_cache = PySys_GetObject("path_importer_cache");
1239 path_hooks = PySys_GetObject("path_hooks");
1240 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001241 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001242 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 }
1244 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1245 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001246}
1247
Nick Coghland5cacbb2015-05-23 22:24:10 +10001248/*[clinic input]
1249_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001250
Nick Coghland5cacbb2015-05-23 22:24:10 +10001251 spec: object
1252 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001253
Nick Coghland5cacbb2015-05-23 22:24:10 +10001254Create an extension module.
1255[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001256
Nick Coghland5cacbb2015-05-23 22:24:10 +10001257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001258_imp_create_builtin(PyObject *module, PyObject *spec)
1259/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001260{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001261 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001263 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001264 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001265 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001266
Nick Coghland5cacbb2015-05-23 22:24:10 +10001267 name = PyObject_GetAttrString(spec, "name");
1268 if (name == NULL) {
1269 return NULL;
1270 }
1271
Victor Stinner5eb4f592013-11-14 22:38:52 +01001272 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001273 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001274 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001275 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001276 return mod;
1277 }
1278
1279 namestr = PyUnicode_AsUTF8(name);
1280 if (namestr == NULL) {
1281 Py_DECREF(name);
1282 return NULL;
1283 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001284
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001285 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001287 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001288 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001290 /* Cannot re-init internal module ("sys" or "builtins") */
1291 mod = PyImport_AddModule(namestr);
1292 Py_DECREF(name);
1293 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001296 if (mod == NULL) {
1297 Py_DECREF(name);
1298 return NULL;
1299 }
1300 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1301 Py_DECREF(name);
1302 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1303 } else {
1304 /* Remember pointer to module init function. */
1305 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001306 if (def == NULL) {
1307 Py_DECREF(name);
1308 return NULL;
1309 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001310 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001311 if (_PyImport_FixupExtensionObject(mod, name, name,
1312 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001313 Py_DECREF(name);
1314 return NULL;
1315 }
1316 Py_DECREF(name);
1317 return mod;
1318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
1320 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001321 Py_DECREF(name);
1322 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001323}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001324
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001325
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001326/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001327
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001328static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001329find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001330{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001331 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001332
Victor Stinner53dc7352011-03-20 01:50:21 +01001333 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 for (p = PyImport_FrozenModules; ; p++) {
1337 if (p->name == NULL)
1338 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001339 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 break;
1341 }
1342 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001343}
1344
Guido van Rossum79f25d91997-04-29 20:08:16 +00001345static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001346get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001347{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001348 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (p == NULL) {
1352 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001353 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 name);
1355 return NULL;
1356 }
1357 if (p->code == NULL) {
1358 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001359 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 name);
1361 return NULL;
1362 }
1363 size = p->size;
1364 if (size < 0)
1365 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001366 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001367}
1368
Brett Cannon8d110132009-03-15 02:20:16 +00001369static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001370is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001371{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001372 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (p == NULL) {
1376 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001377 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 name);
1379 return NULL;
1380 }
Brett Cannon8d110132009-03-15 02:20:16 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (size < 0)
1385 Py_RETURN_TRUE;
1386 else
1387 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001388}
1389
1390
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001391/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001392 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001393 an exception set if the initialization failed.
1394 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001395
1396int
Victor Stinner53dc7352011-03-20 01:50:21 +01001397PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001398{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001399 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001400 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001401 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 int ispackage;
1403 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001404
Victor Stinner53dc7352011-03-20 01:50:21 +01001405 p = find_frozen(name);
1406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (p == NULL)
1408 return 0;
1409 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001410 _PyErr_Format(tstate, PyExc_ImportError,
1411 "Excluded frozen object named %R",
1412 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 return -1;
1414 }
1415 size = p->size;
1416 ispackage = (size < 0);
1417 if (ispackage)
1418 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001419 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 if (co == NULL)
1421 return -1;
1422 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001423 _PyErr_Format(tstate, PyExc_TypeError,
1424 "frozen object %R is not a code object",
1425 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 goto err_return;
1427 }
1428 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001429 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001430 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001432 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (m == NULL)
1434 goto err_return;
1435 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001436 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 goto err_return;
1439 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 err = PyDict_SetItemString(d, "__path__", l);
1441 Py_DECREF(l);
1442 if (err != 0)
1443 goto err_return;
1444 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001445 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001446 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001447 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001448 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001449 m = exec_code_in_module(tstate, name, d, co);
1450 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001452 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 Py_DECREF(co);
1454 Py_DECREF(m);
1455 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001456
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001457err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 Py_DECREF(co);
1459 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001460}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001461
Victor Stinner53dc7352011-03-20 01:50:21 +01001462int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001463PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001464{
1465 PyObject *nameobj;
1466 int ret;
1467 nameobj = PyUnicode_InternFromString(name);
1468 if (nameobj == NULL)
1469 return -1;
1470 ret = PyImport_ImportFrozenModuleObject(nameobj);
1471 Py_DECREF(nameobj);
1472 return ret;
1473}
1474
Guido van Rossum74e6a111994-08-29 12:54:38 +00001475
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001476/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001477 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001478
Guido van Rossum79f25d91997-04-29 20:08:16 +00001479PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001480PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyObject *pname;
1483 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 pname = PyUnicode_FromString(name);
1486 if (pname == NULL)
1487 return NULL;
1488 result = PyImport_Import(pname);
1489 Py_DECREF(pname);
1490 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001491}
1492
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001493
Christian Heimes072c0f12008-01-03 23:01:04 +00001494/* Import a module without blocking
1495 *
1496 * At first it tries to fetch the module from sys.modules. If the module was
1497 * never loaded before it loads it with PyImport_ImportModule() unless another
1498 * thread holds the import lock. In the latter case the function raises an
1499 * ImportError instead of blocking.
1500 *
1501 * Returns the module object with incremented ref count.
1502 */
1503PyObject *
1504PyImport_ImportModuleNoBlock(const char *name)
1505{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001506 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001507}
1508
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001509
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001510/* Remove importlib frames from the traceback,
1511 * except in Verbose mode. */
1512static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001513remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001514{
1515 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001516 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001517 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001518 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001519 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001520 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001521 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001522
1523 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001524 from the traceback. We always trim chunks
1525 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001526
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001527 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001528 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001529 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001530 }
1531
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001532 if (PyType_IsSubtype((PyTypeObject *) exception,
1533 (PyTypeObject *) PyExc_ImportError))
1534 always_trim = 1;
1535
1536 prev_link = &base_tb;
1537 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001538 while (tb != NULL) {
1539 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1540 PyObject *next = (PyObject *) traceback->tb_next;
1541 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001542 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001543 int now_in_importlib;
1544
1545 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001546 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1547 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001548 if (now_in_importlib && !in_importlib) {
1549 /* This is the link to this chunk of importlib tracebacks */
1550 outer_link = prev_link;
1551 }
1552 in_importlib = now_in_importlib;
1553
1554 if (in_importlib &&
1555 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001556 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001557 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001558 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001559 prev_link = outer_link;
1560 }
1561 else {
1562 prev_link = (PyObject **) &traceback->tb_next;
1563 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001564 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001565 tb = next;
1566 }
1567done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001568 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001569}
1570
1571
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001572static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001573resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001574{
Brett Cannonfd074152012-04-14 14:10:13 -04001575 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001576 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001577 _Py_IDENTIFIER(parent);
1578 PyObject *abs_name;
1579 PyObject *package = NULL;
1580 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001581 Py_ssize_t last_dot;
1582 PyObject *base;
1583 int level_up;
1584
1585 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001586 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001587 goto error;
1588 }
1589 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001590 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001591 goto error;
1592 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001593 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001594 if (package == Py_None) {
1595 package = NULL;
1596 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001597 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001598 goto error;
1599 }
1600 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001601 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001602 goto error;
1603 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001604
1605 if (package != NULL) {
1606 Py_INCREF(package);
1607 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001608 _PyErr_SetString(tstate, PyExc_TypeError,
1609 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001610 goto error;
1611 }
1612 else if (spec != NULL && spec != Py_None) {
1613 int equal;
1614 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1615 if (parent == NULL) {
1616 goto error;
1617 }
1618
1619 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1620 Py_DECREF(parent);
1621 if (equal < 0) {
1622 goto error;
1623 }
1624 else if (equal == 0) {
1625 if (PyErr_WarnEx(PyExc_ImportWarning,
1626 "__package__ != __spec__.parent", 1) < 0) {
1627 goto error;
1628 }
1629 }
1630 }
1631 }
1632 else if (spec != NULL && spec != Py_None) {
1633 package = _PyObject_GetAttrId(spec, &PyId_parent);
1634 if (package == NULL) {
1635 goto error;
1636 }
1637 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001638 _PyErr_SetString(tstate, PyExc_TypeError,
1639 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001640 goto error;
1641 }
1642 }
1643 else {
1644 if (PyErr_WarnEx(PyExc_ImportWarning,
1645 "can't resolve package from __spec__ or __package__, "
1646 "falling back on __name__ and __path__", 1) < 0) {
1647 goto error;
1648 }
1649
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001650 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001651 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001652 if (!_PyErr_Occurred(tstate)) {
1653 _PyErr_SetString(tstate, PyExc_KeyError,
1654 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001655 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001656 goto error;
1657 }
1658
1659 Py_INCREF(package);
1660 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001661 _PyErr_SetString(tstate, PyExc_TypeError,
1662 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001663 goto error;
1664 }
1665
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001666 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001667 Py_ssize_t dot;
1668
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001669 if (_PyErr_Occurred(tstate) || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001670 goto error;
1671 }
1672
1673 dot = PyUnicode_FindChar(package, '.',
1674 0, PyUnicode_GET_LENGTH(package), -1);
1675 if (dot == -2) {
1676 goto error;
1677 }
Ben Lewis92420b32019-09-11 20:09:47 +10001678 else if (dot == -1) {
1679 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001680 }
Ben Lewis92420b32019-09-11 20:09:47 +10001681 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1682 if (substr == NULL) {
1683 goto error;
1684 }
1685 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001686 }
1687 }
1688
1689 last_dot = PyUnicode_GET_LENGTH(package);
1690 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001691 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001692 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001693
1694 for (level_up = 1; level_up < level; level_up += 1) {
1695 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1696 if (last_dot == -2) {
1697 goto error;
1698 }
1699 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001700 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001701 "attempted relative import beyond top-level "
1702 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001703 goto error;
1704 }
1705 }
1706
1707 base = PyUnicode_Substring(package, 0, last_dot);
1708 Py_DECREF(package);
1709 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1710 return base;
1711 }
1712
1713 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1714 Py_DECREF(base);
1715 return abs_name;
1716
Ben Lewis92420b32019-09-11 20:09:47 +10001717 no_parent_error:
1718 _PyErr_SetString(tstate, PyExc_ImportError,
1719 "attempted relative import "
1720 "with no known parent package");
1721
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001722 error:
1723 Py_XDECREF(package);
1724 return NULL;
1725}
1726
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001727static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001728import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001729{
1730 _Py_IDENTIFIER(_find_and_load);
1731 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001732 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001733 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001734 static int import_level;
1735 static _PyTime_t accumulated;
1736
1737 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1738
Steve Dowerb82e17e2019-05-23 08:45:22 -07001739 PyObject *sys_path = PySys_GetObject("path");
1740 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1741 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001742 if (_PySys_Audit(tstate, "import", "OOOOO",
1743 abs_name, Py_None, sys_path ? sys_path : Py_None,
1744 sys_meta_path ? sys_meta_path : Py_None,
1745 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001746 return NULL;
1747 }
1748
1749
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001750 /* XOptions is initialized after first some imports.
1751 * So we can't have negative cache before completed initialization.
1752 * Anyway, importlib._find_and_load is much slower than
1753 * _PyDict_GetItemIdWithError().
1754 */
1755 if (import_time) {
1756 static int header = 1;
1757 if (header) {
1758 fputs("import time: self [us] | cumulative | imported package\n",
1759 stderr);
1760 header = 0;
1761 }
1762
1763 import_level++;
1764 t1 = _PyTime_GetPerfCounter();
1765 accumulated = 0;
1766 }
1767
1768 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001769 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001770
1771 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1772 &PyId__find_and_load, abs_name,
1773 interp->import_func, NULL);
1774
1775 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001776 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001777 mod != NULL);
1778
1779 if (import_time) {
1780 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1781
1782 import_level--;
1783 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1784 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1785 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1786 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1787
1788 accumulated = accumulated_copy + cum;
1789 }
1790
1791 return mod;
1792}
1793
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001794PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001795PyImport_GetModule(PyObject *name)
1796{
1797 PyThreadState *tstate = _PyThreadState_GET();
1798 PyObject *mod;
1799
1800 mod = import_get_module(tstate, name);
1801 if (mod != NULL && mod != Py_None) {
1802 if (import_ensure_initialized(tstate, mod, name) < 0) {
1803 Py_DECREF(mod);
1804 remove_importlib_frames(tstate);
1805 return NULL;
1806 }
1807 }
1808 return mod;
1809}
1810
1811PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001812PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1813 PyObject *locals, PyObject *fromlist,
1814 int level)
1815{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001816 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001817 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001818 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001819 PyObject *final_mod = NULL;
1820 PyObject *mod = NULL;
1821 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001822 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001823 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001824
Brett Cannonfd074152012-04-14 14:10:13 -04001825 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001826 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001827 goto error;
1828 }
1829
1830 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1831 for added performance. */
1832
1833 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001834 _PyErr_SetString(tstate, PyExc_TypeError,
1835 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001836 goto error;
1837 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001838 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001839 goto error;
1840 }
1841 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001842 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001843 goto error;
1844 }
Brett Cannon849113a2016-01-22 15:25:50 -08001845
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001846 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001847 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001848 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001849 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001850 }
1851 else { /* level == 0 */
1852 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001853 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001854 goto error;
1855 }
Brett Cannonfd074152012-04-14 14:10:13 -04001856 abs_name = name;
1857 Py_INCREF(abs_name);
1858 }
1859
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001860 mod = import_get_module(tstate, abs_name);
1861 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001862 goto error;
1863 }
1864
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001865 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001866 if (import_ensure_initialized(tstate, mod, name) < 0) {
1867 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001868 }
Brett Cannonfd074152012-04-14 14:10:13 -04001869 }
1870 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001871 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001872 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001873 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001874 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001875 }
1876 }
1877
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001878 has_from = 0;
1879 if (fromlist != NULL && fromlist != Py_None) {
1880 has_from = PyObject_IsTrue(fromlist);
1881 if (has_from < 0)
1882 goto error;
1883 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001884 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001885 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1886 if (level == 0 || len > 0) {
1887 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001888
Victor Stinner744c34e2016-05-20 11:36:13 +02001889 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1890 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001891 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001892 }
1893
Victor Stinner744c34e2016-05-20 11:36:13 +02001894 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001895 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001896 final_mod = mod;
1897 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001898 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001899 }
1900
Brett Cannonfd074152012-04-14 14:10:13 -04001901 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001902 PyObject *front = PyUnicode_Substring(name, 0, dot);
1903 if (front == NULL) {
1904 goto error;
1905 }
1906
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001907 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001908 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001909 }
1910 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001911 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001912 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001913 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001914 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001915 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001916 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001917 }
Brett Cannonfd074152012-04-14 14:10:13 -04001918
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001919 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001920 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001921 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001922 if (!_PyErr_Occurred(tstate)) {
1923 _PyErr_Format(tstate, PyExc_KeyError,
1924 "%R not in sys.modules as expected",
1925 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001926 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001927 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001928 }
Brett Cannonfd074152012-04-14 14:10:13 -04001929 }
1930 }
1931 else {
1932 final_mod = mod;
1933 Py_INCREF(mod);
1934 }
1935 }
1936 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001937 PyObject *path;
1938 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1939 goto error;
1940 }
1941 if (path) {
1942 Py_DECREF(path);
1943 final_mod = _PyObject_CallMethodIdObjArgs(
1944 interp->importlib, &PyId__handle_fromlist,
1945 mod, fromlist, interp->import_func, NULL);
1946 }
1947 else {
1948 final_mod = mod;
1949 Py_INCREF(mod);
1950 }
Brett Cannonfd074152012-04-14 14:10:13 -04001951 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001952
Brett Cannonfd074152012-04-14 14:10:13 -04001953 error:
1954 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001955 Py_XDECREF(mod);
1956 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001957 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001958 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001959 }
Brett Cannonfd074152012-04-14 14:10:13 -04001960 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001961}
1962
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001963PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001964PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001965 PyObject *fromlist, int level)
1966{
1967 PyObject *nameobj, *mod;
1968 nameobj = PyUnicode_FromString(name);
1969 if (nameobj == NULL)
1970 return NULL;
1971 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1972 fromlist, level);
1973 Py_DECREF(nameobj);
1974 return mod;
1975}
1976
1977
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001978/* Re-import a module of any kind and return its module object, WITH
1979 INCREMENTED REFERENCE COUNT */
1980
Guido van Rossum79f25d91997-04-29 20:08:16 +00001981PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001982PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001983{
Robert Rouhanif40bd462020-05-01 16:28:06 -07001984 _Py_IDENTIFIER(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04001985 _Py_IDENTIFIER(reload);
1986 PyObject *reloaded_module = NULL;
Robert Rouhanif40bd462020-05-01 16:28:06 -07001987 PyObject *importlib = _PyImport_GetModuleId(&PyId_importlib);
1988 if (importlib == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001989 if (PyErr_Occurred()) {
1990 return NULL;
1991 }
1992
Robert Rouhanif40bd462020-05-01 16:28:06 -07001993 importlib = PyImport_ImportModule("importlib");
1994 if (importlib == NULL) {
Brett Cannon62228db2012-04-29 14:38:11 -04001995 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001998
Robert Rouhanif40bd462020-05-01 16:28:06 -07001999 reloaded_module = _PyObject_CallMethodIdOneArg(importlib, &PyId_reload, m);
2000 Py_DECREF(importlib);
Brett Cannon62228db2012-04-29 14:38:11 -04002001 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002002}
2003
2004
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002005/* Higher-level import emulator which emulates the "import" statement
2006 more accurately -- it invokes the __import__() function from the
2007 builtins of the current globals. This means that the import is
2008 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002009 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002010 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002011 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002012 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002013
2014PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002015PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002016{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002017 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 static PyObject *silly_list = NULL;
2019 static PyObject *builtins_str = NULL;
2020 static PyObject *import_str = NULL;
2021 PyObject *globals = NULL;
2022 PyObject *import = NULL;
2023 PyObject *builtins = NULL;
2024 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 /* Initialize constant string objects */
2027 if (silly_list == NULL) {
2028 import_str = PyUnicode_InternFromString("__import__");
2029 if (import_str == NULL)
2030 return NULL;
2031 builtins_str = PyUnicode_InternFromString("__builtins__");
2032 if (builtins_str == NULL)
2033 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002034 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if (silly_list == NULL)
2036 return NULL;
2037 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* Get the builtins from current globals */
2040 globals = PyEval_GetGlobals();
2041 if (globals != NULL) {
2042 Py_INCREF(globals);
2043 builtins = PyObject_GetItem(globals, builtins_str);
2044 if (builtins == NULL)
2045 goto err;
2046 }
2047 else {
2048 /* No globals -- use standard builtins, and fake globals */
2049 builtins = PyImport_ImportModuleLevel("builtins",
2050 NULL, NULL, NULL, 0);
2051 if (builtins == NULL)
2052 return NULL;
2053 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2054 if (globals == NULL)
2055 goto err;
2056 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 /* Get the __import__ function from the builtins */
2059 if (PyDict_Check(builtins)) {
2060 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002061 if (import == NULL) {
2062 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2063 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 }
2065 else
2066 import = PyObject_GetAttr(builtins, import_str);
2067 if (import == NULL)
2068 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002071 Always use absolute import here.
2072 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2074 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002075 if (r == NULL)
2076 goto err;
2077 Py_DECREF(r);
2078
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002079 r = import_get_module(tstate, module_name);
2080 if (r == NULL && !_PyErr_Occurred(tstate)) {
2081 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002082 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002083
2084 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 Py_XDECREF(globals);
2086 Py_XDECREF(builtins);
2087 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002090}
2091
Brett Cannon4caa61d2014-01-09 19:03:32 -05002092/*[clinic input]
2093_imp.extension_suffixes
2094
2095Returns the list of file suffixes used to identify extension modules.
2096[clinic start generated code]*/
2097
Brett Cannon4caa61d2014-01-09 19:03:32 -05002098static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002099_imp_extension_suffixes_impl(PyObject *module)
2100/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 list = PyList_New(0);
2105 if (list == NULL)
2106 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002107#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002108 const char *suffix;
2109 unsigned int index = 0;
2110
Brett Cannon2657df42012-05-04 15:20:40 -04002111 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2112 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (item == NULL) {
2114 Py_DECREF(list);
2115 return NULL;
2116 }
2117 if (PyList_Append(list, item) < 0) {
2118 Py_DECREF(list);
2119 Py_DECREF(item);
2120 return NULL;
2121 }
2122 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002123 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 }
Brett Cannon2657df42012-05-04 15:20:40 -04002125#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002127}
2128
Brett Cannon4caa61d2014-01-09 19:03:32 -05002129/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002130_imp.init_frozen
2131
2132 name: unicode
2133 /
2134
2135Initializes a frozen module.
2136[clinic start generated code]*/
2137
Brett Cannon4caa61d2014-01-09 19:03:32 -05002138static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002139_imp_init_frozen_impl(PyObject *module, PyObject *name)
2140/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002141{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002142 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 int ret;
2144 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002145
Victor Stinner53dc7352011-03-20 01:50:21 +01002146 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (ret < 0)
2148 return NULL;
2149 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002150 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002152 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 Py_XINCREF(m);
2154 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002155}
2156
Brett Cannon4caa61d2014-01-09 19:03:32 -05002157/*[clinic input]
2158_imp.get_frozen_object
2159
2160 name: unicode
2161 /
2162
2163Create a code object for a frozen module.
2164[clinic start generated code]*/
2165
Brett Cannon4caa61d2014-01-09 19:03:32 -05002166static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002167_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2168/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002171}
2172
Brett Cannon4caa61d2014-01-09 19:03:32 -05002173/*[clinic input]
2174_imp.is_frozen_package
2175
2176 name: unicode
2177 /
2178
2179Returns True if the module name is of a frozen package.
2180[clinic start generated code]*/
2181
Brett Cannon4caa61d2014-01-09 19:03:32 -05002182static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002183_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2184/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002187}
2188
Brett Cannon4caa61d2014-01-09 19:03:32 -05002189/*[clinic input]
2190_imp.is_builtin
2191
2192 name: unicode
2193 /
2194
2195Returns True if the module name corresponds to a built-in module.
2196[clinic start generated code]*/
2197
Guido van Rossum79f25d91997-04-29 20:08:16 +00002198static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002199_imp_is_builtin_impl(PyObject *module, PyObject *name)
2200/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002201{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002202 return PyLong_FromLong(is_builtin(name));
2203}
2204
2205/*[clinic input]
2206_imp.is_frozen
2207
2208 name: unicode
2209 /
2210
2211Returns True if the module name corresponds to a frozen module.
2212[clinic start generated code]*/
2213
Brett Cannon4caa61d2014-01-09 19:03:32 -05002214static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002215_imp_is_frozen_impl(PyObject *module, PyObject *name)
2216/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002217{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002218 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 p = find_frozen(name);
2221 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002222}
2223
Larry Hastings1df0b352015-08-24 19:53:56 -07002224/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2225static int
2226exec_builtin_or_dynamic(PyObject *mod) {
2227 PyModuleDef *def;
2228 void *state;
2229
2230 if (!PyModule_Check(mod)) {
2231 return 0;
2232 }
2233
2234 def = PyModule_GetDef(mod);
2235 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002236 return 0;
2237 }
Brett Cannon52794db2016-09-07 17:00:43 -07002238
Larry Hastings1df0b352015-08-24 19:53:56 -07002239 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002240 if (state) {
2241 /* Already initialized; skip reload */
2242 return 0;
2243 }
Brett Cannon52794db2016-09-07 17:00:43 -07002244
Larry Hastings1df0b352015-08-24 19:53:56 -07002245 return PyModule_ExecDef(mod, def);
2246}
2247
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002248#ifdef HAVE_DYNAMIC_LOADING
2249
Brett Cannon4caa61d2014-01-09 19:03:32 -05002250/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002251_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002252
Nick Coghland5cacbb2015-05-23 22:24:10 +10002253 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002254 file: object = NULL
2255 /
2256
Nick Coghland5cacbb2015-05-23 22:24:10 +10002257Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002258[clinic start generated code]*/
2259
Brett Cannon4caa61d2014-01-09 19:03:32 -05002260static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002261_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2262/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002263{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002264 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002265 FILE *fp;
2266
Nick Coghland5cacbb2015-05-23 22:24:10 +10002267 name = PyObject_GetAttrString(spec, "name");
2268 if (name == NULL) {
2269 return NULL;
2270 }
2271
2272 path = PyObject_GetAttrString(spec, "origin");
2273 if (path == NULL) {
2274 Py_DECREF(name);
2275 return NULL;
2276 }
2277
2278 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002279 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002280 Py_DECREF(name);
2281 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002282 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002283 return mod;
2284 }
2285
Brett Cannon4caa61d2014-01-09 19:03:32 -05002286 if (file != NULL) {
2287 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002288 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002289 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002290 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002294 else
2295 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002296
2297 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2298
2299 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002300 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 if (fp)
2302 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002303 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002304}
2305
Nick Coghland5cacbb2015-05-23 22:24:10 +10002306/*[clinic input]
2307_imp.exec_dynamic -> int
2308
2309 mod: object
2310 /
2311
2312Initialize an extension module.
2313[clinic start generated code]*/
2314
2315static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002316_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2317/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002318{
Larry Hastings1df0b352015-08-24 19:53:56 -07002319 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002320}
2321
2322
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002323#endif /* HAVE_DYNAMIC_LOADING */
2324
Larry Hastings7726ac92014-01-31 22:03:12 -08002325/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002326_imp.exec_builtin -> int
2327
2328 mod: object
2329 /
2330
2331Initialize a built-in module.
2332[clinic start generated code]*/
2333
2334static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002335_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2336/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002337{
2338 return exec_builtin_or_dynamic(mod);
2339}
2340
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002341/*[clinic input]
2342_imp.source_hash
2343
2344 key: long
2345 source: Py_buffer
2346[clinic start generated code]*/
2347
2348static PyObject *
2349_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2350/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2351{
Benjamin Peterson83620772017-12-09 12:18:56 -08002352 union {
2353 uint64_t x;
2354 char data[sizeof(uint64_t)];
2355 } hash;
2356 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002357#if !PY_LITTLE_ENDIAN
2358 // Force to little-endian. There really ought to be a succinct standard way
2359 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002360 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2361 char tmp = hash.data[i];
2362 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2363 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002364 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002365#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002366 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002367}
2368
Barry Warsaw28a691b2010-04-17 00:19:56 +00002369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002370PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002371"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002372
Guido van Rossum79f25d91997-04-29 20:08:16 +00002373static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002374 _IMP_EXTENSION_SUFFIXES_METHODDEF
2375 _IMP_LOCK_HELD_METHODDEF
2376 _IMP_ACQUIRE_LOCK_METHODDEF
2377 _IMP_RELEASE_LOCK_METHODDEF
2378 _IMP_GET_FROZEN_OBJECT_METHODDEF
2379 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002380 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002381 _IMP_INIT_FROZEN_METHODDEF
2382 _IMP_IS_BUILTIN_METHODDEF
2383 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002384 _IMP_CREATE_DYNAMIC_METHODDEF
2385 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002386 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002387 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002388 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002389 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002390};
2391
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002392
Martin v. Löwis1a214512008-06-11 05:26:20 +00002393static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002395 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 doc_imp,
2397 0,
2398 imp_methods,
2399 NULL,
2400 NULL,
2401 NULL,
2402 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002403};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002404
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002405PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002406PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002411 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002415 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002417 }
2418
Victor Stinnerda7933e2020-04-13 03:04:28 +02002419 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002420 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002421 if (pyc_mode == NULL) {
2422 goto failure;
2423 }
2424 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2425 Py_DECREF(pyc_mode);
2426 goto failure;
2427 }
2428 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002431 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 Py_XDECREF(m);
2433 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002434}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002435
2436
Guido van Rossumb18618d2000-05-03 23:44:39 +00002437/* API for embedding applications that want to add their own entries
2438 to the table of built-in modules. This should normally be called
2439 *before* Py_Initialize(). When the table resize fails, -1 is
2440 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002441
2442 After a similar function by Just van Rossum. */
2443
2444int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002445PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002448 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002449 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* Count the number of entries in both tables */
2452 for (n = 0; newtab[n].name != NULL; n++)
2453 ;
2454 if (n == 0)
2455 return 0; /* Nothing to do */
2456 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2457 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002458
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002459 /* Force default raw memory allocator to get a known allocator to be able
2460 to release the memory in _PyImport_Fini2() */
2461 PyMemAllocatorEx old_alloc;
2462 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002465 p = NULL;
2466 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002467 size_t size = sizeof(struct _inittab) * (i + n + 1);
2468 p = PyMem_RawRealloc(inittab_copy, size);
2469 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002470 if (p == NULL) {
2471 res = -1;
2472 goto done;
2473 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002474
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002475 /* Copy the tables into the new memory at the first call
2476 to PyImport_ExtendInittab(). */
2477 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002479 }
2480 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2481 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002482
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002483done:
2484 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2485 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002486}
2487
2488/* Shorthand to add a single entry given a name and a function */
2489
2490int
Brett Cannona826f322009-04-02 03:41:46 +00002491PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002496
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002497 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002501}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002502
2503#ifdef __cplusplus
2504}
2505#endif