blob: 8c94e0ec54655a3c34a2d06457239caaa16ecad5 [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);
301
302 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
303}
304
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305/* Helper for sys */
306
307PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000308PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309{
Victor Stinner81a7be32020-04-14 15:14:01 +0200310 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow3f9eee62017-09-15 16:35:20 -0600311 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100312 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600313 }
Eric Snow93c92f72017-09-13 23:46:04 -0700314 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315}
316
Eric Snowd393c1b2017-09-14 12:18:12 -0600317/* In some corner cases it is important to be sure that the import
318 machinery has been initialized (or not cleaned up yet). For
319 example, see issue #4236 and PyModule_Create2(). */
320
321int
322_PyImport_IsInitialized(PyInterpreterState *interp)
323{
324 if (interp->modules == NULL)
325 return 0;
326 return 1;
327}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000328
Eric Snow3f9eee62017-09-15 16:35:20 -0600329PyObject *
330_PyImport_GetModuleId(struct _Py_Identifier *nameid)
331{
332 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
333 if (name == NULL) {
334 return NULL;
335 }
336 return PyImport_GetModule(name);
337}
338
339int
340_PyImport_SetModule(PyObject *name, PyObject *m)
341{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200342 PyThreadState *tstate = _PyThreadState_GET();
343 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600344 return PyObject_SetItem(modules, name, m);
345}
346
347int
348_PyImport_SetModuleString(const char *name, PyObject *m)
349{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200350 PyThreadState *tstate = _PyThreadState_GET();
351 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600352 return PyMapping_SetItemString(modules, name, m);
353}
354
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200355static PyObject *
356import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600357{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200358 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600359 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200360 _PyErr_SetString(tstate, PyExc_RuntimeError,
361 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600362 return NULL;
363 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200364
365 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600366 Py_INCREF(modules);
367 if (PyDict_CheckExact(modules)) {
368 m = PyDict_GetItemWithError(modules, name); /* borrowed */
369 Py_XINCREF(m);
370 }
371 else {
372 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200373 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
374 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600375 }
376 }
377 Py_DECREF(modules);
378 return m;
379}
380
381
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100382static int
383import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200384{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100385 PyInterpreterState *interp = tstate->interp;
386 PyObject *spec;
387
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100388 _Py_IDENTIFIER(_lock_unlock_module);
389
390 /* Optimization: only call _bootstrap._lock_unlock_module() if
391 __spec__._initializing is true.
392 NOTE: because of this, initializing must be set *before*
393 stuffing the new module in sys.modules.
394 */
395 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
396 int busy = _PyModuleSpec_IsInitializing(spec);
397 Py_XDECREF(spec);
398 if (busy) {
399 /* Wait until module is done importing. */
400 PyObject *value = _PyObject_CallMethodIdOneArg(
401 interp->importlib, &PyId__lock_unlock_module, name);
402 if (value == NULL) {
403 return -1;
404 }
405 Py_DECREF(value);
406 }
407 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200408}
409
410
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000411/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200412static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 "path", "argv", "ps1", "ps2",
414 "last_type", "last_value", "last_traceback",
415 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200416 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000418};
419
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200420static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 "stdin", "__stdin__",
422 "stdout", "__stdout__",
423 "stderr", "__stderr__",
424 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000425};
426
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000427/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000428
Guido van Rossum3f5da241990-12-20 15:06:42 +0000429void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200430_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000431{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200432 PyInterpreterState *interp = tstate->interp;
433 PyObject *modules = interp->modules;
434 if (modules == NULL) {
435 /* Already done */
436 return;
437 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 /* Delete some special variables first. These are common
440 places where user values hide and people complain when their
441 destructors fail. Since the modules containing them are
442 deleted *last* of all, they would come too late in the normal
443 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000444
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200445 /* XXX Perhaps these precautions are obsolete. Who knows? */
446
Victor Stinnerda7933e2020-04-13 03:04:28 +0200447 int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200448 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200449 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200450 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300451 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300452 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300453 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200454
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200455 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200456 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200457 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200458 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200459 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300460 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300461 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200464 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200465 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200466 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200467 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200468 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
469 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200470 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200471 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200472 PyErr_WriteUnraisable(NULL);
473 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200474 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200475 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300476 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300477 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300478 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000480
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200481 /* We prepare a list which will receive (name, weakref) tuples of
482 modules when they are removed from sys.modules. The name is used
483 for diagnosis messages (in verbose mode), while the weakref helps
484 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200485 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300486 if (weaklist == NULL) {
487 PyErr_WriteUnraisable(NULL);
488 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200489
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200490#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200491 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200492 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300493 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200494 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300495 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300496 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300497 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200498 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300499 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200500 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300501 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300502 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300503 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600505#define CLEAR_MODULE(name, mod) \
506 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200507 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600508 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200509 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600510 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300511 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300512 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300513 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600514 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000515
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200516 /* Remove all modules from sys.modules, hoping that garbage collection
517 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600518 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200519 Py_ssize_t pos = 0;
520 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600521 while (PyDict_Next(modules, &pos, &key, &value)) {
522 CLEAR_MODULE(key, value);
523 }
524 }
525 else {
526 PyObject *iterator = PyObject_GetIter(modules);
527 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300528 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600529 }
530 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200531 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600532 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200533 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600534 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300535 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600536 continue;
537 }
538 CLEAR_MODULE(key, value);
539 Py_DECREF(value);
540 Py_DECREF(key);
541 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300542 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300543 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300544 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600545 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 }
547 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000548
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200549 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600550 if (PyDict_CheckExact(modules)) {
551 PyDict_Clear(modules);
552 }
553 else {
554 _Py_IDENTIFIER(clear);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200555 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300556 PyErr_WriteUnraisable(NULL);
557 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600558 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200559 /* Restore the original builtins dict, to ensure that any
560 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200561 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300562 if (dict == NULL) {
563 PyErr_WriteUnraisable(NULL);
564 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200565 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300566 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200567 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300568 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200569 Py_XDECREF(dict);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200570 /* Collect references */
571 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200572 /* Dump GC stats before it's too late, since it uses the warnings
573 machinery. */
Victor Stinner67e0de62019-11-20 11:48:18 +0100574 _PyGC_DumpShutdownStats(tstate);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200575
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200576 /* Now, if there are any modules left alive, clear their globals to
577 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200578 up here, since they are kept alive in the interpreter state.
579
580 The special treatment of "builtins" here is because even
581 when it's not referenced as a module, its dictionary is
582 referenced by almost every module's __builtins__. Since
583 deleting a module clears its dictionary (even if there are
584 references left to it), we need to delete the "builtins"
585 module last. Likewise, we don't delete sys until the very
586 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200587 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200588 Py_ssize_t i;
589 /* Since dict is ordered in CPython 3.6+, modules are saved in
590 importing order. First clear modules imported later. */
591 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200592 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200593 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200594 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
595 if (mod == Py_None)
596 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200597 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200598 dict = PyModule_GetDict(mod);
599 if (dict == interp->builtins || dict == interp->sysdict)
600 continue;
601 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200602 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200603 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200604 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200605 _PyModule_Clear(mod);
606 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200607 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200608 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000610
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200611 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200612 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200613 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200614 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200615 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200616 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200617 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200618 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200619 _PyModule_ClearDict(interp->builtins);
620
Eddie Elizondo4590f722020-02-04 02:29:25 -0800621 /* Clear module dict copies stored in the interpreter state */
622 _PyInterpreterState_ClearModules(interp);
623
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200624 /* Clear and delete the modules directory. Actual modules will
625 still be there only if imported during the execution of some
626 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700627 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200629
630 /* Once more */
631 _PyGC_CollectNoFail();
632
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300633#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200634#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000635}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000636
637
Barry Warsaw28a691b2010-04-17 00:19:56 +0000638/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000639
640long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000641PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000642{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200643 long res;
Victor Stinner81a7be32020-04-14 15:14:01 +0200644 PyInterpreterState *interp = _PyInterpreterState_GET();
Eric Snow32439d62015-05-02 19:15:18 -0600645 PyObject *external, *pyc_magic;
646
647 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
648 if (external == NULL)
649 return -1;
650 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
651 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400652 if (pyc_magic == NULL)
653 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200654 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700655 Py_DECREF(pyc_magic);
656 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000657}
658
659
Brett Cannon3adc7b72012-07-09 14:22:12 -0400660extern const char * _PySys_ImplCacheTag;
661
Barry Warsaw28a691b2010-04-17 00:19:56 +0000662const char *
663PyImport_GetMagicTag(void)
664{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400665 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000666}
667
Brett Cannon98979b82012-07-02 15:13:11 -0400668
Guido van Rossum25ce5661997-08-02 03:10:38 +0000669/* Magic for extension modules (built-in as well as dynamically
670 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200671 once, we keep a static dictionary 'extensions' keyed by the tuple
672 (module name, module name) (for built-in modules) or by
673 (filename, module name) (for dynamically loaded modules), containing these
674 modules. A copy of the module's dictionary is stored by calling
675 _PyImport_FixupExtensionObject() immediately after the module initialization
676 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100677 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000678
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000679 Modules which do support multiple initialization set their m_size
680 field to a non-negative number (indicating the size of the
681 module-specific state). They are still recorded in the extensions
682 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000683*/
684
685int
Victor Stinner95872862011-03-07 18:20:56 +0100686_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200687 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (mod == NULL || !PyModule_Check(mod)) {
690 PyErr_BadInternalCall();
691 return -1;
692 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100693
694 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (!def) {
696 PyErr_BadInternalCall();
697 return -1;
698 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100699
700 PyThreadState *tstate = _PyThreadState_GET();
701 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100703 }
704 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600705 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 return -1;
707 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100708
709 if (_Py_IsMainInterpreter(tstate)) {
710 if (def->m_size == -1) {
711 if (def->m_base.m_copy) {
712 /* Somebody already imported the module,
713 likely under a different name.
714 XXX this should really not happen. */
715 Py_CLEAR(def->m_base.m_copy);
716 }
717 PyObject *dict = PyModule_GetDict(mod);
718 if (dict == NULL) {
719 return -1;
720 }
721 def->m_base.m_copy = PyDict_Copy(dict);
722 if (def->m_base.m_copy == NULL) {
723 return -1;
724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100726
727 if (extensions == NULL) {
728 extensions = PyDict_New();
729 if (extensions == NULL) {
730 return -1;
731 }
732 }
733
734 PyObject *key = PyTuple_Pack(2, filename, name);
735 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100737 }
738 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
739 Py_DECREF(key);
740 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000746}
747
Victor Stinner49d3f252010-10-17 01:24:53 +0000748int
Eric Snowd393c1b2017-09-14 12:18:12 -0600749_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000750{
751 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100752 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100753 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100754 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000755 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600756 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100757 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000758 return res;
759}
760
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200761static PyObject *
762import_find_extension(PyThreadState *tstate, PyObject *name,
763 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000764{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200765 if (extensions == NULL) {
766 return NULL;
767 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600768
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200769 PyObject *key = PyTuple_Pack(2, filename, name);
770 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200772 }
773 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500774 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200775 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200777 }
778
779 PyObject *mod, *mdict;
780 PyObject *modules = tstate->interp->modules;
781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (def->m_size == -1) {
783 /* Module does not support repeated initialization */
784 if (def->m_base.m_copy == NULL)
785 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200786 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (mod == NULL)
788 return NULL;
789 mdict = PyModule_GetDict(mod);
790 if (mdict == NULL)
791 return NULL;
792 if (PyDict_Update(mdict, def->m_base.m_copy))
793 return NULL;
794 }
795 else {
796 if (def->m_base.m_init == NULL)
797 return NULL;
798 mod = def->m_base.m_init();
799 if (mod == NULL)
800 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600801 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200802 Py_DECREF(mod);
803 return NULL;
804 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_DECREF(mod);
806 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100807 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600808 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 return NULL;
810 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200811
Victor Stinnerda7933e2020-04-13 03:04:28 +0200812 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200813 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100814 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200815 name, filename);
816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000818}
819
Victor Stinner49d3f252010-10-17 01:24:53 +0000820PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200821_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
822{
823 PyThreadState *tstate = _PyThreadState_GET();
824 return import_find_extension(tstate, name, filename);
825}
826
827
828PyObject *
829_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000830{
Victor Stinner95872862011-03-07 18:20:56 +0100831 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100832 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100833 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000834 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200835 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100836 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000837 return res;
838}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000839
840/* Get the module object corresponding to a module name.
841 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000842 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000843 Because the former action is most common, THIS DOES NOT RETURN A
844 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000845
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200846static PyObject *
847import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000848{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200849 PyObject *modules = tstate->interp->modules;
850 if (modules == NULL) {
851 _PyErr_SetString(tstate, PyExc_RuntimeError,
852 "no import module dictionary");
853 return NULL;
854 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600855
Eric Snow86b7afd2017-09-04 17:54:09 -0600856 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600857 if (PyDict_CheckExact(modules)) {
858 m = PyDict_GetItemWithError(modules, name);
859 }
860 else {
861 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000862 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600863 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200864 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
865 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600866 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200867 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200868 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200869 return NULL;
870 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600871 if (m != NULL && PyModule_Check(m)) {
872 return m;
873 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000874 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 if (m == NULL)
876 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600877 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 Py_DECREF(m);
879 return NULL;
880 }
881 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884}
885
Victor Stinner27ee0892011-03-04 12:57:09 +0000886PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200887PyImport_AddModuleObject(PyObject *name)
888{
889 PyThreadState *tstate = _PyThreadState_GET();
890 return import_add_module(tstate, name);
891}
892
893
894PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000895PyImport_AddModule(const char *name)
896{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200897 PyObject *nameobj = PyUnicode_FromString(name);
898 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000899 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200900 }
901 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000902 Py_DECREF(nameobj);
903 return module;
904}
905
906
Tim Peters1cd70172004-08-02 03:52:12 +0000907/* Remove name from sys.modules, if it's there. */
908static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200909remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000910{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600911 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200912 _PyErr_Fetch(tstate, &type, &value, &traceback);
913
914 PyObject *modules = tstate->interp->modules;
Zackery Spytz94a64e92019-05-08 10:31:23 -0600915 if (!PyMapping_HasKey(modules, name)) {
916 goto out;
917 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600918 if (PyMapping_DelItem(modules, name) < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200919 _PyErr_SetString(tstate, PyExc_RuntimeError,
920 "deleting key in sys.modules failed");
921 _PyErr_ChainExceptions(type, value, traceback);
922 return;
Eric Snow3f9eee62017-09-15 16:35:20 -0600923 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200924
Zackery Spytz94a64e92019-05-08 10:31:23 -0600925out:
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200926 _PyErr_Restore(tstate, type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000927}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000928
Christian Heimes3b06e532008-01-07 20:12:44 +0000929
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000930/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000931 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
932 * removed from sys.modules, to avoid leaving damaged module objects
933 * in sys.modules. The caller may wish to restore the original
934 * module object (if any) in this case; PyImport_ReloadModule is an
935 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000936 *
937 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
938 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000939 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000940PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300941PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 return PyImport_ExecCodeModuleWithPathnames(
944 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000945}
946
947PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300948PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 return PyImport_ExecCodeModuleWithPathnames(
951 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000952}
953
954PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300955PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
956 const char *pathname,
957 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000958{
Victor Stinner27ee0892011-03-04 12:57:09 +0000959 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600960 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000961
962 nameobj = PyUnicode_FromString(name);
963 if (nameobj == NULL)
964 return NULL;
965
Victor Stinner27ee0892011-03-04 12:57:09 +0000966 if (cpathname != NULL) {
967 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
968 if (cpathobj == NULL)
969 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400970 }
971 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000972 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400973
974 if (pathname != NULL) {
975 pathobj = PyUnicode_DecodeFSDefault(pathname);
976 if (pathobj == NULL)
977 goto error;
978 }
979 else if (cpathobj != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200980 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannona6473f92012-07-13 13:57:03 -0400981 _Py_IDENTIFIER(_get_sourcefile);
982
983 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100984 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400985 }
986
Eric Snow32439d62015-05-02 19:15:18 -0600987 external= PyObject_GetAttrString(interp->importlib,
988 "_bootstrap_external");
989 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200990 pathobj = _PyObject_CallMethodIdOneArg(
991 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600992 Py_DECREF(external);
993 }
Brett Cannona6473f92012-07-13 13:57:03 -0400994 if (pathobj == NULL)
995 PyErr_Clear();
996 }
997 else
998 pathobj = NULL;
999
Victor Stinner27ee0892011-03-04 12:57:09 +00001000 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
1001error:
1002 Py_DECREF(nameobj);
1003 Py_XDECREF(pathobj);
1004 Py_XDECREF(cpathobj);
1005 return m;
1006}
1007
Brett Cannon18fc4e72014-04-04 10:01:46 -04001008static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001009module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +00001010{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001011 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001012 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001013
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001014 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (m == NULL)
1016 return NULL;
1017 /* If the module is being reloaded, we get the old module back
1018 and re-use its dict to exec the new code. */
1019 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001020 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001021 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001022 _PyDict_SetItemId(d, &PyId___builtins__,
1023 PyEval_GetBuiltins()) != 0)
1024 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001025 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001026 return NULL;
1027 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001029
Eric Snow08197a42014-05-12 17:54:55 -06001030 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001031}
1032
1033static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001034exec_code_in_module(PyThreadState *tstate, PyObject *name,
1035 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001036{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001037 PyObject *v, *m;
1038
1039 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1040 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001041 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001042 return NULL;
1043 }
1044 Py_DECREF(v);
1045
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001046 m = import_get_module(tstate, name);
1047 if (m == NULL && !_PyErr_Occurred(tstate)) {
1048 _PyErr_Format(tstate, PyExc_ImportError,
1049 "Loaded module %R not found in sys.modules",
1050 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001051 }
1052
Brett Cannon18fc4e72014-04-04 10:01:46 -04001053 return m;
1054}
1055
1056PyObject*
1057PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1058 PyObject *cpathname)
1059{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001060 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001061 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001062 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001063
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001064 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001065 if (d == NULL) {
1066 return NULL;
1067 }
1068
Eric Snow08197a42014-05-12 17:54:55 -06001069 if (pathname == NULL) {
1070 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001072 external = PyObject_GetAttrString(tstate->interp->importlib,
1073 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001074 if (external == NULL)
1075 return NULL;
1076 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001077 &PyId__fix_up_module,
1078 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001079 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001080 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001081 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001082 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
Eric Snow08197a42014-05-12 17:54:55 -06001084 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001085}
1086
1087
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001088static void
1089update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyObject *constants, *tmp;
1092 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (PyUnicode_Compare(co->co_filename, oldname))
1095 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001096
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001097 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001098 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 constants = co->co_consts;
1101 n = PyTuple_GET_SIZE(constants);
1102 for (i = 0; i < n; i++) {
1103 tmp = PyTuple_GET_ITEM(constants, i);
1104 if (PyCode_Check(tmp))
1105 update_code_filenames((PyCodeObject *)tmp,
1106 oldname, newname);
1107 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001108}
1109
Victor Stinner2f42ae52011-03-20 00:41:24 +01001110static void
1111update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001112{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001113 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001114
Victor Stinner2f42ae52011-03-20 00:41:24 +01001115 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1116 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 oldname = co->co_filename;
1119 Py_INCREF(oldname);
1120 update_code_filenames(co, oldname, newname);
1121 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001122}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001123
Brett Cannon4caa61d2014-01-09 19:03:32 -05001124/*[clinic input]
1125_imp._fix_co_filename
1126
1127 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1128 Code object to change.
1129
1130 path: unicode
1131 File path to use.
1132 /
1133
1134Changes code.co_filename to specify the passed-in file path.
1135[clinic start generated code]*/
1136
Brett Cannon4caa61d2014-01-09 19:03:32 -05001137static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001138_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001139 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001140/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001141
Brett Cannon4caa61d2014-01-09 19:03:32 -05001142{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001143 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001144
1145 Py_RETURN_NONE;
1146}
1147
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001148
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001149/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001150static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001151
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001152
1153/* Helper to test for built-in module */
1154
1155static int
Victor Stinner95872862011-03-07 18:20:56 +01001156is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001157{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001158 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001160 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (PyImport_Inittab[i].initfunc == NULL)
1162 return -1;
1163 else
1164 return 1;
1165 }
1166 }
1167 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001168}
1169
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001170
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001171/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001172 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001173 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001174 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001175 this tells our caller that the path based finder could not find
1176 a finder for this path item. Cache the result in
1177 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001178 Returns a borrowed reference. */
1179
1180static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001181get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1182 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 PyObject *importer;
1185 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 /* These conditions are the caller's responsibility: */
1188 assert(PyList_Check(path_hooks));
1189 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 nhooks = PyList_Size(path_hooks);
1192 if (nhooks < 0)
1193 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001194
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001195 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001196 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 /* set path_importer_cache[p] to None to avoid recursion */
1200 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1201 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 for (j = 0; j < nhooks; j++) {
1204 PyObject *hook = PyList_GetItem(path_hooks, j);
1205 if (hook == NULL)
1206 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +01001207 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (importer != NULL)
1209 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001210
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001211 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 return NULL;
1213 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001214 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
1216 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001217 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 }
1219 if (importer != NULL) {
1220 int err = PyDict_SetItem(path_importer_cache, p, importer);
1221 Py_DECREF(importer);
1222 if (err != 0)
1223 return NULL;
1224 }
1225 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001226}
1227
Benjamin Petersone5024512018-09-12 12:06:42 -07001228PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001229PyImport_GetImporter(PyObject *path)
1230{
1231 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001233
Victor Stinner1e53bba2013-07-16 22:26:05 +02001234 path_importer_cache = PySys_GetObject("path_importer_cache");
1235 path_hooks = PySys_GetObject("path_hooks");
1236 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001237 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001238 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 }
1240 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1241 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001242}
1243
Nick Coghland5cacbb2015-05-23 22:24:10 +10001244/*[clinic input]
1245_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246
Nick Coghland5cacbb2015-05-23 22:24:10 +10001247 spec: object
1248 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001249
Nick Coghland5cacbb2015-05-23 22:24:10 +10001250Create an extension module.
1251[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001252
Nick Coghland5cacbb2015-05-23 22:24:10 +10001253static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001254_imp_create_builtin(PyObject *module, PyObject *spec)
1255/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001256{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001257 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001259 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001260 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001261 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001262
Nick Coghland5cacbb2015-05-23 22:24:10 +10001263 name = PyObject_GetAttrString(spec, "name");
1264 if (name == NULL) {
1265 return NULL;
1266 }
1267
Victor Stinner5eb4f592013-11-14 22:38:52 +01001268 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001269 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001270 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001271 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001272 return mod;
1273 }
1274
1275 namestr = PyUnicode_AsUTF8(name);
1276 if (namestr == NULL) {
1277 Py_DECREF(name);
1278 return NULL;
1279 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001280
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001281 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001283 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001284 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001286 /* Cannot re-init internal module ("sys" or "builtins") */
1287 mod = PyImport_AddModule(namestr);
1288 Py_DECREF(name);
1289 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001292 if (mod == NULL) {
1293 Py_DECREF(name);
1294 return NULL;
1295 }
1296 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1297 Py_DECREF(name);
1298 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1299 } else {
1300 /* Remember pointer to module init function. */
1301 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001302 if (def == NULL) {
1303 Py_DECREF(name);
1304 return NULL;
1305 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001306 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001307 if (_PyImport_FixupExtensionObject(mod, name, name,
1308 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001309 Py_DECREF(name);
1310 return NULL;
1311 }
1312 Py_DECREF(name);
1313 return mod;
1314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 }
1316 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001317 Py_DECREF(name);
1318 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001319}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001320
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001321
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001322/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001323
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001324static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001325find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001326{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001327 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001328
Victor Stinner53dc7352011-03-20 01:50:21 +01001329 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 for (p = PyImport_FrozenModules; ; p++) {
1333 if (p->name == NULL)
1334 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001335 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 break;
1337 }
1338 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001339}
1340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001342get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001343{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001344 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (p == NULL) {
1348 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001349 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 name);
1351 return NULL;
1352 }
1353 if (p->code == NULL) {
1354 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001355 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 name);
1357 return NULL;
1358 }
1359 size = p->size;
1360 if (size < 0)
1361 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001362 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001363}
1364
Brett Cannon8d110132009-03-15 02:20:16 +00001365static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001366is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001367{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001368 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (p == NULL) {
1372 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001373 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 name);
1375 return NULL;
1376 }
Brett Cannon8d110132009-03-15 02:20:16 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (size < 0)
1381 Py_RETURN_TRUE;
1382 else
1383 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001384}
1385
1386
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001387/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001388 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001389 an exception set if the initialization failed.
1390 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001391
1392int
Victor Stinner53dc7352011-03-20 01:50:21 +01001393PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001394{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001395 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001396 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001397 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 int ispackage;
1399 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001400
Victor Stinner53dc7352011-03-20 01:50:21 +01001401 p = find_frozen(name);
1402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (p == NULL)
1404 return 0;
1405 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001406 _PyErr_Format(tstate, PyExc_ImportError,
1407 "Excluded frozen object named %R",
1408 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 return -1;
1410 }
1411 size = p->size;
1412 ispackage = (size < 0);
1413 if (ispackage)
1414 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001415 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (co == NULL)
1417 return -1;
1418 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001419 _PyErr_Format(tstate, PyExc_TypeError,
1420 "frozen object %R is not a code object",
1421 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 goto err_return;
1423 }
1424 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001425 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001426 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001428 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 if (m == NULL)
1430 goto err_return;
1431 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001432 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 goto err_return;
1435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 err = PyDict_SetItemString(d, "__path__", l);
1437 Py_DECREF(l);
1438 if (err != 0)
1439 goto err_return;
1440 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001441 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001442 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001443 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001444 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001445 m = exec_code_in_module(tstate, name, d, co);
1446 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 Py_DECREF(co);
1450 Py_DECREF(m);
1451 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001452
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001453err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_DECREF(co);
1455 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001456}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001457
Victor Stinner53dc7352011-03-20 01:50:21 +01001458int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001459PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001460{
1461 PyObject *nameobj;
1462 int ret;
1463 nameobj = PyUnicode_InternFromString(name);
1464 if (nameobj == NULL)
1465 return -1;
1466 ret = PyImport_ImportFrozenModuleObject(nameobj);
1467 Py_DECREF(nameobj);
1468 return ret;
1469}
1470
Guido van Rossum74e6a111994-08-29 12:54:38 +00001471
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001472/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001473 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001474
Guido van Rossum79f25d91997-04-29 20:08:16 +00001475PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001476PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyObject *pname;
1479 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 pname = PyUnicode_FromString(name);
1482 if (pname == NULL)
1483 return NULL;
1484 result = PyImport_Import(pname);
1485 Py_DECREF(pname);
1486 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001487}
1488
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001489
Christian Heimes072c0f12008-01-03 23:01:04 +00001490/* Import a module without blocking
1491 *
1492 * At first it tries to fetch the module from sys.modules. If the module was
1493 * never loaded before it loads it with PyImport_ImportModule() unless another
1494 * thread holds the import lock. In the latter case the function raises an
1495 * ImportError instead of blocking.
1496 *
1497 * Returns the module object with incremented ref count.
1498 */
1499PyObject *
1500PyImport_ImportModuleNoBlock(const char *name)
1501{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001502 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001503}
1504
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001505
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001506/* Remove importlib frames from the traceback,
1507 * except in Verbose mode. */
1508static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001509remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001510{
1511 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001512 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001513 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001514 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001515 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001516 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001517 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001518
1519 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001520 from the traceback. We always trim chunks
1521 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001522
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001523 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
Victor Stinnerda7933e2020-04-13 03:04:28 +02001524 if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001525 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001526 }
1527
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001528 if (PyType_IsSubtype((PyTypeObject *) exception,
1529 (PyTypeObject *) PyExc_ImportError))
1530 always_trim = 1;
1531
1532 prev_link = &base_tb;
1533 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001534 while (tb != NULL) {
1535 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1536 PyObject *next = (PyObject *) traceback->tb_next;
1537 PyFrameObject *frame = traceback->tb_frame;
Victor Stinnera42ca742020-04-28 19:01:31 +02001538 PyCodeObject *code = PyFrame_GetCode(frame);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001539 int now_in_importlib;
1540
1541 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001542 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1543 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001544 if (now_in_importlib && !in_importlib) {
1545 /* This is the link to this chunk of importlib tracebacks */
1546 outer_link = prev_link;
1547 }
1548 in_importlib = now_in_importlib;
1549
1550 if (in_importlib &&
1551 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001552 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001553 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001554 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001555 prev_link = outer_link;
1556 }
1557 else {
1558 prev_link = (PyObject **) &traceback->tb_next;
1559 }
Victor Stinner8852ad42020-04-29 01:28:13 +02001560 Py_DECREF(code);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001561 tb = next;
1562 }
1563done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001564 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001565}
1566
1567
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001568static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001569resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001570{
Brett Cannonfd074152012-04-14 14:10:13 -04001571 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001572 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001573 _Py_IDENTIFIER(parent);
1574 PyObject *abs_name;
1575 PyObject *package = NULL;
1576 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001577 Py_ssize_t last_dot;
1578 PyObject *base;
1579 int level_up;
1580
1581 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001582 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001583 goto error;
1584 }
1585 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001586 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001587 goto error;
1588 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001589 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001590 if (package == Py_None) {
1591 package = NULL;
1592 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001593 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001594 goto error;
1595 }
1596 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001597 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001598 goto error;
1599 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001600
1601 if (package != NULL) {
1602 Py_INCREF(package);
1603 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001604 _PyErr_SetString(tstate, PyExc_TypeError,
1605 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001606 goto error;
1607 }
1608 else if (spec != NULL && spec != Py_None) {
1609 int equal;
1610 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1611 if (parent == NULL) {
1612 goto error;
1613 }
1614
1615 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1616 Py_DECREF(parent);
1617 if (equal < 0) {
1618 goto error;
1619 }
1620 else if (equal == 0) {
1621 if (PyErr_WarnEx(PyExc_ImportWarning,
1622 "__package__ != __spec__.parent", 1) < 0) {
1623 goto error;
1624 }
1625 }
1626 }
1627 }
1628 else if (spec != NULL && spec != Py_None) {
1629 package = _PyObject_GetAttrId(spec, &PyId_parent);
1630 if (package == NULL) {
1631 goto error;
1632 }
1633 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001634 _PyErr_SetString(tstate, PyExc_TypeError,
1635 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001636 goto error;
1637 }
1638 }
1639 else {
1640 if (PyErr_WarnEx(PyExc_ImportWarning,
1641 "can't resolve package from __spec__ or __package__, "
1642 "falling back on __name__ and __path__", 1) < 0) {
1643 goto error;
1644 }
1645
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001646 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001647 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001648 if (!_PyErr_Occurred(tstate)) {
1649 _PyErr_SetString(tstate, PyExc_KeyError,
1650 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001651 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001652 goto error;
1653 }
1654
1655 Py_INCREF(package);
1656 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001657 _PyErr_SetString(tstate, PyExc_TypeError,
1658 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001659 goto error;
1660 }
1661
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001662 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001663 Py_ssize_t dot;
1664
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001665 if (_PyErr_Occurred(tstate) || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001666 goto error;
1667 }
1668
1669 dot = PyUnicode_FindChar(package, '.',
1670 0, PyUnicode_GET_LENGTH(package), -1);
1671 if (dot == -2) {
1672 goto error;
1673 }
Ben Lewis92420b32019-09-11 20:09:47 +10001674 else if (dot == -1) {
1675 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001676 }
Ben Lewis92420b32019-09-11 20:09:47 +10001677 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1678 if (substr == NULL) {
1679 goto error;
1680 }
1681 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001682 }
1683 }
1684
1685 last_dot = PyUnicode_GET_LENGTH(package);
1686 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001687 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001688 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001689
1690 for (level_up = 1; level_up < level; level_up += 1) {
1691 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1692 if (last_dot == -2) {
1693 goto error;
1694 }
1695 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001696 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001697 "attempted relative import beyond top-level "
1698 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001699 goto error;
1700 }
1701 }
1702
1703 base = PyUnicode_Substring(package, 0, last_dot);
1704 Py_DECREF(package);
1705 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1706 return base;
1707 }
1708
1709 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1710 Py_DECREF(base);
1711 return abs_name;
1712
Ben Lewis92420b32019-09-11 20:09:47 +10001713 no_parent_error:
1714 _PyErr_SetString(tstate, PyExc_ImportError,
1715 "attempted relative import "
1716 "with no known parent package");
1717
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001718 error:
1719 Py_XDECREF(package);
1720 return NULL;
1721}
1722
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001723static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001724import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001725{
1726 _Py_IDENTIFIER(_find_and_load);
1727 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001728 PyInterpreterState *interp = tstate->interp;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001729 int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001730 static int import_level;
1731 static _PyTime_t accumulated;
1732
1733 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1734
Steve Dowerb82e17e2019-05-23 08:45:22 -07001735 PyObject *sys_path = PySys_GetObject("path");
1736 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1737 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001738 if (_PySys_Audit(tstate, "import", "OOOOO",
1739 abs_name, Py_None, sys_path ? sys_path : Py_None,
1740 sys_meta_path ? sys_meta_path : Py_None,
1741 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001742 return NULL;
1743 }
1744
1745
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001746 /* XOptions is initialized after first some imports.
1747 * So we can't have negative cache before completed initialization.
1748 * Anyway, importlib._find_and_load is much slower than
1749 * _PyDict_GetItemIdWithError().
1750 */
1751 if (import_time) {
1752 static int header = 1;
1753 if (header) {
1754 fputs("import time: self [us] | cumulative | imported package\n",
1755 stderr);
1756 header = 0;
1757 }
1758
1759 import_level++;
1760 t1 = _PyTime_GetPerfCounter();
1761 accumulated = 0;
1762 }
1763
1764 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001765 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001766
1767 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1768 &PyId__find_and_load, abs_name,
1769 interp->import_func, NULL);
1770
1771 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001772 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001773 mod != NULL);
1774
1775 if (import_time) {
1776 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1777
1778 import_level--;
1779 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1780 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1781 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1782 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1783
1784 accumulated = accumulated_copy + cum;
1785 }
1786
1787 return mod;
1788}
1789
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001790PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001791PyImport_GetModule(PyObject *name)
1792{
1793 PyThreadState *tstate = _PyThreadState_GET();
1794 PyObject *mod;
1795
1796 mod = import_get_module(tstate, name);
1797 if (mod != NULL && mod != Py_None) {
1798 if (import_ensure_initialized(tstate, mod, name) < 0) {
1799 Py_DECREF(mod);
1800 remove_importlib_frames(tstate);
1801 return NULL;
1802 }
1803 }
1804 return mod;
1805}
1806
1807PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001808PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1809 PyObject *locals, PyObject *fromlist,
1810 int level)
1811{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001812 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001813 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001814 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001815 PyObject *final_mod = NULL;
1816 PyObject *mod = NULL;
1817 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001818 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001819 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001820
Brett Cannonfd074152012-04-14 14:10:13 -04001821 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001822 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001823 goto error;
1824 }
1825
1826 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1827 for added performance. */
1828
1829 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001830 _PyErr_SetString(tstate, PyExc_TypeError,
1831 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001832 goto error;
1833 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001834 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001835 goto error;
1836 }
1837 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001838 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001839 goto error;
1840 }
Brett Cannon849113a2016-01-22 15:25:50 -08001841
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001842 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001843 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001844 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001845 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001846 }
1847 else { /* level == 0 */
1848 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001849 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001850 goto error;
1851 }
Brett Cannonfd074152012-04-14 14:10:13 -04001852 abs_name = name;
1853 Py_INCREF(abs_name);
1854 }
1855
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001856 mod = import_get_module(tstate, abs_name);
1857 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001858 goto error;
1859 }
1860
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001861 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001862 if (import_ensure_initialized(tstate, mod, name) < 0) {
1863 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001864 }
Brett Cannonfd074152012-04-14 14:10:13 -04001865 }
1866 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001867 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001868 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001869 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001870 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001871 }
1872 }
1873
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001874 has_from = 0;
1875 if (fromlist != NULL && fromlist != Py_None) {
1876 has_from = PyObject_IsTrue(fromlist);
1877 if (has_from < 0)
1878 goto error;
1879 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001880 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001881 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1882 if (level == 0 || len > 0) {
1883 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001884
Victor Stinner744c34e2016-05-20 11:36:13 +02001885 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1886 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001887 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001888 }
1889
Victor Stinner744c34e2016-05-20 11:36:13 +02001890 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001891 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001892 final_mod = mod;
1893 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001894 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001895 }
1896
Brett Cannonfd074152012-04-14 14:10:13 -04001897 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001898 PyObject *front = PyUnicode_Substring(name, 0, dot);
1899 if (front == NULL) {
1900 goto error;
1901 }
1902
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001903 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001904 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001905 }
1906 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001907 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001908 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001909 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001910 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001911 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001912 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001913 }
Brett Cannonfd074152012-04-14 14:10:13 -04001914
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001915 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001916 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001917 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001918 if (!_PyErr_Occurred(tstate)) {
1919 _PyErr_Format(tstate, PyExc_KeyError,
1920 "%R not in sys.modules as expected",
1921 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001922 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001923 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001924 }
Brett Cannonfd074152012-04-14 14:10:13 -04001925 }
1926 }
1927 else {
1928 final_mod = mod;
1929 Py_INCREF(mod);
1930 }
1931 }
1932 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001933 PyObject *path;
1934 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1935 goto error;
1936 }
1937 if (path) {
1938 Py_DECREF(path);
1939 final_mod = _PyObject_CallMethodIdObjArgs(
1940 interp->importlib, &PyId__handle_fromlist,
1941 mod, fromlist, interp->import_func, NULL);
1942 }
1943 else {
1944 final_mod = mod;
1945 Py_INCREF(mod);
1946 }
Brett Cannonfd074152012-04-14 14:10:13 -04001947 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001948
Brett Cannonfd074152012-04-14 14:10:13 -04001949 error:
1950 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001951 Py_XDECREF(mod);
1952 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001953 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001954 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001955 }
Brett Cannonfd074152012-04-14 14:10:13 -04001956 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001957}
1958
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001959PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001960PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001961 PyObject *fromlist, int level)
1962{
1963 PyObject *nameobj, *mod;
1964 nameobj = PyUnicode_FromString(name);
1965 if (nameobj == NULL)
1966 return NULL;
1967 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1968 fromlist, level);
1969 Py_DECREF(nameobj);
1970 return mod;
1971}
1972
1973
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001974/* Re-import a module of any kind and return its module object, WITH
1975 INCREMENTED REFERENCE COUNT */
1976
Guido van Rossum79f25d91997-04-29 20:08:16 +00001977PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001978PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001979{
Eric Snow3f9eee62017-09-15 16:35:20 -06001980 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001981 _Py_IDENTIFIER(reload);
1982 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001983 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001984 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001985 if (PyErr_Occurred()) {
1986 return NULL;
1987 }
1988
Brett Cannon62228db2012-04-29 14:38:11 -04001989 imp = PyImport_ImportModule("imp");
1990 if (imp == NULL) {
1991 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001994
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001995 reloaded_module = _PyObject_CallMethodIdOneArg(imp, &PyId_reload, m);
Brett Cannon62228db2012-04-29 14:38:11 -04001996 Py_DECREF(imp);
1997 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001998}
1999
2000
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002001/* Higher-level import emulator which emulates the "import" statement
2002 more accurately -- it invokes the __import__() function from the
2003 builtins of the current globals. This means that the import is
2004 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002005 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002006 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002007 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002008 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002009
2010PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002011PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002012{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002013 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 static PyObject *silly_list = NULL;
2015 static PyObject *builtins_str = NULL;
2016 static PyObject *import_str = NULL;
2017 PyObject *globals = NULL;
2018 PyObject *import = NULL;
2019 PyObject *builtins = NULL;
2020 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* Initialize constant string objects */
2023 if (silly_list == NULL) {
2024 import_str = PyUnicode_InternFromString("__import__");
2025 if (import_str == NULL)
2026 return NULL;
2027 builtins_str = PyUnicode_InternFromString("__builtins__");
2028 if (builtins_str == NULL)
2029 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002030 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (silly_list == NULL)
2032 return NULL;
2033 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* Get the builtins from current globals */
2036 globals = PyEval_GetGlobals();
2037 if (globals != NULL) {
2038 Py_INCREF(globals);
2039 builtins = PyObject_GetItem(globals, builtins_str);
2040 if (builtins == NULL)
2041 goto err;
2042 }
2043 else {
2044 /* No globals -- use standard builtins, and fake globals */
2045 builtins = PyImport_ImportModuleLevel("builtins",
2046 NULL, NULL, NULL, 0);
2047 if (builtins == NULL)
2048 return NULL;
2049 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2050 if (globals == NULL)
2051 goto err;
2052 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 /* Get the __import__ function from the builtins */
2055 if (PyDict_Check(builtins)) {
2056 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002057 if (import == NULL) {
2058 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2059 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 }
2061 else
2062 import = PyObject_GetAttr(builtins, import_str);
2063 if (import == NULL)
2064 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002067 Always use absolute import here.
2068 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2070 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002071 if (r == NULL)
2072 goto err;
2073 Py_DECREF(r);
2074
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002075 r = import_get_module(tstate, module_name);
2076 if (r == NULL && !_PyErr_Occurred(tstate)) {
2077 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002078 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002079
2080 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 Py_XDECREF(globals);
2082 Py_XDECREF(builtins);
2083 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002086}
2087
Brett Cannon4caa61d2014-01-09 19:03:32 -05002088/*[clinic input]
2089_imp.extension_suffixes
2090
2091Returns the list of file suffixes used to identify extension modules.
2092[clinic start generated code]*/
2093
Brett Cannon4caa61d2014-01-09 19:03:32 -05002094static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002095_imp_extension_suffixes_impl(PyObject *module)
2096/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 list = PyList_New(0);
2101 if (list == NULL)
2102 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002103#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002104 const char *suffix;
2105 unsigned int index = 0;
2106
Brett Cannon2657df42012-05-04 15:20:40 -04002107 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2108 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (item == NULL) {
2110 Py_DECREF(list);
2111 return NULL;
2112 }
2113 if (PyList_Append(list, item) < 0) {
2114 Py_DECREF(list);
2115 Py_DECREF(item);
2116 return NULL;
2117 }
2118 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002119 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 }
Brett Cannon2657df42012-05-04 15:20:40 -04002121#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002123}
2124
Brett Cannon4caa61d2014-01-09 19:03:32 -05002125/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002126_imp.init_frozen
2127
2128 name: unicode
2129 /
2130
2131Initializes a frozen module.
2132[clinic start generated code]*/
2133
Brett Cannon4caa61d2014-01-09 19:03:32 -05002134static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002135_imp_init_frozen_impl(PyObject *module, PyObject *name)
2136/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002137{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002138 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 int ret;
2140 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002141
Victor Stinner53dc7352011-03-20 01:50:21 +01002142 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (ret < 0)
2144 return NULL;
2145 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002146 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002148 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_XINCREF(m);
2150 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002151}
2152
Brett Cannon4caa61d2014-01-09 19:03:32 -05002153/*[clinic input]
2154_imp.get_frozen_object
2155
2156 name: unicode
2157 /
2158
2159Create a code object for a frozen module.
2160[clinic start generated code]*/
2161
Brett Cannon4caa61d2014-01-09 19:03:32 -05002162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002163_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2164/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002167}
2168
Brett Cannon4caa61d2014-01-09 19:03:32 -05002169/*[clinic input]
2170_imp.is_frozen_package
2171
2172 name: unicode
2173 /
2174
2175Returns True if the module name is of a frozen package.
2176[clinic start generated code]*/
2177
Brett Cannon4caa61d2014-01-09 19:03:32 -05002178static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002179_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2180/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002183}
2184
Brett Cannon4caa61d2014-01-09 19:03:32 -05002185/*[clinic input]
2186_imp.is_builtin
2187
2188 name: unicode
2189 /
2190
2191Returns True if the module name corresponds to a built-in module.
2192[clinic start generated code]*/
2193
Guido van Rossum79f25d91997-04-29 20:08:16 +00002194static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002195_imp_is_builtin_impl(PyObject *module, PyObject *name)
2196/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002197{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002198 return PyLong_FromLong(is_builtin(name));
2199}
2200
2201/*[clinic input]
2202_imp.is_frozen
2203
2204 name: unicode
2205 /
2206
2207Returns True if the module name corresponds to a frozen module.
2208[clinic start generated code]*/
2209
Brett Cannon4caa61d2014-01-09 19:03:32 -05002210static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002211_imp_is_frozen_impl(PyObject *module, PyObject *name)
2212/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002213{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002214 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 p = find_frozen(name);
2217 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002218}
2219
Larry Hastings1df0b352015-08-24 19:53:56 -07002220/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2221static int
2222exec_builtin_or_dynamic(PyObject *mod) {
2223 PyModuleDef *def;
2224 void *state;
2225
2226 if (!PyModule_Check(mod)) {
2227 return 0;
2228 }
2229
2230 def = PyModule_GetDef(mod);
2231 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002232 return 0;
2233 }
Brett Cannon52794db2016-09-07 17:00:43 -07002234
Larry Hastings1df0b352015-08-24 19:53:56 -07002235 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002236 if (state) {
2237 /* Already initialized; skip reload */
2238 return 0;
2239 }
Brett Cannon52794db2016-09-07 17:00:43 -07002240
Larry Hastings1df0b352015-08-24 19:53:56 -07002241 return PyModule_ExecDef(mod, def);
2242}
2243
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002244#ifdef HAVE_DYNAMIC_LOADING
2245
Brett Cannon4caa61d2014-01-09 19:03:32 -05002246/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002247_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002248
Nick Coghland5cacbb2015-05-23 22:24:10 +10002249 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002250 file: object = NULL
2251 /
2252
Nick Coghland5cacbb2015-05-23 22:24:10 +10002253Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002254[clinic start generated code]*/
2255
Brett Cannon4caa61d2014-01-09 19:03:32 -05002256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002257_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2258/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002259{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002260 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002261 FILE *fp;
2262
Nick Coghland5cacbb2015-05-23 22:24:10 +10002263 name = PyObject_GetAttrString(spec, "name");
2264 if (name == NULL) {
2265 return NULL;
2266 }
2267
2268 path = PyObject_GetAttrString(spec, "origin");
2269 if (path == NULL) {
2270 Py_DECREF(name);
2271 return NULL;
2272 }
2273
2274 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002275 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002276 Py_DECREF(name);
2277 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002278 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002279 return mod;
2280 }
2281
Brett Cannon4caa61d2014-01-09 19:03:32 -05002282 if (file != NULL) {
2283 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002284 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002285 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002286 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002288 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002290 else
2291 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002292
2293 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2294
2295 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002296 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 if (fp)
2298 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002299 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002300}
2301
Nick Coghland5cacbb2015-05-23 22:24:10 +10002302/*[clinic input]
2303_imp.exec_dynamic -> int
2304
2305 mod: object
2306 /
2307
2308Initialize an extension module.
2309[clinic start generated code]*/
2310
2311static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002312_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2313/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002314{
Larry Hastings1df0b352015-08-24 19:53:56 -07002315 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002316}
2317
2318
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002319#endif /* HAVE_DYNAMIC_LOADING */
2320
Larry Hastings7726ac92014-01-31 22:03:12 -08002321/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002322_imp.exec_builtin -> int
2323
2324 mod: object
2325 /
2326
2327Initialize a built-in module.
2328[clinic start generated code]*/
2329
2330static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002331_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2332/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002333{
2334 return exec_builtin_or_dynamic(mod);
2335}
2336
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002337/*[clinic input]
2338_imp.source_hash
2339
2340 key: long
2341 source: Py_buffer
2342[clinic start generated code]*/
2343
2344static PyObject *
2345_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2346/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2347{
Benjamin Peterson83620772017-12-09 12:18:56 -08002348 union {
2349 uint64_t x;
2350 char data[sizeof(uint64_t)];
2351 } hash;
2352 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002353#if !PY_LITTLE_ENDIAN
2354 // Force to little-endian. There really ought to be a succinct standard way
2355 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002356 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2357 char tmp = hash.data[i];
2358 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2359 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002360 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002361#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002362 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002363}
2364
Barry Warsaw28a691b2010-04-17 00:19:56 +00002365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002366PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002367"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002368
Guido van Rossum79f25d91997-04-29 20:08:16 +00002369static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002370 _IMP_EXTENSION_SUFFIXES_METHODDEF
2371 _IMP_LOCK_HELD_METHODDEF
2372 _IMP_ACQUIRE_LOCK_METHODDEF
2373 _IMP_RELEASE_LOCK_METHODDEF
2374 _IMP_GET_FROZEN_OBJECT_METHODDEF
2375 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002376 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002377 _IMP_INIT_FROZEN_METHODDEF
2378 _IMP_IS_BUILTIN_METHODDEF
2379 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002380 _IMP_CREATE_DYNAMIC_METHODDEF
2381 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002382 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002383 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002384 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002385 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002386};
2387
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002388
Martin v. Löwis1a214512008-06-11 05:26:20 +00002389static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002391 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 doc_imp,
2393 0,
2394 imp_methods,
2395 NULL,
2396 NULL,
2397 NULL,
2398 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002399};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002400
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002401PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002402PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002407 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002411 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002413 }
2414
Victor Stinnerda7933e2020-04-13 03:04:28 +02002415 const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002416 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002417 if (pyc_mode == NULL) {
2418 goto failure;
2419 }
2420 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2421 Py_DECREF(pyc_mode);
2422 goto failure;
2423 }
2424 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002427 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 Py_XDECREF(m);
2429 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002430}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002431
2432
Guido van Rossumb18618d2000-05-03 23:44:39 +00002433/* API for embedding applications that want to add their own entries
2434 to the table of built-in modules. This should normally be called
2435 *before* Py_Initialize(). When the table resize fails, -1 is
2436 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002437
2438 After a similar function by Just van Rossum. */
2439
2440int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002441PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002444 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002445 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* Count the number of entries in both tables */
2448 for (n = 0; newtab[n].name != NULL; n++)
2449 ;
2450 if (n == 0)
2451 return 0; /* Nothing to do */
2452 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2453 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002454
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002455 /* Force default raw memory allocator to get a known allocator to be able
2456 to release the memory in _PyImport_Fini2() */
2457 PyMemAllocatorEx old_alloc;
2458 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002461 p = NULL;
2462 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002463 size_t size = sizeof(struct _inittab) * (i + n + 1);
2464 p = PyMem_RawRealloc(inittab_copy, size);
2465 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002466 if (p == NULL) {
2467 res = -1;
2468 goto done;
2469 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002470
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002471 /* Copy the tables into the new memory at the first call
2472 to PyImport_ExtendInittab(). */
2473 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002475 }
2476 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2477 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002478
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002479done:
2480 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2481 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002482}
2483
2484/* Shorthand to add a single entry given a name and a function */
2485
2486int
Brett Cannona826f322009-04-02 03:41:46 +00002487PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002492
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002493 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002497}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002498
2499#ifdef __cplusplus
2500}
2501#endif