blob: 2e434561f63c5dbb3b6092601040d6fe1138111d [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module definition and import implementation */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner61691d82019-10-02 23:51:20 +02007#include "pycore_initconfig.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02008#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pyhash.h"
10#include "pycore_pylifecycle.h"
11#include "pycore_pymem.h"
12#include "pycore_pystate.h"
Victor Stinner1c1e68c2020-03-27 15:11:45 +010013#include "pycore_sysmodule.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000015#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020017#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000018#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000019#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020020#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000021
Guido van Rossum55a83382000-09-20 20:31:38 +000022#ifdef HAVE_FCNTL_H
23#include <fcntl.h>
24#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000026extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000028
Barry Warsaw28a691b2010-04-17 00:19:56 +000029#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000030
Victor Stinner0a28f8d2019-06-19 02:54:39 +020031/* Forward references */
32static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
33
Victor Stinner95872862011-03-07 18:20:56 +010034/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000035static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000036
Guido van Rossum771c6c81997-10-31 18:37:24 +000037/* This table is defined in config.c: */
38extern struct _inittab _PyImport_Inittab[];
39
40struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010041static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000042
Hai Shi46874c22020-01-30 17:20:25 -060043_Py_IDENTIFIER(__path__);
44_Py_IDENTIFIER(__spec__);
45
Brett Cannon4caa61d2014-01-09 19:03:32 -050046/*[clinic input]
47module _imp
48[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030049/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040050
51#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050052
Guido van Rossum1ae940a1995-01-02 19:04:15 +000053/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054
Victor Stinner331a6a52019-05-27 16:39:22 +020055PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020056_PyImportHooks_Init(PyThreadState *tstate)
Just van Rossum52e14d62002-12-30 22:08:05 +000057{
Brett Cannonfd074152012-04-14 14:10:13 -040058 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000060
Brett Cannonfd074152012-04-14 14:10:13 -040061 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 v = PyList_New(0);
63 if (v == NULL)
64 goto error;
65 err = PySys_SetObject("meta_path", v);
66 Py_DECREF(v);
67 if (err)
68 goto error;
69 v = PyDict_New();
70 if (v == NULL)
71 goto error;
72 err = PySys_SetObject("path_importer_cache", v);
73 Py_DECREF(v);
74 if (err)
75 goto error;
76 path_hooks = PyList_New(0);
77 if (path_hooks == NULL)
78 goto error;
79 err = PySys_SetObject("path_hooks", path_hooks);
80 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 }
Brett Cannonfd074152012-04-14 14:10:13 -040083 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020084 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080085
86 error:
Victor Stinnerb45d2592019-06-20 00:05:23 +020087 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020088 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080089 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040090}
91
Victor Stinner331a6a52019-05-27 16:39:22 +020092PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020093_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040094{
ukwksk5e6312c2018-05-15 04:10:52 +090095 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040096 int err = 0;
97
98 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020099 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200100 _PyErr_SetString(tstate, PyExc_RuntimeError,
101 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400102 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200103 }
Brett Cannonfd074152012-04-14 14:10:13 -0400104
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200105 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200106 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400107 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200108 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109
ukwksk5e6312c2018-05-15 04:10:52 +0900110 zipimport = PyImport_ImportModule("zipimport");
111 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200112 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200113 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 }
117 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200118 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900119 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200120 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900121 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200123 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200124 if (verbose) {
125 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 }
128 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400129 /* sys.path_hooks.insert(0, zipimporter) */
130 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400132 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400134 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200135 if (verbose) {
136 PySys_WriteStderr("# installed zipimport hook\n");
137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 }
139 }
Brett Cannonfd074152012-04-14 14:10:13 -0400140
Victor Stinner331a6a52019-05-27 16:39:22 +0200141 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400142
143 error:
144 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200145 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000146}
147
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148/* Locking primitives to prevent parallel imports of the same module
149 in different threads to return with a partially loaded module.
150 These calls are serialized by the global interpreter lock. */
151
Guido van Rossum49b56061998-10-01 20:42:43 +0000152#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153
Guido van Rossum65d5b571998-12-21 19:32:43 +0000154static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200155static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156static int import_lock_level = 0;
157
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000158void
159_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000160{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200161 unsigned long me = PyThread_get_thread_ident();
162 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 return; /* Too bad */
164 if (import_lock == NULL) {
165 import_lock = PyThread_allocate_lock();
166 if (import_lock == NULL)
167 return; /* Nothing much we can do. */
168 }
169 if (import_lock_thread == me) {
170 import_lock_level++;
171 return;
172 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200173 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
174 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 {
176 PyThreadState *tstate = PyEval_SaveThread();
177 PyThread_acquire_lock(import_lock, 1);
178 PyEval_RestoreThread(tstate);
179 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100180 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 import_lock_thread = me;
182 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000183}
184
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000185int
186_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000187{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200188 unsigned long me = PyThread_get_thread_ident();
189 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 return 0; /* Too bad */
191 if (import_lock_thread != me)
192 return -1;
193 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100194 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200196 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 PyThread_release_lock(import_lock);
198 }
199 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000200}
201
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200202/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000203 created child processes do not share locks with the parent.
204 We now acquire the import lock around fork() calls but on some platforms
205 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000206
207void
208_PyImport_ReInitLock(void)
209{
Christian Heimes418fd742015-04-19 21:08:42 +0200210 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200212 if (import_lock == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100213 _Py_FatalErrorFunc(__func__, "failed to create a new lock");
Christian Heimes418fd742015-04-19 21:08:42 +0200214 }
215 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000216 if (import_lock_level > 1) {
217 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200218 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500219 /* The following could fail if the lock is already held, but forking as
220 a side-effect of an import is a) rare, b) nuts, and c) difficult to
221 do thanks to the lock only being held when doing individual module
222 locks per import. */
223 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000224 import_lock_thread = me;
225 import_lock_level--;
226 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200227 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000228 import_lock_level = 0;
229 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000230}
231
Brett Cannon4caa61d2014-01-09 19:03:32 -0500232/*[clinic input]
233_imp.lock_held
234
235Return True if the import lock is currently held, else False.
236
237On platforms without threads, return False.
238[clinic start generated code]*/
239
Brett Cannon4caa61d2014-01-09 19:03:32 -0500240static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300241_imp_lock_held_impl(PyObject *module)
242/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000243{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200244 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000245}
246
Brett Cannon4caa61d2014-01-09 19:03:32 -0500247/*[clinic input]
248_imp.acquire_lock
249
250Acquires the interpreter's import lock for the current thread.
251
252This lock should be used by import hooks to ensure thread-safety when importing
253modules. On platforms without threads, this function does nothing.
254[clinic start generated code]*/
255
Brett Cannon4caa61d2014-01-09 19:03:32 -0500256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300257_imp_acquire_lock_impl(PyObject *module)
258/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200261 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000262}
263
Brett Cannon4caa61d2014-01-09 19:03:32 -0500264/*[clinic input]
265_imp.release_lock
266
267Release the interpreter's import lock.
268
269On platforms without threads, this function does nothing.
270[clinic start generated code]*/
271
Brett Cannon4caa61d2014-01-09 19:03:32 -0500272static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300273_imp_release_lock_impl(PyObject *module)
274/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 if (_PyImport_ReleaseLock() < 0) {
277 PyErr_SetString(PyExc_RuntimeError,
278 "not holding the import lock");
279 return NULL;
280 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200281 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000282}
283
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100284void
285_PyImport_Fini(void)
286{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200287 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100288 if (import_lock != NULL) {
289 PyThread_free_lock(import_lock);
290 import_lock = NULL;
291 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100292}
293
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100294void
295_PyImport_Fini2(void)
296{
297 /* Use the same memory allocator than PyImport_ExtendInittab(). */
298 PyMemAllocatorEx old_alloc;
299 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
300
301 /* Free memory allocated by PyImport_ExtendInittab() */
302 PyMem_RawFree(inittab_copy);
303
304 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
305}
306
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307/* Helper for sys */
308
309PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000310PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000311{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200312 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow3f9eee62017-09-15 16:35:20 -0600313 if (interp->modules == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100314 Py_FatalError("interpreter has no modules dictionary");
Eric Snow3f9eee62017-09-15 16:35:20 -0600315 }
Eric Snow93c92f72017-09-13 23:46:04 -0700316 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317}
318
Eric Snowd393c1b2017-09-14 12:18:12 -0600319/* In some corner cases it is important to be sure that the import
320 machinery has been initialized (or not cleaned up yet). For
321 example, see issue #4236 and PyModule_Create2(). */
322
323int
324_PyImport_IsInitialized(PyInterpreterState *interp)
325{
326 if (interp->modules == NULL)
327 return 0;
328 return 1;
329}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000330
Eric Snow3f9eee62017-09-15 16:35:20 -0600331PyObject *
332_PyImport_GetModuleId(struct _Py_Identifier *nameid)
333{
334 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
335 if (name == NULL) {
336 return NULL;
337 }
338 return PyImport_GetModule(name);
339}
340
341int
342_PyImport_SetModule(PyObject *name, PyObject *m)
343{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200344 PyThreadState *tstate = _PyThreadState_GET();
345 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600346 return PyObject_SetItem(modules, name, m);
347}
348
349int
350_PyImport_SetModuleString(const char *name, PyObject *m)
351{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200352 PyThreadState *tstate = _PyThreadState_GET();
353 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600354 return PyMapping_SetItemString(modules, name, m);
355}
356
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200357static PyObject *
358import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600359{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200360 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600361 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200362 _PyErr_SetString(tstate, PyExc_RuntimeError,
363 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600364 return NULL;
365 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200366
367 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600368 Py_INCREF(modules);
369 if (PyDict_CheckExact(modules)) {
370 m = PyDict_GetItemWithError(modules, name); /* borrowed */
371 Py_XINCREF(m);
372 }
373 else {
374 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200375 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
376 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600377 }
378 }
379 Py_DECREF(modules);
380 return m;
381}
382
383
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100384static int
385import_ensure_initialized(PyThreadState *tstate, PyObject *mod, PyObject *name)
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200386{
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100387 PyInterpreterState *interp = tstate->interp;
388 PyObject *spec;
389
Joannah Nanjekye37c22202019-09-11 13:47:39 +0100390 _Py_IDENTIFIER(_lock_unlock_module);
391
392 /* Optimization: only call _bootstrap._lock_unlock_module() if
393 __spec__._initializing is true.
394 NOTE: because of this, initializing must be set *before*
395 stuffing the new module in sys.modules.
396 */
397 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
398 int busy = _PyModuleSpec_IsInitializing(spec);
399 Py_XDECREF(spec);
400 if (busy) {
401 /* Wait until module is done importing. */
402 PyObject *value = _PyObject_CallMethodIdOneArg(
403 interp->importlib, &PyId__lock_unlock_module, name);
404 if (value == NULL) {
405 return -1;
406 }
407 Py_DECREF(value);
408 }
409 return 0;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200410}
411
412
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000413/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200414static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 "path", "argv", "ps1", "ps2",
416 "last_type", "last_value", "last_traceback",
417 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200418 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000420};
421
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200422static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 "stdin", "__stdin__",
424 "stdout", "__stdout__",
425 "stderr", "__stderr__",
426 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000427};
428
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000429/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000430
Guido van Rossum3f5da241990-12-20 15:06:42 +0000431void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200432_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000433{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200434 PyInterpreterState *interp = tstate->interp;
435 PyObject *modules = interp->modules;
436 if (modules == NULL) {
437 /* Already done */
438 return;
439 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 /* Delete some special variables first. These are common
442 places where user values hide and people complain when their
443 destructors fail. Since the modules containing them are
444 deleted *last* of all, they would come too late in the normal
445 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000446
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200447 /* XXX Perhaps these precautions are obsolete. Who knows? */
448
Victor Stinner331a6a52019-05-27 16:39:22 +0200449 int verbose = interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200450 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200451 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200452 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300453 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300454 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300455 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200456
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200457 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200458 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200459 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200460 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200461 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300462 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300463 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200466 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200467 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200468 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200469 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200470 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
471 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200472 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200473 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200474 PyErr_WriteUnraisable(NULL);
475 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200476 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200477 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300478 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300479 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000482
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200483 /* We prepare a list which will receive (name, weakref) tuples of
484 modules when they are removed from sys.modules. The name is used
485 for diagnosis messages (in verbose mode), while the weakref helps
486 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200487 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300488 if (weaklist == NULL) {
489 PyErr_WriteUnraisable(NULL);
490 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200491
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200492#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200493 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200494 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300495 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200496 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300497 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300498 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300499 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200500 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300501 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200502 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300503 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300504 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300505 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600507#define CLEAR_MODULE(name, mod) \
508 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200509 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600510 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200511 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600512 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300513 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300514 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300515 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600516 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000517
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200518 /* Remove all modules from sys.modules, hoping that garbage collection
519 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600520 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200521 Py_ssize_t pos = 0;
522 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600523 while (PyDict_Next(modules, &pos, &key, &value)) {
524 CLEAR_MODULE(key, value);
525 }
526 }
527 else {
528 PyObject *iterator = PyObject_GetIter(modules);
529 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300530 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600531 }
532 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200533 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600534 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200535 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600536 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300537 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600538 continue;
539 }
540 CLEAR_MODULE(key, value);
541 Py_DECREF(value);
542 Py_DECREF(key);
543 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300544 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300545 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300546 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600547 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 }
549 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000550
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200551 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600552 if (PyDict_CheckExact(modules)) {
553 PyDict_Clear(modules);
554 }
555 else {
556 _Py_IDENTIFIER(clear);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200557 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300558 PyErr_WriteUnraisable(NULL);
559 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600560 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200561 /* Restore the original builtins dict, to ensure that any
562 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200563 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300564 if (dict == NULL) {
565 PyErr_WriteUnraisable(NULL);
566 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200567 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300568 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200569 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300570 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200571 Py_XDECREF(dict);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200572 /* Collect references */
573 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200574 /* Dump GC stats before it's too late, since it uses the warnings
575 machinery. */
Victor Stinner67e0de62019-11-20 11:48:18 +0100576 _PyGC_DumpShutdownStats(tstate);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200577
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200578 /* Now, if there are any modules left alive, clear their globals to
579 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200580 up here, since they are kept alive in the interpreter state.
581
582 The special treatment of "builtins" here is because even
583 when it's not referenced as a module, its dictionary is
584 referenced by almost every module's __builtins__. Since
585 deleting a module clears its dictionary (even if there are
586 references left to it), we need to delete the "builtins"
587 module last. Likewise, we don't delete sys until the very
588 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200589 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200590 Py_ssize_t i;
591 /* Since dict is ordered in CPython 3.6+, modules are saved in
592 importing order. First clear modules imported later. */
593 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200594 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200595 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200596 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
597 if (mod == Py_None)
598 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200599 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200600 dict = PyModule_GetDict(mod);
601 if (dict == interp->builtins || dict == interp->sysdict)
602 continue;
603 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200604 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200605 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200606 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200607 _PyModule_Clear(mod);
608 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200609 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200610 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000612
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200613 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200614 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200615 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200616 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200617 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200618 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200619 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200620 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200621 _PyModule_ClearDict(interp->builtins);
622
Eddie Elizondo4590f722020-02-04 02:29:25 -0800623 /* Clear module dict copies stored in the interpreter state */
624 _PyInterpreterState_ClearModules(interp);
625
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200626 /* Clear and delete the modules directory. Actual modules will
627 still be there only if imported during the execution of some
628 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700629 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200631
632 /* Once more */
633 _PyGC_CollectNoFail();
634
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300635#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200636#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000637}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000638
639
Barry Warsaw28a691b2010-04-17 00:19:56 +0000640/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000641
642long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000643PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000644{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200645 long res;
Victor Stinnerff4584c2020-03-13 18:03:56 +0100646 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow32439d62015-05-02 19:15:18 -0600647 PyObject *external, *pyc_magic;
648
649 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
650 if (external == NULL)
651 return -1;
652 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
653 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400654 if (pyc_magic == NULL)
655 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200656 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700657 Py_DECREF(pyc_magic);
658 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000659}
660
661
Brett Cannon3adc7b72012-07-09 14:22:12 -0400662extern const char * _PySys_ImplCacheTag;
663
Barry Warsaw28a691b2010-04-17 00:19:56 +0000664const char *
665PyImport_GetMagicTag(void)
666{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400667 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000668}
669
Brett Cannon98979b82012-07-02 15:13:11 -0400670
Guido van Rossum25ce5661997-08-02 03:10:38 +0000671/* Magic for extension modules (built-in as well as dynamically
672 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200673 once, we keep a static dictionary 'extensions' keyed by the tuple
674 (module name, module name) (for built-in modules) or by
675 (filename, module name) (for dynamically loaded modules), containing these
676 modules. A copy of the module's dictionary is stored by calling
677 _PyImport_FixupExtensionObject() immediately after the module initialization
678 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100679 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000681 Modules which do support multiple initialization set their m_size
682 field to a non-negative number (indicating the size of the
683 module-specific state). They are still recorded in the extensions
684 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000685*/
686
687int
Victor Stinner95872862011-03-07 18:20:56 +0100688_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200689 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (mod == NULL || !PyModule_Check(mod)) {
692 PyErr_BadInternalCall();
693 return -1;
694 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100695
696 struct PyModuleDef *def = PyModule_GetDef(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (!def) {
698 PyErr_BadInternalCall();
699 return -1;
700 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100701
702 PyThreadState *tstate = _PyThreadState_GET();
703 if (PyObject_SetItem(modules, name, mod) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100705 }
706 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600707 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return -1;
709 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100710
711 if (_Py_IsMainInterpreter(tstate)) {
712 if (def->m_size == -1) {
713 if (def->m_base.m_copy) {
714 /* Somebody already imported the module,
715 likely under a different name.
716 XXX this should really not happen. */
717 Py_CLEAR(def->m_base.m_copy);
718 }
719 PyObject *dict = PyModule_GetDict(mod);
720 if (dict == NULL) {
721 return -1;
722 }
723 def->m_base.m_copy = PyDict_Copy(dict);
724 if (def->m_base.m_copy == NULL) {
725 return -1;
726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100728
729 if (extensions == NULL) {
730 extensions = PyDict_New();
731 if (extensions == NULL) {
732 return -1;
733 }
734 }
735
736 PyObject *key = PyTuple_Pack(2, filename, name);
737 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100739 }
740 int res = PyDict_SetItem(extensions, key, (PyObject *)def);
741 Py_DECREF(key);
742 if (res < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100744 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000748}
749
Victor Stinner49d3f252010-10-17 01:24:53 +0000750int
Eric Snowd393c1b2017-09-14 12:18:12 -0600751_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000752{
753 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100754 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100755 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100756 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000757 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600758 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100759 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000760 return res;
761}
762
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200763static PyObject *
764import_find_extension(PyThreadState *tstate, PyObject *name,
765 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000766{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200767 if (extensions == NULL) {
768 return NULL;
769 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600770
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200771 PyObject *key = PyTuple_Pack(2, filename, name);
772 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200774 }
775 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500776 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200777 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200779 }
780
781 PyObject *mod, *mdict;
782 PyObject *modules = tstate->interp->modules;
783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (def->m_size == -1) {
785 /* Module does not support repeated initialization */
786 if (def->m_base.m_copy == NULL)
787 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200788 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (mod == NULL)
790 return NULL;
791 mdict = PyModule_GetDict(mod);
792 if (mdict == NULL)
793 return NULL;
794 if (PyDict_Update(mdict, def->m_base.m_copy))
795 return NULL;
796 }
797 else {
798 if (def->m_base.m_init == NULL)
799 return NULL;
800 mod = def->m_base.m_init();
801 if (mod == NULL)
802 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600803 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200804 Py_DECREF(mod);
805 return NULL;
806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 Py_DECREF(mod);
808 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100809 if (_PyState_AddModule(tstate, mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600810 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return NULL;
812 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200813
814 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200815 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100816 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200817 name, filename);
818 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000820}
821
Victor Stinner49d3f252010-10-17 01:24:53 +0000822PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200823_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
824{
825 PyThreadState *tstate = _PyThreadState_GET();
826 return import_find_extension(tstate, name, filename);
827}
828
829
830PyObject *
831_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000832{
Victor Stinner95872862011-03-07 18:20:56 +0100833 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100834 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100835 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000836 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200837 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100838 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000839 return res;
840}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000841
842/* Get the module object corresponding to a module name.
843 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000844 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000845 Because the former action is most common, THIS DOES NOT RETURN A
846 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000847
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200848static PyObject *
849import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000850{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200851 PyObject *modules = tstate->interp->modules;
852 if (modules == NULL) {
853 _PyErr_SetString(tstate, PyExc_RuntimeError,
854 "no import module dictionary");
855 return NULL;
856 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600857
Eric Snow86b7afd2017-09-04 17:54:09 -0600858 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600859 if (PyDict_CheckExact(modules)) {
860 m = PyDict_GetItemWithError(modules, name);
861 }
862 else {
863 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000864 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600865 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200866 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
867 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600868 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200869 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200870 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200871 return NULL;
872 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600873 if (m != NULL && PyModule_Check(m)) {
874 return m;
875 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000876 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (m == NULL)
878 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600879 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 Py_DECREF(m);
881 return NULL;
882 }
883 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886}
887
Victor Stinner27ee0892011-03-04 12:57:09 +0000888PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200889PyImport_AddModuleObject(PyObject *name)
890{
891 PyThreadState *tstate = _PyThreadState_GET();
892 return import_add_module(tstate, name);
893}
894
895
896PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000897PyImport_AddModule(const char *name)
898{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200899 PyObject *nameobj = PyUnicode_FromString(name);
900 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000901 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200902 }
903 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000904 Py_DECREF(nameobj);
905 return module;
906}
907
908
Tim Peters1cd70172004-08-02 03:52:12 +0000909/* Remove name from sys.modules, if it's there. */
910static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200911remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000912{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600913 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200914 _PyErr_Fetch(tstate, &type, &value, &traceback);
915
916 PyObject *modules = tstate->interp->modules;
Zackery Spytz94a64e92019-05-08 10:31:23 -0600917 if (!PyMapping_HasKey(modules, name)) {
918 goto out;
919 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600920 if (PyMapping_DelItem(modules, name) < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200921 _PyErr_SetString(tstate, PyExc_RuntimeError,
922 "deleting key in sys.modules failed");
923 _PyErr_ChainExceptions(type, value, traceback);
924 return;
Eric Snow3f9eee62017-09-15 16:35:20 -0600925 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200926
Zackery Spytz94a64e92019-05-08 10:31:23 -0600927out:
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200928 _PyErr_Restore(tstate, type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000929}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000930
Christian Heimes3b06e532008-01-07 20:12:44 +0000931
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000932/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000933 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
934 * removed from sys.modules, to avoid leaving damaged module objects
935 * in sys.modules. The caller may wish to restore the original
936 * module object (if any) in this case; PyImport_ReloadModule is an
937 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000938 *
939 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
940 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000941 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000942PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300943PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 return PyImport_ExecCodeModuleWithPathnames(
946 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000947}
948
949PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300950PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return PyImport_ExecCodeModuleWithPathnames(
953 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000954}
955
956PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300957PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
958 const char *pathname,
959 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000960{
Victor Stinner27ee0892011-03-04 12:57:09 +0000961 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600962 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000963
964 nameobj = PyUnicode_FromString(name);
965 if (nameobj == NULL)
966 return NULL;
967
Victor Stinner27ee0892011-03-04 12:57:09 +0000968 if (cpathname != NULL) {
969 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
970 if (cpathobj == NULL)
971 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400972 }
973 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000974 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400975
976 if (pathname != NULL) {
977 pathobj = PyUnicode_DecodeFSDefault(pathname);
978 if (pathobj == NULL)
979 goto error;
980 }
981 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200982 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400983 _Py_IDENTIFIER(_get_sourcefile);
984
985 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100986 Py_FatalError("no current interpreter");
Brett Cannona6473f92012-07-13 13:57:03 -0400987 }
988
Eric Snow32439d62015-05-02 19:15:18 -0600989 external= PyObject_GetAttrString(interp->importlib,
990 "_bootstrap_external");
991 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200992 pathobj = _PyObject_CallMethodIdOneArg(
993 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600994 Py_DECREF(external);
995 }
Brett Cannona6473f92012-07-13 13:57:03 -0400996 if (pathobj == NULL)
997 PyErr_Clear();
998 }
999 else
1000 pathobj = NULL;
1001
Victor Stinner27ee0892011-03-04 12:57:09 +00001002 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
1003error:
1004 Py_DECREF(nameobj);
1005 Py_XDECREF(pathobj);
1006 Py_XDECREF(cpathobj);
1007 return m;
1008}
1009
Brett Cannon18fc4e72014-04-04 10:01:46 -04001010static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001011module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +00001012{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001013 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001014 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001015
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001016 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (m == NULL)
1018 return NULL;
1019 /* If the module is being reloaded, we get the old module back
1020 and re-use its dict to exec the new code. */
1021 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001022 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001023 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001024 _PyDict_SetItemId(d, &PyId___builtins__,
1025 PyEval_GetBuiltins()) != 0)
1026 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001027 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001028 return NULL;
1029 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001031
Eric Snow08197a42014-05-12 17:54:55 -06001032 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001033}
1034
1035static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001036exec_code_in_module(PyThreadState *tstate, PyObject *name,
1037 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001038{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001039 PyObject *v, *m;
1040
1041 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1042 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001043 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001044 return NULL;
1045 }
1046 Py_DECREF(v);
1047
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001048 m = import_get_module(tstate, name);
1049 if (m == NULL && !_PyErr_Occurred(tstate)) {
1050 _PyErr_Format(tstate, PyExc_ImportError,
1051 "Loaded module %R not found in sys.modules",
1052 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001053 }
1054
Brett Cannon18fc4e72014-04-04 10:01:46 -04001055 return m;
1056}
1057
1058PyObject*
1059PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1060 PyObject *cpathname)
1061{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001062 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001063 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001064 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001065
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001066 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001067 if (d == NULL) {
1068 return NULL;
1069 }
1070
Eric Snow08197a42014-05-12 17:54:55 -06001071 if (pathname == NULL) {
1072 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001074 external = PyObject_GetAttrString(tstate->interp->importlib,
1075 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001076 if (external == NULL)
1077 return NULL;
1078 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001079 &PyId__fix_up_module,
1080 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001081 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001082 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001083 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001084 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 }
Eric Snow08197a42014-05-12 17:54:55 -06001086 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001087}
1088
1089
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001090static void
1091update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyObject *constants, *tmp;
1094 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (PyUnicode_Compare(co->co_filename, oldname))
1097 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001098
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001099 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001100 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 constants = co->co_consts;
1103 n = PyTuple_GET_SIZE(constants);
1104 for (i = 0; i < n; i++) {
1105 tmp = PyTuple_GET_ITEM(constants, i);
1106 if (PyCode_Check(tmp))
1107 update_code_filenames((PyCodeObject *)tmp,
1108 oldname, newname);
1109 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001110}
1111
Victor Stinner2f42ae52011-03-20 00:41:24 +01001112static void
1113update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001114{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001115 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001116
Victor Stinner2f42ae52011-03-20 00:41:24 +01001117 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1118 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 oldname = co->co_filename;
1121 Py_INCREF(oldname);
1122 update_code_filenames(co, oldname, newname);
1123 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001124}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001125
Brett Cannon4caa61d2014-01-09 19:03:32 -05001126/*[clinic input]
1127_imp._fix_co_filename
1128
1129 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1130 Code object to change.
1131
1132 path: unicode
1133 File path to use.
1134 /
1135
1136Changes code.co_filename to specify the passed-in file path.
1137[clinic start generated code]*/
1138
Brett Cannon4caa61d2014-01-09 19:03:32 -05001139static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001140_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001141 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001142/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001143
Brett Cannon4caa61d2014-01-09 19:03:32 -05001144{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001145 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001146
1147 Py_RETURN_NONE;
1148}
1149
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001150
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001151/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001152static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001153
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001154
1155/* Helper to test for built-in module */
1156
1157static int
Victor Stinner95872862011-03-07 18:20:56 +01001158is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001159{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001160 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001162 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (PyImport_Inittab[i].initfunc == NULL)
1164 return -1;
1165 else
1166 return 1;
1167 }
1168 }
1169 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001170}
1171
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001172
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001173/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001174 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001175 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001176 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001177 this tells our caller that the path based finder could not find
1178 a finder for this path item. Cache the result in
1179 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001180 Returns a borrowed reference. */
1181
1182static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001183get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1184 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyObject *importer;
1187 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 /* These conditions are the caller's responsibility: */
1190 assert(PyList_Check(path_hooks));
1191 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 nhooks = PyList_Size(path_hooks);
1194 if (nhooks < 0)
1195 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001196
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001197 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001198 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 /* set path_importer_cache[p] to None to avoid recursion */
1202 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1203 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 for (j = 0; j < nhooks; j++) {
1206 PyObject *hook = PyList_GetItem(path_hooks, j);
1207 if (hook == NULL)
1208 return NULL;
Petr Viktorinffd97532020-02-11 17:46:57 +01001209 importer = PyObject_CallOneArg(hook, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 if (importer != NULL)
1211 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001212
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001213 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return NULL;
1215 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001216 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 }
1218 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001219 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 }
1221 if (importer != NULL) {
1222 int err = PyDict_SetItem(path_importer_cache, p, importer);
1223 Py_DECREF(importer);
1224 if (err != 0)
1225 return NULL;
1226 }
1227 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001228}
1229
Benjamin Petersone5024512018-09-12 12:06:42 -07001230PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001231PyImport_GetImporter(PyObject *path)
1232{
1233 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001235
Victor Stinner1e53bba2013-07-16 22:26:05 +02001236 path_importer_cache = PySys_GetObject("path_importer_cache");
1237 path_hooks = PySys_GetObject("path_hooks");
1238 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001239 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001240 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 }
1242 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1243 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001244}
1245
Nick Coghland5cacbb2015-05-23 22:24:10 +10001246/*[clinic input]
1247_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001248
Nick Coghland5cacbb2015-05-23 22:24:10 +10001249 spec: object
1250 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001251
Nick Coghland5cacbb2015-05-23 22:24:10 +10001252Create an extension module.
1253[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001254
Nick Coghland5cacbb2015-05-23 22:24:10 +10001255static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001256_imp_create_builtin(PyObject *module, PyObject *spec)
1257/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001258{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001259 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001261 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001262 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001263 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001264
Nick Coghland5cacbb2015-05-23 22:24:10 +10001265 name = PyObject_GetAttrString(spec, "name");
1266 if (name == NULL) {
1267 return NULL;
1268 }
1269
Victor Stinner5eb4f592013-11-14 22:38:52 +01001270 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001271 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001272 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001273 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001274 return mod;
1275 }
1276
1277 namestr = PyUnicode_AsUTF8(name);
1278 if (namestr == NULL) {
1279 Py_DECREF(name);
1280 return NULL;
1281 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001282
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001283 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001285 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001286 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001288 /* Cannot re-init internal module ("sys" or "builtins") */
1289 mod = PyImport_AddModule(namestr);
1290 Py_DECREF(name);
1291 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001294 if (mod == NULL) {
1295 Py_DECREF(name);
1296 return NULL;
1297 }
1298 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1299 Py_DECREF(name);
1300 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1301 } else {
1302 /* Remember pointer to module init function. */
1303 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001304 if (def == NULL) {
1305 Py_DECREF(name);
1306 return NULL;
1307 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001308 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001309 if (_PyImport_FixupExtensionObject(mod, name, name,
1310 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001311 Py_DECREF(name);
1312 return NULL;
1313 }
1314 Py_DECREF(name);
1315 return mod;
1316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 }
1318 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001319 Py_DECREF(name);
1320 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001321}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001322
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001323
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001324/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001325
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001326static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001327find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001328{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001329 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001330
Victor Stinner53dc7352011-03-20 01:50:21 +01001331 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 for (p = PyImport_FrozenModules; ; p++) {
1335 if (p->name == NULL)
1336 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001337 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 break;
1339 }
1340 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001341}
1342
Guido van Rossum79f25d91997-04-29 20:08:16 +00001343static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001344get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001345{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001346 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (p == NULL) {
1350 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001351 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 name);
1353 return NULL;
1354 }
1355 if (p->code == NULL) {
1356 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001357 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 name);
1359 return NULL;
1360 }
1361 size = p->size;
1362 if (size < 0)
1363 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001364 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001365}
1366
Brett Cannon8d110132009-03-15 02:20:16 +00001367static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001368is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001369{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001370 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 if (p == NULL) {
1374 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001375 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 name);
1377 return NULL;
1378 }
Brett Cannon8d110132009-03-15 02:20:16 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (size < 0)
1383 Py_RETURN_TRUE;
1384 else
1385 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001386}
1387
1388
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001389/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001390 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001391 an exception set if the initialization failed.
1392 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001393
1394int
Victor Stinner53dc7352011-03-20 01:50:21 +01001395PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001396{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001397 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001398 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001399 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 int ispackage;
1401 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001402
Victor Stinner53dc7352011-03-20 01:50:21 +01001403 p = find_frozen(name);
1404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (p == NULL)
1406 return 0;
1407 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001408 _PyErr_Format(tstate, PyExc_ImportError,
1409 "Excluded frozen object named %R",
1410 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 return -1;
1412 }
1413 size = p->size;
1414 ispackage = (size < 0);
1415 if (ispackage)
1416 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001417 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (co == NULL)
1419 return -1;
1420 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001421 _PyErr_Format(tstate, PyExc_TypeError,
1422 "frozen object %R is not a code object",
1423 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 goto err_return;
1425 }
1426 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001427 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001428 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001430 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (m == NULL)
1432 goto err_return;
1433 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001434 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 goto err_return;
1437 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 err = PyDict_SetItemString(d, "__path__", l);
1439 Py_DECREF(l);
1440 if (err != 0)
1441 goto err_return;
1442 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001443 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001444 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001445 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001446 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001447 m = exec_code_in_module(tstate, name, d, co);
1448 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001450 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 Py_DECREF(co);
1452 Py_DECREF(m);
1453 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001454
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001455err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 Py_DECREF(co);
1457 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001458}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001459
Victor Stinner53dc7352011-03-20 01:50:21 +01001460int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001461PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001462{
1463 PyObject *nameobj;
1464 int ret;
1465 nameobj = PyUnicode_InternFromString(name);
1466 if (nameobj == NULL)
1467 return -1;
1468 ret = PyImport_ImportFrozenModuleObject(nameobj);
1469 Py_DECREF(nameobj);
1470 return ret;
1471}
1472
Guido van Rossum74e6a111994-08-29 12:54:38 +00001473
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001474/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001475 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001476
Guido van Rossum79f25d91997-04-29 20:08:16 +00001477PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001478PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyObject *pname;
1481 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 pname = PyUnicode_FromString(name);
1484 if (pname == NULL)
1485 return NULL;
1486 result = PyImport_Import(pname);
1487 Py_DECREF(pname);
1488 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001489}
1490
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001491
Christian Heimes072c0f12008-01-03 23:01:04 +00001492/* Import a module without blocking
1493 *
1494 * At first it tries to fetch the module from sys.modules. If the module was
1495 * never loaded before it loads it with PyImport_ImportModule() unless another
1496 * thread holds the import lock. In the latter case the function raises an
1497 * ImportError instead of blocking.
1498 *
1499 * Returns the module object with incremented ref count.
1500 */
1501PyObject *
1502PyImport_ImportModuleNoBlock(const char *name)
1503{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001504 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001505}
1506
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001507
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001508/* Remove importlib frames from the traceback,
1509 * except in Verbose mode. */
1510static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001511remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001512{
1513 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001514 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001515 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001516 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001517 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001518 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001519 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001520
1521 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001522 from the traceback. We always trim chunks
1523 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001524
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001525 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
1526 if (!exception || tstate->interp->config.verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001527 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001528 }
1529
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001530 if (PyType_IsSubtype((PyTypeObject *) exception,
1531 (PyTypeObject *) PyExc_ImportError))
1532 always_trim = 1;
1533
1534 prev_link = &base_tb;
1535 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001536 while (tb != NULL) {
1537 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1538 PyObject *next = (PyObject *) traceback->tb_next;
1539 PyFrameObject *frame = traceback->tb_frame;
1540 PyCodeObject *code = frame->f_code;
1541 int now_in_importlib;
1542
1543 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001544 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1545 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001546 if (now_in_importlib && !in_importlib) {
1547 /* This is the link to this chunk of importlib tracebacks */
1548 outer_link = prev_link;
1549 }
1550 in_importlib = now_in_importlib;
1551
1552 if (in_importlib &&
1553 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001554 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001555 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001556 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001557 prev_link = outer_link;
1558 }
1559 else {
1560 prev_link = (PyObject **) &traceback->tb_next;
1561 }
1562 tb = next;
1563 }
1564done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001565 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001566}
1567
1568
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001569static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001570resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001571{
Brett Cannonfd074152012-04-14 14:10:13 -04001572 _Py_IDENTIFIER(__package__);
Brett Cannonfd074152012-04-14 14:10:13 -04001573 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001574 _Py_IDENTIFIER(parent);
1575 PyObject *abs_name;
1576 PyObject *package = NULL;
1577 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001578 Py_ssize_t last_dot;
1579 PyObject *base;
1580 int level_up;
1581
1582 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001583 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001584 goto error;
1585 }
1586 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001587 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001588 goto error;
1589 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001590 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001591 if (package == Py_None) {
1592 package = NULL;
1593 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001594 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001595 goto error;
1596 }
1597 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001598 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001599 goto error;
1600 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001601
1602 if (package != NULL) {
1603 Py_INCREF(package);
1604 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001605 _PyErr_SetString(tstate, PyExc_TypeError,
1606 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001607 goto error;
1608 }
1609 else if (spec != NULL && spec != Py_None) {
1610 int equal;
1611 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1612 if (parent == NULL) {
1613 goto error;
1614 }
1615
1616 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1617 Py_DECREF(parent);
1618 if (equal < 0) {
1619 goto error;
1620 }
1621 else if (equal == 0) {
1622 if (PyErr_WarnEx(PyExc_ImportWarning,
1623 "__package__ != __spec__.parent", 1) < 0) {
1624 goto error;
1625 }
1626 }
1627 }
1628 }
1629 else if (spec != NULL && spec != Py_None) {
1630 package = _PyObject_GetAttrId(spec, &PyId_parent);
1631 if (package == NULL) {
1632 goto error;
1633 }
1634 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001635 _PyErr_SetString(tstate, PyExc_TypeError,
1636 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001637 goto error;
1638 }
1639 }
1640 else {
1641 if (PyErr_WarnEx(PyExc_ImportWarning,
1642 "can't resolve package from __spec__ or __package__, "
1643 "falling back on __name__ and __path__", 1) < 0) {
1644 goto error;
1645 }
1646
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001647 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001648 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001649 if (!_PyErr_Occurred(tstate)) {
1650 _PyErr_SetString(tstate, PyExc_KeyError,
1651 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001652 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001653 goto error;
1654 }
1655
1656 Py_INCREF(package);
1657 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001658 _PyErr_SetString(tstate, PyExc_TypeError,
1659 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001660 goto error;
1661 }
1662
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001663 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001664 Py_ssize_t dot;
1665
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001666 if (_PyErr_Occurred(tstate) || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001667 goto error;
1668 }
1669
1670 dot = PyUnicode_FindChar(package, '.',
1671 0, PyUnicode_GET_LENGTH(package), -1);
1672 if (dot == -2) {
1673 goto error;
1674 }
Ben Lewis92420b32019-09-11 20:09:47 +10001675 else if (dot == -1) {
1676 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001677 }
Ben Lewis92420b32019-09-11 20:09:47 +10001678 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1679 if (substr == NULL) {
1680 goto error;
1681 }
1682 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001683 }
1684 }
1685
1686 last_dot = PyUnicode_GET_LENGTH(package);
1687 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001688 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001689 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001690
1691 for (level_up = 1; level_up < level; level_up += 1) {
1692 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1693 if (last_dot == -2) {
1694 goto error;
1695 }
1696 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001697 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001698 "attempted relative import beyond top-level "
1699 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001700 goto error;
1701 }
1702 }
1703
1704 base = PyUnicode_Substring(package, 0, last_dot);
1705 Py_DECREF(package);
1706 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1707 return base;
1708 }
1709
1710 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1711 Py_DECREF(base);
1712 return abs_name;
1713
Ben Lewis92420b32019-09-11 20:09:47 +10001714 no_parent_error:
1715 _PyErr_SetString(tstate, PyExc_ImportError,
1716 "attempted relative import "
1717 "with no known parent package");
1718
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001719 error:
1720 Py_XDECREF(package);
1721 return NULL;
1722}
1723
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001724static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001725import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001726{
1727 _Py_IDENTIFIER(_find_and_load);
1728 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001729 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +02001730 int import_time = interp->config.import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001731 static int import_level;
1732 static _PyTime_t accumulated;
1733
1734 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1735
Steve Dowerb82e17e2019-05-23 08:45:22 -07001736 PyObject *sys_path = PySys_GetObject("path");
1737 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1738 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1c1e68c2020-03-27 15:11:45 +01001739 if (_PySys_Audit(tstate, "import", "OOOOO",
1740 abs_name, Py_None, sys_path ? sys_path : Py_None,
1741 sys_meta_path ? sys_meta_path : Py_None,
1742 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001743 return NULL;
1744 }
1745
1746
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001747 /* XOptions is initialized after first some imports.
1748 * So we can't have negative cache before completed initialization.
1749 * Anyway, importlib._find_and_load is much slower than
1750 * _PyDict_GetItemIdWithError().
1751 */
1752 if (import_time) {
1753 static int header = 1;
1754 if (header) {
1755 fputs("import time: self [us] | cumulative | imported package\n",
1756 stderr);
1757 header = 0;
1758 }
1759
1760 import_level++;
1761 t1 = _PyTime_GetPerfCounter();
1762 accumulated = 0;
1763 }
1764
1765 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001766 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001767
1768 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1769 &PyId__find_and_load, abs_name,
1770 interp->import_func, NULL);
1771
1772 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
Andy Lesterfc2d8d62020-03-30 15:19:14 -05001773 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001774 mod != NULL);
1775
1776 if (import_time) {
1777 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1778
1779 import_level--;
1780 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1781 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1782 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1783 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1784
1785 accumulated = accumulated_copy + cum;
1786 }
1787
1788 return mod;
1789}
1790
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001791PyObject *
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001792PyImport_GetModule(PyObject *name)
1793{
1794 PyThreadState *tstate = _PyThreadState_GET();
1795 PyObject *mod;
1796
1797 mod = import_get_module(tstate, name);
1798 if (mod != NULL && mod != Py_None) {
1799 if (import_ensure_initialized(tstate, mod, name) < 0) {
1800 Py_DECREF(mod);
1801 remove_importlib_frames(tstate);
1802 return NULL;
1803 }
1804 }
1805 return mod;
1806}
1807
1808PyObject *
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001809PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1810 PyObject *locals, PyObject *fromlist,
1811 int level)
1812{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001813 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001814 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001815 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001816 PyObject *final_mod = NULL;
1817 PyObject *mod = NULL;
1818 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001819 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001820 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001821
Brett Cannonfd074152012-04-14 14:10:13 -04001822 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001823 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001824 goto error;
1825 }
1826
1827 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1828 for added performance. */
1829
1830 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001831 _PyErr_SetString(tstate, PyExc_TypeError,
1832 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001833 goto error;
1834 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001835 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001836 goto error;
1837 }
1838 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001839 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001840 goto error;
1841 }
Brett Cannon849113a2016-01-22 15:25:50 -08001842
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001843 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001844 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001845 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001846 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001847 }
1848 else { /* level == 0 */
1849 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001850 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001851 goto error;
1852 }
Brett Cannonfd074152012-04-14 14:10:13 -04001853 abs_name = name;
1854 Py_INCREF(abs_name);
1855 }
1856
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001857 mod = import_get_module(tstate, abs_name);
1858 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001859 goto error;
1860 }
1861
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001862 if (mod != NULL && mod != Py_None) {
Joannah Nanjekye37c22202019-09-11 13:47:39 +01001863 if (import_ensure_initialized(tstate, mod, name) < 0) {
1864 goto error;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001865 }
Brett Cannonfd074152012-04-14 14:10:13 -04001866 }
1867 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001868 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001869 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001870 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001871 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001872 }
1873 }
1874
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001875 has_from = 0;
1876 if (fromlist != NULL && fromlist != Py_None) {
1877 has_from = PyObject_IsTrue(fromlist);
1878 if (has_from < 0)
1879 goto error;
1880 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001881 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001882 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1883 if (level == 0 || len > 0) {
1884 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001885
Victor Stinner744c34e2016-05-20 11:36:13 +02001886 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1887 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001888 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001889 }
1890
Victor Stinner744c34e2016-05-20 11:36:13 +02001891 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001892 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001893 final_mod = mod;
1894 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001895 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001896 }
1897
Brett Cannonfd074152012-04-14 14:10:13 -04001898 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001899 PyObject *front = PyUnicode_Substring(name, 0, dot);
1900 if (front == NULL) {
1901 goto error;
1902 }
1903
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001904 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001905 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001906 }
1907 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001908 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001909 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001910 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001911 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001912 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001913 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001914 }
Brett Cannonfd074152012-04-14 14:10:13 -04001915
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001916 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001917 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001918 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001919 if (!_PyErr_Occurred(tstate)) {
1920 _PyErr_Format(tstate, PyExc_KeyError,
1921 "%R not in sys.modules as expected",
1922 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001923 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001924 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001925 }
Brett Cannonfd074152012-04-14 14:10:13 -04001926 }
1927 }
1928 else {
1929 final_mod = mod;
1930 Py_INCREF(mod);
1931 }
1932 }
1933 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001934 PyObject *path;
1935 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1936 goto error;
1937 }
1938 if (path) {
1939 Py_DECREF(path);
1940 final_mod = _PyObject_CallMethodIdObjArgs(
1941 interp->importlib, &PyId__handle_fromlist,
1942 mod, fromlist, interp->import_func, NULL);
1943 }
1944 else {
1945 final_mod = mod;
1946 Py_INCREF(mod);
1947 }
Brett Cannonfd074152012-04-14 14:10:13 -04001948 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001949
Brett Cannonfd074152012-04-14 14:10:13 -04001950 error:
1951 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001952 Py_XDECREF(mod);
1953 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001954 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001955 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001956 }
Brett Cannonfd074152012-04-14 14:10:13 -04001957 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001958}
1959
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001960PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001961PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001962 PyObject *fromlist, int level)
1963{
1964 PyObject *nameobj, *mod;
1965 nameobj = PyUnicode_FromString(name);
1966 if (nameobj == NULL)
1967 return NULL;
1968 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1969 fromlist, level);
1970 Py_DECREF(nameobj);
1971 return mod;
1972}
1973
1974
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001975/* Re-import a module of any kind and return its module object, WITH
1976 INCREMENTED REFERENCE COUNT */
1977
Guido van Rossum79f25d91997-04-29 20:08:16 +00001978PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001979PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001980{
Eric Snow3f9eee62017-09-15 16:35:20 -06001981 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001982 _Py_IDENTIFIER(reload);
1983 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001984 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001985 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001986 if (PyErr_Occurred()) {
1987 return NULL;
1988 }
1989
Brett Cannon62228db2012-04-29 14:38:11 -04001990 imp = PyImport_ImportModule("imp");
1991 if (imp == NULL) {
1992 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001995
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001996 reloaded_module = _PyObject_CallMethodIdOneArg(imp, &PyId_reload, m);
Brett Cannon62228db2012-04-29 14:38:11 -04001997 Py_DECREF(imp);
1998 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001999}
2000
2001
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002002/* Higher-level import emulator which emulates the "import" statement
2003 more accurately -- it invokes the __import__() function from the
2004 builtins of the current globals. This means that the import is
2005 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002006 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002007 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002008 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002009 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002010
2011PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002012PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002013{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002014 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 static PyObject *silly_list = NULL;
2016 static PyObject *builtins_str = NULL;
2017 static PyObject *import_str = NULL;
2018 PyObject *globals = NULL;
2019 PyObject *import = NULL;
2020 PyObject *builtins = NULL;
2021 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 /* Initialize constant string objects */
2024 if (silly_list == NULL) {
2025 import_str = PyUnicode_InternFromString("__import__");
2026 if (import_str == NULL)
2027 return NULL;
2028 builtins_str = PyUnicode_InternFromString("__builtins__");
2029 if (builtins_str == NULL)
2030 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002031 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (silly_list == NULL)
2033 return NULL;
2034 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* Get the builtins from current globals */
2037 globals = PyEval_GetGlobals();
2038 if (globals != NULL) {
2039 Py_INCREF(globals);
2040 builtins = PyObject_GetItem(globals, builtins_str);
2041 if (builtins == NULL)
2042 goto err;
2043 }
2044 else {
2045 /* No globals -- use standard builtins, and fake globals */
2046 builtins = PyImport_ImportModuleLevel("builtins",
2047 NULL, NULL, NULL, 0);
2048 if (builtins == NULL)
2049 return NULL;
2050 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2051 if (globals == NULL)
2052 goto err;
2053 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 /* Get the __import__ function from the builtins */
2056 if (PyDict_Check(builtins)) {
2057 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002058 if (import == NULL) {
2059 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2060 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 }
2062 else
2063 import = PyObject_GetAttr(builtins, import_str);
2064 if (import == NULL)
2065 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002068 Always use absolute import here.
2069 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2071 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002072 if (r == NULL)
2073 goto err;
2074 Py_DECREF(r);
2075
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002076 r = import_get_module(tstate, module_name);
2077 if (r == NULL && !_PyErr_Occurred(tstate)) {
2078 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002079 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002080
2081 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 Py_XDECREF(globals);
2083 Py_XDECREF(builtins);
2084 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002087}
2088
Brett Cannon4caa61d2014-01-09 19:03:32 -05002089/*[clinic input]
2090_imp.extension_suffixes
2091
2092Returns the list of file suffixes used to identify extension modules.
2093[clinic start generated code]*/
2094
Brett Cannon4caa61d2014-01-09 19:03:32 -05002095static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002096_imp_extension_suffixes_impl(PyObject *module)
2097/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 list = PyList_New(0);
2102 if (list == NULL)
2103 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002104#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002105 const char *suffix;
2106 unsigned int index = 0;
2107
Brett Cannon2657df42012-05-04 15:20:40 -04002108 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2109 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (item == NULL) {
2111 Py_DECREF(list);
2112 return NULL;
2113 }
2114 if (PyList_Append(list, item) < 0) {
2115 Py_DECREF(list);
2116 Py_DECREF(item);
2117 return NULL;
2118 }
2119 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002120 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
Brett Cannon2657df42012-05-04 15:20:40 -04002122#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002124}
2125
Brett Cannon4caa61d2014-01-09 19:03:32 -05002126/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002127_imp.init_frozen
2128
2129 name: unicode
2130 /
2131
2132Initializes a frozen module.
2133[clinic start generated code]*/
2134
Brett Cannon4caa61d2014-01-09 19:03:32 -05002135static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002136_imp_init_frozen_impl(PyObject *module, PyObject *name)
2137/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002138{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002139 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 int ret;
2141 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002142
Victor Stinner53dc7352011-03-20 01:50:21 +01002143 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (ret < 0)
2145 return NULL;
2146 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002147 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002149 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 Py_XINCREF(m);
2151 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002152}
2153
Brett Cannon4caa61d2014-01-09 19:03:32 -05002154/*[clinic input]
2155_imp.get_frozen_object
2156
2157 name: unicode
2158 /
2159
2160Create a code object for a frozen module.
2161[clinic start generated code]*/
2162
Brett Cannon4caa61d2014-01-09 19:03:32 -05002163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002164_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2165/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002168}
2169
Brett Cannon4caa61d2014-01-09 19:03:32 -05002170/*[clinic input]
2171_imp.is_frozen_package
2172
2173 name: unicode
2174 /
2175
2176Returns True if the module name is of a frozen package.
2177[clinic start generated code]*/
2178
Brett Cannon4caa61d2014-01-09 19:03:32 -05002179static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002180_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2181/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002184}
2185
Brett Cannon4caa61d2014-01-09 19:03:32 -05002186/*[clinic input]
2187_imp.is_builtin
2188
2189 name: unicode
2190 /
2191
2192Returns True if the module name corresponds to a built-in module.
2193[clinic start generated code]*/
2194
Guido van Rossum79f25d91997-04-29 20:08:16 +00002195static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002196_imp_is_builtin_impl(PyObject *module, PyObject *name)
2197/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002198{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002199 return PyLong_FromLong(is_builtin(name));
2200}
2201
2202/*[clinic input]
2203_imp.is_frozen
2204
2205 name: unicode
2206 /
2207
2208Returns True if the module name corresponds to a frozen module.
2209[clinic start generated code]*/
2210
Brett Cannon4caa61d2014-01-09 19:03:32 -05002211static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002212_imp_is_frozen_impl(PyObject *module, PyObject *name)
2213/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002214{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002215 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 p = find_frozen(name);
2218 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002219}
2220
Larry Hastings1df0b352015-08-24 19:53:56 -07002221/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2222static int
2223exec_builtin_or_dynamic(PyObject *mod) {
2224 PyModuleDef *def;
2225 void *state;
2226
2227 if (!PyModule_Check(mod)) {
2228 return 0;
2229 }
2230
2231 def = PyModule_GetDef(mod);
2232 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002233 return 0;
2234 }
Brett Cannon52794db2016-09-07 17:00:43 -07002235
Larry Hastings1df0b352015-08-24 19:53:56 -07002236 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002237 if (state) {
2238 /* Already initialized; skip reload */
2239 return 0;
2240 }
Brett Cannon52794db2016-09-07 17:00:43 -07002241
Larry Hastings1df0b352015-08-24 19:53:56 -07002242 return PyModule_ExecDef(mod, def);
2243}
2244
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002245#ifdef HAVE_DYNAMIC_LOADING
2246
Brett Cannon4caa61d2014-01-09 19:03:32 -05002247/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002248_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002249
Nick Coghland5cacbb2015-05-23 22:24:10 +10002250 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002251 file: object = NULL
2252 /
2253
Nick Coghland5cacbb2015-05-23 22:24:10 +10002254Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002255[clinic start generated code]*/
2256
Brett Cannon4caa61d2014-01-09 19:03:32 -05002257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002258_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2259/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002260{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002261 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002262 FILE *fp;
2263
Nick Coghland5cacbb2015-05-23 22:24:10 +10002264 name = PyObject_GetAttrString(spec, "name");
2265 if (name == NULL) {
2266 return NULL;
2267 }
2268
2269 path = PyObject_GetAttrString(spec, "origin");
2270 if (path == NULL) {
2271 Py_DECREF(name);
2272 return NULL;
2273 }
2274
2275 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002276 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002277 Py_DECREF(name);
2278 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002279 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002280 return mod;
2281 }
2282
Brett Cannon4caa61d2014-01-09 19:03:32 -05002283 if (file != NULL) {
2284 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002285 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002286 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002287 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002291 else
2292 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002293
2294 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2295
2296 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002297 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 if (fp)
2299 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002300 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002301}
2302
Nick Coghland5cacbb2015-05-23 22:24:10 +10002303/*[clinic input]
2304_imp.exec_dynamic -> int
2305
2306 mod: object
2307 /
2308
2309Initialize an extension module.
2310[clinic start generated code]*/
2311
2312static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002313_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2314/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002315{
Larry Hastings1df0b352015-08-24 19:53:56 -07002316 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002317}
2318
2319
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002320#endif /* HAVE_DYNAMIC_LOADING */
2321
Larry Hastings7726ac92014-01-31 22:03:12 -08002322/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002323_imp.exec_builtin -> int
2324
2325 mod: object
2326 /
2327
2328Initialize a built-in module.
2329[clinic start generated code]*/
2330
2331static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002332_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2333/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002334{
2335 return exec_builtin_or_dynamic(mod);
2336}
2337
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002338/*[clinic input]
2339_imp.source_hash
2340
2341 key: long
2342 source: Py_buffer
2343[clinic start generated code]*/
2344
2345static PyObject *
2346_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2347/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2348{
Benjamin Peterson83620772017-12-09 12:18:56 -08002349 union {
2350 uint64_t x;
2351 char data[sizeof(uint64_t)];
2352 } hash;
2353 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002354#if !PY_LITTLE_ENDIAN
2355 // Force to little-endian. There really ought to be a succinct standard way
2356 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002357 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2358 char tmp = hash.data[i];
2359 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2360 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002361 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002362#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002363 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002364}
2365
Barry Warsaw28a691b2010-04-17 00:19:56 +00002366
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002367PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002368"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002369
Guido van Rossum79f25d91997-04-29 20:08:16 +00002370static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002371 _IMP_EXTENSION_SUFFIXES_METHODDEF
2372 _IMP_LOCK_HELD_METHODDEF
2373 _IMP_ACQUIRE_LOCK_METHODDEF
2374 _IMP_RELEASE_LOCK_METHODDEF
2375 _IMP_GET_FROZEN_OBJECT_METHODDEF
2376 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002377 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002378 _IMP_INIT_FROZEN_METHODDEF
2379 _IMP_IS_BUILTIN_METHODDEF
2380 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002381 _IMP_CREATE_DYNAMIC_METHODDEF
2382 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002383 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002384 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002385 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002386 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002387};
2388
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002389
Martin v. Löwis1a214512008-06-11 05:26:20 +00002390static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002392 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 doc_imp,
2394 0,
2395 imp_methods,
2396 NULL,
2397 NULL,
2398 NULL,
2399 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002400};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002401
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002402PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002403PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002408 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002412 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002414 }
2415
Victor Stinnerff4584c2020-03-13 18:03:56 +01002416 const wchar_t *mode = _PyInterpreterState_GET_UNSAFE()->config.check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002417 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002418 if (pyc_mode == NULL) {
2419 goto failure;
2420 }
2421 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2422 Py_DECREF(pyc_mode);
2423 goto failure;
2424 }
2425 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002428 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 Py_XDECREF(m);
2430 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002431}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002432
2433
Guido van Rossumb18618d2000-05-03 23:44:39 +00002434/* API for embedding applications that want to add their own entries
2435 to the table of built-in modules. This should normally be called
2436 *before* Py_Initialize(). When the table resize fails, -1 is
2437 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002438
2439 After a similar function by Just van Rossum. */
2440
2441int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002442PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002445 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002446 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* Count the number of entries in both tables */
2449 for (n = 0; newtab[n].name != NULL; n++)
2450 ;
2451 if (n == 0)
2452 return 0; /* Nothing to do */
2453 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2454 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002455
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002456 /* Force default raw memory allocator to get a known allocator to be able
2457 to release the memory in _PyImport_Fini2() */
2458 PyMemAllocatorEx old_alloc;
2459 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002462 p = NULL;
2463 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002464 size_t size = sizeof(struct _inittab) * (i + n + 1);
2465 p = PyMem_RawRealloc(inittab_copy, size);
2466 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002467 if (p == NULL) {
2468 res = -1;
2469 goto done;
2470 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002471
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002472 /* Copy the tables into the new memory at the first call
2473 to PyImport_ExtendInittab(). */
2474 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002476 }
2477 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2478 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002479
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002480done:
2481 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2482 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002483}
2484
2485/* Shorthand to add a single entry given a name and a function */
2486
2487int
Brett Cannona826f322009-04-02 03:41:46 +00002488PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002493
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002494 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002498}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002499
2500#ifdef __cplusplus
2501}
2502#endif