blob: dc0d5b8b901ca028a04833a01ca25c1f6755b203 [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 Stinner0a28f8d2019-06-19 02:54:39 +02007#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01008#include "pycore_pyhash.h"
9#include "pycore_pylifecycle.h"
10#include "pycore_pymem.h"
11#include "pycore_pystate.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020015#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000016#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000017#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020018#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000019
Guido van Rossum55a83382000-09-20 20:31:38 +000020#ifdef HAVE_FCNTL_H
21#include <fcntl.h>
22#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000024extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000026
Barry Warsaw28a691b2010-04-17 00:19:56 +000027#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000028
Victor Stinner0a28f8d2019-06-19 02:54:39 +020029/* Forward references */
30static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
31
Victor Stinner95872862011-03-07 18:20:56 +010032/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000033static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000034
Guido van Rossum771c6c81997-10-31 18:37:24 +000035/* This table is defined in config.c: */
36extern struct _inittab _PyImport_Inittab[];
37
38struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010039static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000040
Brett Cannon4caa61d2014-01-09 19:03:32 -050041/*[clinic input]
42module _imp
43[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030044/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040045
46#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050047
Guido van Rossum1ae940a1995-01-02 19:04:15 +000048/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049
Victor Stinner331a6a52019-05-27 16:39:22 +020050PyStatus
Victor Stinner672b6ba2017-12-06 17:25:50 +010051_PyImport_Init(PyInterpreterState *interp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020053 interp->builtins_copy = PyDict_Copy(interp->builtins);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054 if (interp->builtins_copy == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020055 return _PyStatus_ERR("Can't backup builtins dict");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056 }
Victor Stinner331a6a52019-05-27 16:39:22 +020057 return _PyStatus_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058}
59
Victor Stinner331a6a52019-05-27 16:39:22 +020060PyStatus
Just van Rossum52e14d62002-12-30 22:08:05 +000061_PyImportHooks_Init(void)
62{
Brett Cannonfd074152012-04-14 14:10:13 -040063 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000065
Brett Cannonfd074152012-04-14 14:10:13 -040066 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 v = PyList_New(0);
68 if (v == NULL)
69 goto error;
70 err = PySys_SetObject("meta_path", v);
71 Py_DECREF(v);
72 if (err)
73 goto error;
74 v = PyDict_New();
75 if (v == NULL)
76 goto error;
77 err = PySys_SetObject("path_importer_cache", v);
78 Py_DECREF(v);
79 if (err)
80 goto error;
81 path_hooks = PyList_New(0);
82 if (path_hooks == NULL)
83 goto error;
84 err = PySys_SetObject("path_hooks", path_hooks);
85 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 }
Brett Cannonfd074152012-04-14 14:10:13 -040088 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020089 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080090
91 error:
92 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +020093 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080094 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040095}
96
Victor Stinner331a6a52019-05-27 16:39:22 +020097PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020098_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -040099{
ukwksk5e6312c2018-05-15 04:10:52 +0900100 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -0400101 int err = 0;
102
103 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200104 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200105 _PyErr_SetString(tstate, PyExc_RuntimeError,
106 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400107 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200108 }
Brett Cannonfd074152012-04-14 14:10:13 -0400109
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200110 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200111 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400112 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200113 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114
ukwksk5e6312c2018-05-15 04:10:52 +0900115 zipimport = PyImport_ImportModule("zipimport");
116 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200117 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200118 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200120 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 }
122 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200123 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900124 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200125 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900126 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200128 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200129 if (verbose) {
130 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 }
133 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400134 /* sys.path_hooks.insert(0, zipimporter) */
135 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400137 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400139 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200140 if (verbose) {
141 PySys_WriteStderr("# installed zipimport hook\n");
142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 }
144 }
Brett Cannonfd074152012-04-14 14:10:13 -0400145
Victor Stinner331a6a52019-05-27 16:39:22 +0200146 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400147
148 error:
149 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200150 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000151}
152
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153/* Locking primitives to prevent parallel imports of the same module
154 in different threads to return with a partially loaded module.
155 These calls are serialized by the global interpreter lock. */
156
Guido van Rossum49b56061998-10-01 20:42:43 +0000157#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000158
Guido van Rossum65d5b571998-12-21 19:32:43 +0000159static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200160static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000161static int import_lock_level = 0;
162
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000163void
164_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000165{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200166 unsigned long me = PyThread_get_thread_ident();
167 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 return; /* Too bad */
169 if (import_lock == NULL) {
170 import_lock = PyThread_allocate_lock();
171 if (import_lock == NULL)
172 return; /* Nothing much we can do. */
173 }
174 if (import_lock_thread == me) {
175 import_lock_level++;
176 return;
177 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200178 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
179 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 {
181 PyThreadState *tstate = PyEval_SaveThread();
182 PyThread_acquire_lock(import_lock, 1);
183 PyEval_RestoreThread(tstate);
184 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100185 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 import_lock_thread = me;
187 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000188}
189
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000190int
191_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000192{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200193 unsigned long me = PyThread_get_thread_ident();
194 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return 0; /* Too bad */
196 if (import_lock_thread != me)
197 return -1;
198 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100199 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200201 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 PyThread_release_lock(import_lock);
203 }
204 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000205}
206
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200207/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000208 created child processes do not share locks with the parent.
209 We now acquire the import lock around fork() calls but on some platforms
210 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000211
212void
213_PyImport_ReInitLock(void)
214{
Christian Heimes418fd742015-04-19 21:08:42 +0200215 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200217 if (import_lock == NULL) {
218 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
219 }
220 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000221 if (import_lock_level > 1) {
222 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200223 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500224 /* The following could fail if the lock is already held, but forking as
225 a side-effect of an import is a) rare, b) nuts, and c) difficult to
226 do thanks to the lock only being held when doing individual module
227 locks per import. */
228 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000229 import_lock_thread = me;
230 import_lock_level--;
231 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200232 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000233 import_lock_level = 0;
234 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000235}
236
Brett Cannon4caa61d2014-01-09 19:03:32 -0500237/*[clinic input]
238_imp.lock_held
239
240Return True if the import lock is currently held, else False.
241
242On platforms without threads, return False.
243[clinic start generated code]*/
244
Brett Cannon4caa61d2014-01-09 19:03:32 -0500245static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300246_imp_lock_held_impl(PyObject *module)
247/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000248{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200249 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000250}
251
Brett Cannon4caa61d2014-01-09 19:03:32 -0500252/*[clinic input]
253_imp.acquire_lock
254
255Acquires the interpreter's import lock for the current thread.
256
257This lock should be used by import hooks to ensure thread-safety when importing
258modules. On platforms without threads, this function does nothing.
259[clinic start generated code]*/
260
Brett Cannon4caa61d2014-01-09 19:03:32 -0500261static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300262_imp_acquire_lock_impl(PyObject *module)
263/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200266 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000267}
268
Brett Cannon4caa61d2014-01-09 19:03:32 -0500269/*[clinic input]
270_imp.release_lock
271
272Release the interpreter's import lock.
273
274On platforms without threads, this function does nothing.
275[clinic start generated code]*/
276
Brett Cannon4caa61d2014-01-09 19:03:32 -0500277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300278_imp_release_lock_impl(PyObject *module)
279/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (_PyImport_ReleaseLock() < 0) {
282 PyErr_SetString(PyExc_RuntimeError,
283 "not holding the import lock");
284 return NULL;
285 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200286 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000287}
288
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100289void
290_PyImport_Fini(void)
291{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200292 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100293 if (import_lock != NULL) {
294 PyThread_free_lock(import_lock);
295 import_lock = NULL;
296 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100297}
298
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100299void
300_PyImport_Fini2(void)
301{
302 /* Use the same memory allocator than PyImport_ExtendInittab(). */
303 PyMemAllocatorEx old_alloc;
304 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
305
306 /* Free memory allocated by PyImport_ExtendInittab() */
307 PyMem_RawFree(inittab_copy);
308
309 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
310}
311
Guido van Rossum25ce5661997-08-02 03:10:38 +0000312/* Helper for sys */
313
314PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000315PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200317 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow3f9eee62017-09-15 16:35:20 -0600318 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700319 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600320 }
Eric Snow93c92f72017-09-13 23:46:04 -0700321 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000322}
323
Eric Snowd393c1b2017-09-14 12:18:12 -0600324/* In some corner cases it is important to be sure that the import
325 machinery has been initialized (or not cleaned up yet). For
326 example, see issue #4236 and PyModule_Create2(). */
327
328int
329_PyImport_IsInitialized(PyInterpreterState *interp)
330{
331 if (interp->modules == NULL)
332 return 0;
333 return 1;
334}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000335
Eric Snow3f9eee62017-09-15 16:35:20 -0600336PyObject *
337_PyImport_GetModuleId(struct _Py_Identifier *nameid)
338{
339 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
340 if (name == NULL) {
341 return NULL;
342 }
343 return PyImport_GetModule(name);
344}
345
346int
347_PyImport_SetModule(PyObject *name, PyObject *m)
348{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200349 PyThreadState *tstate = _PyThreadState_GET();
350 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600351 return PyObject_SetItem(modules, name, m);
352}
353
354int
355_PyImport_SetModuleString(const char *name, PyObject *m)
356{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200357 PyThreadState *tstate = _PyThreadState_GET();
358 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600359 return PyMapping_SetItemString(modules, name, m);
360}
361
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200362static PyObject *
363import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600364{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200365 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600366 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200367 _PyErr_SetString(tstate, PyExc_RuntimeError,
368 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600369 return NULL;
370 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200371
372 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600373 Py_INCREF(modules);
374 if (PyDict_CheckExact(modules)) {
375 m = PyDict_GetItemWithError(modules, name); /* borrowed */
376 Py_XINCREF(m);
377 }
378 else {
379 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200380 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
381 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600382 }
383 }
384 Py_DECREF(modules);
385 return m;
386}
387
388
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200389PyObject *
390PyImport_GetModule(PyObject *name)
391{
392 PyThreadState *tstate = _PyThreadState_GET();
393 return import_get_module(tstate, name);
394}
395
396
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000397/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200398static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 "path", "argv", "ps1", "ps2",
400 "last_type", "last_value", "last_traceback",
401 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200402 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000404};
405
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200406static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 "stdin", "__stdin__",
408 "stdout", "__stdout__",
409 "stderr", "__stderr__",
410 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000411};
412
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000413/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000414
Guido van Rossum3f5da241990-12-20 15:06:42 +0000415void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200416_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000417{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200418 PyInterpreterState *interp = tstate->interp;
419 PyObject *modules = interp->modules;
420 if (modules == NULL) {
421 /* Already done */
422 return;
423 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* Delete some special variables first. These are common
426 places where user values hide and people complain when their
427 destructors fail. Since the modules containing them are
428 deleted *last* of all, they would come too late in the normal
429 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000430
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200431 /* XXX Perhaps these precautions are obsolete. Who knows? */
432
Victor Stinner331a6a52019-05-27 16:39:22 +0200433 int verbose = interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200434 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200435 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200436 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300437 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300438 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300439 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200440
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200441 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200442 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200443 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200444 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200445 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300446 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300447 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200450 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200451 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200452 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200453 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200454 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
455 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200456 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200457 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200458 PyErr_WriteUnraisable(NULL);
459 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200460 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200461 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300462 if (PyDict_SetItemString(interp->sysdict, *p, value) < 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 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000466
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200467 /* We prepare a list which will receive (name, weakref) tuples of
468 modules when they are removed from sys.modules. The name is used
469 for diagnosis messages (in verbose mode), while the weakref helps
470 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200471 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300472 if (weaklist == NULL) {
473 PyErr_WriteUnraisable(NULL);
474 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200475
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200476#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200477 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200478 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300479 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200480 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300481 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300482 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300483 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200484 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300485 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200486 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300487 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300488 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300489 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600491#define CLEAR_MODULE(name, mod) \
492 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200493 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600494 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200495 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600496 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300497 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300498 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300499 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600500 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000501
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200502 /* Remove all modules from sys.modules, hoping that garbage collection
503 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600504 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200505 Py_ssize_t pos = 0;
506 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600507 while (PyDict_Next(modules, &pos, &key, &value)) {
508 CLEAR_MODULE(key, value);
509 }
510 }
511 else {
512 PyObject *iterator = PyObject_GetIter(modules);
513 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300514 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600515 }
516 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200517 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600518 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200519 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600520 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300521 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600522 continue;
523 }
524 CLEAR_MODULE(key, value);
525 Py_DECREF(value);
526 Py_DECREF(key);
527 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300528 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300529 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300530 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600531 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 }
533 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000534
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200535 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600536 if (PyDict_CheckExact(modules)) {
537 PyDict_Clear(modules);
538 }
539 else {
540 _Py_IDENTIFIER(clear);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300541 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
542 PyErr_WriteUnraisable(NULL);
543 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600544 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200545 /* Restore the original builtins dict, to ensure that any
546 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200547 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300548 if (dict == NULL) {
549 PyErr_WriteUnraisable(NULL);
550 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200551 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300552 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200553 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300554 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200555 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200556 /* Clear module dict copies stored in the interpreter state */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200557 _PyInterpreterState_ClearModules(tstate->interp);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200558 /* Collect references */
559 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200560 /* Dump GC stats before it's too late, since it uses the warnings
561 machinery. */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200562 _PyGC_DumpShutdownStats(&_PyRuntime);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200563
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200564 /* Now, if there are any modules left alive, clear their globals to
565 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200566 up here, since they are kept alive in the interpreter state.
567
568 The special treatment of "builtins" here is because even
569 when it's not referenced as a module, its dictionary is
570 referenced by almost every module's __builtins__. Since
571 deleting a module clears its dictionary (even if there are
572 references left to it), we need to delete the "builtins"
573 module last. Likewise, we don't delete sys until the very
574 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200575 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200576 Py_ssize_t i;
577 /* Since dict is ordered in CPython 3.6+, modules are saved in
578 importing order. First clear modules imported later. */
579 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200580 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200581 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200582 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
583 if (mod == Py_None)
584 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200585 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200586 dict = PyModule_GetDict(mod);
587 if (dict == interp->builtins || dict == interp->sysdict)
588 continue;
589 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200590 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200591 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200592 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200593 _PyModule_Clear(mod);
594 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200595 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200596 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000598
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200599 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200600 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200601 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200602 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200603 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200604 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200605 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200606 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200607 _PyModule_ClearDict(interp->builtins);
608
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200609 /* Clear and delete the modules directory. Actual modules will
610 still be there only if imported during the execution of some
611 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700612 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200614
615 /* Once more */
616 _PyGC_CollectNoFail();
617
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300618#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200619#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000620}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000621
622
Barry Warsaw28a691b2010-04-17 00:19:56 +0000623/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000624
625long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000626PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000627{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200628 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200629 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600630 PyObject *external, *pyc_magic;
631
632 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
633 if (external == NULL)
634 return -1;
635 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
636 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400637 if (pyc_magic == NULL)
638 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200639 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700640 Py_DECREF(pyc_magic);
641 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000642}
643
644
Brett Cannon3adc7b72012-07-09 14:22:12 -0400645extern const char * _PySys_ImplCacheTag;
646
Barry Warsaw28a691b2010-04-17 00:19:56 +0000647const char *
648PyImport_GetMagicTag(void)
649{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400650 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000651}
652
Brett Cannon98979b82012-07-02 15:13:11 -0400653
Guido van Rossum25ce5661997-08-02 03:10:38 +0000654/* Magic for extension modules (built-in as well as dynamically
655 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200656 once, we keep a static dictionary 'extensions' keyed by the tuple
657 (module name, module name) (for built-in modules) or by
658 (filename, module name) (for dynamically loaded modules), containing these
659 modules. A copy of the module's dictionary is stored by calling
660 _PyImport_FixupExtensionObject() immediately after the module initialization
661 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100662 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000663
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000664 Modules which do support multiple initialization set their m_size
665 field to a non-negative number (indicating the size of the
666 module-specific state). They are still recorded in the extensions
667 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000668*/
669
670int
Victor Stinner95872862011-03-07 18:20:56 +0100671_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200672 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000673{
Eric Snowd393c1b2017-09-14 12:18:12 -0600674 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500676 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (extensions == NULL) {
678 extensions = PyDict_New();
679 if (extensions == NULL)
680 return -1;
681 }
682 if (mod == NULL || !PyModule_Check(mod)) {
683 PyErr_BadInternalCall();
684 return -1;
685 }
686 def = PyModule_GetDef(mod);
687 if (!def) {
688 PyErr_BadInternalCall();
689 return -1;
690 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600691 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 return -1;
693 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600694 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 return -1;
696 }
697 if (def->m_size == -1) {
698 if (def->m_base.m_copy) {
699 /* Somebody already imported the module,
700 likely under a different name.
701 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200702 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 }
704 dict = PyModule_GetDict(mod);
705 if (dict == NULL)
706 return -1;
707 def->m_base.m_copy = PyDict_Copy(dict);
708 if (def->m_base.m_copy == NULL)
709 return -1;
710 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500711 key = PyTuple_Pack(2, filename, name);
712 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200713 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500714 res = PyDict_SetItem(extensions, key, (PyObject *)def);
715 Py_DECREF(key);
716 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200717 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000719}
720
Victor Stinner49d3f252010-10-17 01:24:53 +0000721int
Eric Snowd393c1b2017-09-14 12:18:12 -0600722_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000723{
724 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100725 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100726 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100727 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000728 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600729 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100730 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000731 return res;
732}
733
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200734static PyObject *
735import_find_extension(PyThreadState *tstate, PyObject *name,
736 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000737{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200738 if (extensions == NULL) {
739 return NULL;
740 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600741
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200742 PyObject *key = PyTuple_Pack(2, filename, name);
743 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200745 }
746 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500747 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200748 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200750 }
751
752 PyObject *mod, *mdict;
753 PyObject *modules = tstate->interp->modules;
754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (def->m_size == -1) {
756 /* Module does not support repeated initialization */
757 if (def->m_base.m_copy == NULL)
758 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200759 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (mod == NULL)
761 return NULL;
762 mdict = PyModule_GetDict(mod);
763 if (mdict == NULL)
764 return NULL;
765 if (PyDict_Update(mdict, def->m_base.m_copy))
766 return NULL;
767 }
768 else {
769 if (def->m_base.m_init == NULL)
770 return NULL;
771 mod = def->m_base.m_init();
772 if (mod == NULL)
773 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600774 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200775 Py_DECREF(mod);
776 return NULL;
777 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 Py_DECREF(mod);
779 }
780 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600781 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 return NULL;
783 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200784
785 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200786 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100787 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200788 name, filename);
789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000791}
792
Victor Stinner49d3f252010-10-17 01:24:53 +0000793PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200794_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
795{
796 PyThreadState *tstate = _PyThreadState_GET();
797 return import_find_extension(tstate, name, filename);
798}
799
800
801PyObject *
802_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000803{
Victor Stinner95872862011-03-07 18:20:56 +0100804 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100805 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100806 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000807 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200808 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100809 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000810 return res;
811}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000812
813/* Get the module object corresponding to a module name.
814 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000815 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000816 Because the former action is most common, THIS DOES NOT RETURN A
817 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000818
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200819static PyObject *
820import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000821{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200822 PyObject *modules = tstate->interp->modules;
823 if (modules == NULL) {
824 _PyErr_SetString(tstate, PyExc_RuntimeError,
825 "no import module dictionary");
826 return NULL;
827 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600828
Eric Snow86b7afd2017-09-04 17:54:09 -0600829 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600830 if (PyDict_CheckExact(modules)) {
831 m = PyDict_GetItemWithError(modules, name);
832 }
833 else {
834 m = PyObject_GetItem(modules, name);
835 // For backward-comaptibility we copy the behavior
836 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200837 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
838 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600839 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200840 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200841 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200842 return NULL;
843 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600844 if (m != NULL && PyModule_Check(m)) {
845 return m;
846 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000847 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (m == NULL)
849 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600850 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 Py_DECREF(m);
852 return NULL;
853 }
854 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000857}
858
Victor Stinner27ee0892011-03-04 12:57:09 +0000859PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200860PyImport_AddModuleObject(PyObject *name)
861{
862 PyThreadState *tstate = _PyThreadState_GET();
863 return import_add_module(tstate, name);
864}
865
866
867PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000868PyImport_AddModule(const char *name)
869{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200870 PyObject *nameobj = PyUnicode_FromString(name);
871 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000872 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200873 }
874 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000875 Py_DECREF(nameobj);
876 return module;
877}
878
879
Tim Peters1cd70172004-08-02 03:52:12 +0000880/* Remove name from sys.modules, if it's there. */
881static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200882remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000883{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600884 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200885 _PyErr_Fetch(tstate, &type, &value, &traceback);
886
887 PyObject *modules = tstate->interp->modules;
Zackery Spytz94a64e92019-05-08 10:31:23 -0600888 if (!PyMapping_HasKey(modules, name)) {
889 goto out;
890 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600891 if (PyMapping_DelItem(modules, name) < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200892 _PyErr_SetString(tstate, PyExc_RuntimeError,
893 "deleting key in sys.modules failed");
894 _PyErr_ChainExceptions(type, value, traceback);
895 return;
Eric Snow3f9eee62017-09-15 16:35:20 -0600896 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200897
Zackery Spytz94a64e92019-05-08 10:31:23 -0600898out:
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200899 _PyErr_Restore(tstate, type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000900}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000901
Christian Heimes3b06e532008-01-07 20:12:44 +0000902
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000903/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000904 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
905 * removed from sys.modules, to avoid leaving damaged module objects
906 * in sys.modules. The caller may wish to restore the original
907 * module object (if any) in this case; PyImport_ReloadModule is an
908 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000909 *
910 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
911 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000912 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000913PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300914PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 return PyImport_ExecCodeModuleWithPathnames(
917 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000918}
919
920PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300921PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 return PyImport_ExecCodeModuleWithPathnames(
924 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000925}
926
927PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300928PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
929 const char *pathname,
930 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000931{
Victor Stinner27ee0892011-03-04 12:57:09 +0000932 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600933 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000934
935 nameobj = PyUnicode_FromString(name);
936 if (nameobj == NULL)
937 return NULL;
938
Victor Stinner27ee0892011-03-04 12:57:09 +0000939 if (cpathname != NULL) {
940 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
941 if (cpathobj == NULL)
942 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400943 }
944 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000945 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400946
947 if (pathname != NULL) {
948 pathobj = PyUnicode_DecodeFSDefault(pathname);
949 if (pathobj == NULL)
950 goto error;
951 }
952 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200953 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400954 _Py_IDENTIFIER(_get_sourcefile);
955
956 if (interp == NULL) {
957 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
958 "no interpreter!");
959 }
960
Eric Snow32439d62015-05-02 19:15:18 -0600961 external= PyObject_GetAttrString(interp->importlib,
962 "_bootstrap_external");
963 if (external != NULL) {
964 pathobj = _PyObject_CallMethodIdObjArgs(external,
965 &PyId__get_sourcefile, cpathobj,
966 NULL);
967 Py_DECREF(external);
968 }
Brett Cannona6473f92012-07-13 13:57:03 -0400969 if (pathobj == NULL)
970 PyErr_Clear();
971 }
972 else
973 pathobj = NULL;
974
Victor Stinner27ee0892011-03-04 12:57:09 +0000975 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
976error:
977 Py_DECREF(nameobj);
978 Py_XDECREF(pathobj);
979 Py_XDECREF(cpathobj);
980 return m;
981}
982
Brett Cannon18fc4e72014-04-04 10:01:46 -0400983static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200984module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000985{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200986 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400987 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000988
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200989 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (m == NULL)
991 return NULL;
992 /* If the module is being reloaded, we get the old module back
993 and re-use its dict to exec the new code. */
994 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200995 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200996 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200997 _PyDict_SetItemId(d, &PyId___builtins__,
998 PyEval_GetBuiltins()) != 0)
999 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001000 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001001 return NULL;
1002 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001004
Eric Snow08197a42014-05-12 17:54:55 -06001005 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001006}
1007
1008static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001009exec_code_in_module(PyThreadState *tstate, PyObject *name,
1010 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001011{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001012 PyObject *v, *m;
1013
1014 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1015 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001016 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001017 return NULL;
1018 }
1019 Py_DECREF(v);
1020
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001021 m = import_get_module(tstate, name);
1022 if (m == NULL && !_PyErr_Occurred(tstate)) {
1023 _PyErr_Format(tstate, PyExc_ImportError,
1024 "Loaded module %R not found in sys.modules",
1025 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001026 }
1027
Brett Cannon18fc4e72014-04-04 10:01:46 -04001028 return m;
1029}
1030
1031PyObject*
1032PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1033 PyObject *cpathname)
1034{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001035 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001036 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001037 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001038
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001039 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001040 if (d == NULL) {
1041 return NULL;
1042 }
1043
Eric Snow08197a42014-05-12 17:54:55 -06001044 if (pathname == NULL) {
1045 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001047 external = PyObject_GetAttrString(tstate->interp->importlib,
1048 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001049 if (external == NULL)
1050 return NULL;
1051 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001052 &PyId__fix_up_module,
1053 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001054 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001055 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001056 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001057 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 }
Eric Snow08197a42014-05-12 17:54:55 -06001059 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001060}
1061
1062
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001063static void
1064update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyObject *constants, *tmp;
1067 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 if (PyUnicode_Compare(co->co_filename, oldname))
1070 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001071
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001072 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001073 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 constants = co->co_consts;
1076 n = PyTuple_GET_SIZE(constants);
1077 for (i = 0; i < n; i++) {
1078 tmp = PyTuple_GET_ITEM(constants, i);
1079 if (PyCode_Check(tmp))
1080 update_code_filenames((PyCodeObject *)tmp,
1081 oldname, newname);
1082 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001083}
1084
Victor Stinner2f42ae52011-03-20 00:41:24 +01001085static void
1086update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001087{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001088 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001089
Victor Stinner2f42ae52011-03-20 00:41:24 +01001090 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1091 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 oldname = co->co_filename;
1094 Py_INCREF(oldname);
1095 update_code_filenames(co, oldname, newname);
1096 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001097}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001098
Brett Cannon4caa61d2014-01-09 19:03:32 -05001099/*[clinic input]
1100_imp._fix_co_filename
1101
1102 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1103 Code object to change.
1104
1105 path: unicode
1106 File path to use.
1107 /
1108
1109Changes code.co_filename to specify the passed-in file path.
1110[clinic start generated code]*/
1111
Brett Cannon4caa61d2014-01-09 19:03:32 -05001112static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001113_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001114 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001115/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001116
Brett Cannon4caa61d2014-01-09 19:03:32 -05001117{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001118 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001119
1120 Py_RETURN_NONE;
1121}
1122
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001123
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001124/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001125static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001126
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001127
1128/* Helper to test for built-in module */
1129
1130static int
Victor Stinner95872862011-03-07 18:20:56 +01001131is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001132{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001133 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001135 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (PyImport_Inittab[i].initfunc == NULL)
1137 return -1;
1138 else
1139 return 1;
1140 }
1141 }
1142 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001143}
1144
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001145
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001146/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001147 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001148 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001149 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001150 this tells our caller that the path based finder could not find
1151 a finder for this path item. Cache the result in
1152 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001153 Returns a borrowed reference. */
1154
1155static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001156get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1157 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *importer;
1160 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 /* These conditions are the caller's responsibility: */
1163 assert(PyList_Check(path_hooks));
1164 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 nhooks = PyList_Size(path_hooks);
1167 if (nhooks < 0)
1168 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001169
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001170 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001171 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* set path_importer_cache[p] to None to avoid recursion */
1175 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1176 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 for (j = 0; j < nhooks; j++) {
1179 PyObject *hook = PyList_GetItem(path_hooks, j);
1180 if (hook == NULL)
1181 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001182 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (importer != NULL)
1184 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001185
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001186 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return NULL;
1188 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001189 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 }
1191 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001192 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 }
1194 if (importer != NULL) {
1195 int err = PyDict_SetItem(path_importer_cache, p, importer);
1196 Py_DECREF(importer);
1197 if (err != 0)
1198 return NULL;
1199 }
1200 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001201}
1202
Benjamin Petersone5024512018-09-12 12:06:42 -07001203PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001204PyImport_GetImporter(PyObject *path)
1205{
1206 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001208
Victor Stinner1e53bba2013-07-16 22:26:05 +02001209 path_importer_cache = PySys_GetObject("path_importer_cache");
1210 path_hooks = PySys_GetObject("path_hooks");
1211 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001212 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001213 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 }
1215 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1216 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001217}
1218
Nick Coghland5cacbb2015-05-23 22:24:10 +10001219/*[clinic input]
1220_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001221
Nick Coghland5cacbb2015-05-23 22:24:10 +10001222 spec: object
1223 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001224
Nick Coghland5cacbb2015-05-23 22:24:10 +10001225Create an extension module.
1226[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001227
Nick Coghland5cacbb2015-05-23 22:24:10 +10001228static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001229_imp_create_builtin(PyObject *module, PyObject *spec)
1230/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001231{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001232 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001234 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001235 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001236 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001237
Nick Coghland5cacbb2015-05-23 22:24:10 +10001238 name = PyObject_GetAttrString(spec, "name");
1239 if (name == NULL) {
1240 return NULL;
1241 }
1242
Victor Stinner5eb4f592013-11-14 22:38:52 +01001243 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001244 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001245 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001246 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001247 return mod;
1248 }
1249
1250 namestr = PyUnicode_AsUTF8(name);
1251 if (namestr == NULL) {
1252 Py_DECREF(name);
1253 return NULL;
1254 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001255
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001256 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001258 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001259 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001261 /* Cannot re-init internal module ("sys" or "builtins") */
1262 mod = PyImport_AddModule(namestr);
1263 Py_DECREF(name);
1264 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001267 if (mod == NULL) {
1268 Py_DECREF(name);
1269 return NULL;
1270 }
1271 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1272 Py_DECREF(name);
1273 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1274 } else {
1275 /* Remember pointer to module init function. */
1276 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001277 if (def == NULL) {
1278 Py_DECREF(name);
1279 return NULL;
1280 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001281 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001282 if (_PyImport_FixupExtensionObject(mod, name, name,
1283 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001284 Py_DECREF(name);
1285 return NULL;
1286 }
1287 Py_DECREF(name);
1288 return mod;
1289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 }
1291 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001292 Py_DECREF(name);
1293 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001294}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001295
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001296
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001297/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001298
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001299static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001300find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001301{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001302 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001303
Victor Stinner53dc7352011-03-20 01:50:21 +01001304 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 for (p = PyImport_FrozenModules; ; p++) {
1308 if (p->name == NULL)
1309 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001310 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 break;
1312 }
1313 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001314}
1315
Guido van Rossum79f25d91997-04-29 20:08:16 +00001316static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001317get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001318{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001319 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (p == NULL) {
1323 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001324 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 name);
1326 return NULL;
1327 }
1328 if (p->code == NULL) {
1329 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001330 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 name);
1332 return NULL;
1333 }
1334 size = p->size;
1335 if (size < 0)
1336 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001337 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001338}
1339
Brett Cannon8d110132009-03-15 02:20:16 +00001340static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001341is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001342{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001343 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (p == NULL) {
1347 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001348 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 name);
1350 return NULL;
1351 }
Brett Cannon8d110132009-03-15 02:20:16 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 if (size < 0)
1356 Py_RETURN_TRUE;
1357 else
1358 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001359}
1360
1361
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001362/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001363 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001364 an exception set if the initialization failed.
1365 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001366
1367int
Victor Stinner53dc7352011-03-20 01:50:21 +01001368PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001369{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001370 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001371 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001372 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 int ispackage;
1374 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001375
Victor Stinner53dc7352011-03-20 01:50:21 +01001376 p = find_frozen(name);
1377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (p == NULL)
1379 return 0;
1380 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001381 _PyErr_Format(tstate, PyExc_ImportError,
1382 "Excluded frozen object named %R",
1383 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return -1;
1385 }
1386 size = p->size;
1387 ispackage = (size < 0);
1388 if (ispackage)
1389 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001390 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (co == NULL)
1392 return -1;
1393 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001394 _PyErr_Format(tstate, PyExc_TypeError,
1395 "frozen object %R is not a code object",
1396 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 goto err_return;
1398 }
1399 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001400 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001401 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001403 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 if (m == NULL)
1405 goto err_return;
1406 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001407 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 goto err_return;
1410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 err = PyDict_SetItemString(d, "__path__", l);
1412 Py_DECREF(l);
1413 if (err != 0)
1414 goto err_return;
1415 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001416 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001417 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001418 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001419 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001420 m = exec_code_in_module(tstate, name, d, co);
1421 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_DECREF(co);
1425 Py_DECREF(m);
1426 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001427
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001428err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 Py_DECREF(co);
1430 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001431}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001432
Victor Stinner53dc7352011-03-20 01:50:21 +01001433int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001434PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001435{
1436 PyObject *nameobj;
1437 int ret;
1438 nameobj = PyUnicode_InternFromString(name);
1439 if (nameobj == NULL)
1440 return -1;
1441 ret = PyImport_ImportFrozenModuleObject(nameobj);
1442 Py_DECREF(nameobj);
1443 return ret;
1444}
1445
Guido van Rossum74e6a111994-08-29 12:54:38 +00001446
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001447/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001448 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001449
Guido van Rossum79f25d91997-04-29 20:08:16 +00001450PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001451PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *pname;
1454 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 pname = PyUnicode_FromString(name);
1457 if (pname == NULL)
1458 return NULL;
1459 result = PyImport_Import(pname);
1460 Py_DECREF(pname);
1461 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001462}
1463
Christian Heimes072c0f12008-01-03 23:01:04 +00001464/* Import a module without blocking
1465 *
1466 * At first it tries to fetch the module from sys.modules. If the module was
1467 * never loaded before it loads it with PyImport_ImportModule() unless another
1468 * thread holds the import lock. In the latter case the function raises an
1469 * ImportError instead of blocking.
1470 *
1471 * Returns the module object with incremented ref count.
1472 */
1473PyObject *
1474PyImport_ImportModuleNoBlock(const char *name)
1475{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001476 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001477}
1478
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001479
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001480/* Remove importlib frames from the traceback,
1481 * except in Verbose mode. */
1482static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001483remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001484{
1485 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001486 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001487 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001488 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001489 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001490 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001491 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001492
1493 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001494 from the traceback. We always trim chunks
1495 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001496
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001497 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
1498 if (!exception || tstate->interp->config.verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001499 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001500 }
1501
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001502 if (PyType_IsSubtype((PyTypeObject *) exception,
1503 (PyTypeObject *) PyExc_ImportError))
1504 always_trim = 1;
1505
1506 prev_link = &base_tb;
1507 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001508 while (tb != NULL) {
1509 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1510 PyObject *next = (PyObject *) traceback->tb_next;
1511 PyFrameObject *frame = traceback->tb_frame;
1512 PyCodeObject *code = frame->f_code;
1513 int now_in_importlib;
1514
1515 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001516 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1517 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001518 if (now_in_importlib && !in_importlib) {
1519 /* This is the link to this chunk of importlib tracebacks */
1520 outer_link = prev_link;
1521 }
1522 in_importlib = now_in_importlib;
1523
1524 if (in_importlib &&
1525 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001526 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001527 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001528 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001529 prev_link = outer_link;
1530 }
1531 else {
1532 prev_link = (PyObject **) &traceback->tb_next;
1533 }
1534 tb = next;
1535 }
1536done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001537 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001538}
1539
1540
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001541static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001542resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001543{
Eric Snowb523f842013-11-22 09:05:39 -07001544 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001545 _Py_IDENTIFIER(__package__);
1546 _Py_IDENTIFIER(__path__);
1547 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001548 _Py_IDENTIFIER(parent);
1549 PyObject *abs_name;
1550 PyObject *package = NULL;
1551 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001552 Py_ssize_t last_dot;
1553 PyObject *base;
1554 int level_up;
1555
1556 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001557 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001558 goto error;
1559 }
1560 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001561 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001562 goto error;
1563 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001564 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001565 if (package == Py_None) {
1566 package = NULL;
1567 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001568 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001569 goto error;
1570 }
1571 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001572 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001573 goto error;
1574 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001575
1576 if (package != NULL) {
1577 Py_INCREF(package);
1578 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001579 _PyErr_SetString(tstate, PyExc_TypeError,
1580 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001581 goto error;
1582 }
1583 else if (spec != NULL && spec != Py_None) {
1584 int equal;
1585 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1586 if (parent == NULL) {
1587 goto error;
1588 }
1589
1590 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1591 Py_DECREF(parent);
1592 if (equal < 0) {
1593 goto error;
1594 }
1595 else if (equal == 0) {
1596 if (PyErr_WarnEx(PyExc_ImportWarning,
1597 "__package__ != __spec__.parent", 1) < 0) {
1598 goto error;
1599 }
1600 }
1601 }
1602 }
1603 else if (spec != NULL && spec != Py_None) {
1604 package = _PyObject_GetAttrId(spec, &PyId_parent);
1605 if (package == NULL) {
1606 goto error;
1607 }
1608 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001609 _PyErr_SetString(tstate, PyExc_TypeError,
1610 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001611 goto error;
1612 }
1613 }
1614 else {
1615 if (PyErr_WarnEx(PyExc_ImportWarning,
1616 "can't resolve package from __spec__ or __package__, "
1617 "falling back on __name__ and __path__", 1) < 0) {
1618 goto error;
1619 }
1620
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001621 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001622 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001623 if (!_PyErr_Occurred(tstate)) {
1624 _PyErr_SetString(tstate, PyExc_KeyError,
1625 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001626 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001627 goto error;
1628 }
1629
1630 Py_INCREF(package);
1631 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001632 _PyErr_SetString(tstate, PyExc_TypeError,
1633 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001634 goto error;
1635 }
1636
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001637 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001638 Py_ssize_t dot;
1639
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001640 if (_PyErr_Occurred(tstate) || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001641 goto error;
1642 }
1643
1644 dot = PyUnicode_FindChar(package, '.',
1645 0, PyUnicode_GET_LENGTH(package), -1);
1646 if (dot == -2) {
1647 goto error;
1648 }
1649
1650 if (dot >= 0) {
1651 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1652 if (substr == NULL) {
1653 goto error;
1654 }
1655 Py_SETREF(package, substr);
1656 }
1657 }
1658 }
1659
1660 last_dot = PyUnicode_GET_LENGTH(package);
1661 if (last_dot == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001662 _PyErr_SetString(tstate, PyExc_ImportError,
1663 "attempted relative import "
1664 "with no known parent package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001665 goto error;
1666 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001667
1668 for (level_up = 1; level_up < level; level_up += 1) {
1669 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1670 if (last_dot == -2) {
1671 goto error;
1672 }
1673 else if (last_dot == -1) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001674 _PyErr_SetString(tstate, PyExc_ValueError,
1675 "attempted relative import beyond top-level "
1676 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001677 goto error;
1678 }
1679 }
1680
1681 base = PyUnicode_Substring(package, 0, last_dot);
1682 Py_DECREF(package);
1683 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1684 return base;
1685 }
1686
1687 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1688 Py_DECREF(base);
1689 return abs_name;
1690
1691 error:
1692 Py_XDECREF(package);
1693 return NULL;
1694}
1695
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001696static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001697import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001698{
1699 _Py_IDENTIFIER(_find_and_load);
1700 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001701 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +02001702 int import_time = interp->config.import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001703 static int import_level;
1704 static _PyTime_t accumulated;
1705
1706 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1707
Steve Dowerb82e17e2019-05-23 08:45:22 -07001708 PyObject *sys_path = PySys_GetObject("path");
1709 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1710 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1711 if (PySys_Audit("import", "OOOOO",
1712 abs_name, Py_None, sys_path ? sys_path : Py_None,
1713 sys_meta_path ? sys_meta_path : Py_None,
1714 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1715 return NULL;
1716 }
1717
1718
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001719 /* XOptions is initialized after first some imports.
1720 * So we can't have negative cache before completed initialization.
1721 * Anyway, importlib._find_and_load is much slower than
1722 * _PyDict_GetItemIdWithError().
1723 */
1724 if (import_time) {
1725 static int header = 1;
1726 if (header) {
1727 fputs("import time: self [us] | cumulative | imported package\n",
1728 stderr);
1729 header = 0;
1730 }
1731
1732 import_level++;
1733 t1 = _PyTime_GetPerfCounter();
1734 accumulated = 0;
1735 }
1736
1737 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1738 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1739
1740 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1741 &PyId__find_and_load, abs_name,
1742 interp->import_func, NULL);
1743
1744 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1745 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1746 mod != NULL);
1747
1748 if (import_time) {
1749 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1750
1751 import_level--;
1752 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1753 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1754 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1755 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1756
1757 accumulated = accumulated_copy + cum;
1758 }
1759
1760 return mod;
1761}
1762
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001763PyObject *
1764PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1765 PyObject *locals, PyObject *fromlist,
1766 int level)
1767{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001768 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001769 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001770 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001771 PyObject *final_mod = NULL;
1772 PyObject *mod = NULL;
1773 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001774 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001775 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001776
Brett Cannonfd074152012-04-14 14:10:13 -04001777 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001778 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001779 goto error;
1780 }
1781
1782 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1783 for added performance. */
1784
1785 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001786 _PyErr_SetString(tstate, PyExc_TypeError,
1787 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001788 goto error;
1789 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001790 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001791 goto error;
1792 }
1793 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001794 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001795 goto error;
1796 }
Brett Cannon849113a2016-01-22 15:25:50 -08001797
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001798 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001799 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001800 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001801 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001802 }
1803 else { /* level == 0 */
1804 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001805 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001806 goto error;
1807 }
Brett Cannonfd074152012-04-14 14:10:13 -04001808 abs_name = name;
1809 Py_INCREF(abs_name);
1810 }
1811
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001812 mod = import_get_module(tstate, abs_name);
1813 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001814 goto error;
1815 }
1816
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001817 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001818 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001819 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001820 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001821
Antoine Pitrou03989852012-08-28 00:24:52 +02001822 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001823 __spec__._initializing is true.
1824 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001825 stuffing the new module in sys.modules.
1826 */
Eric Snowb523f842013-11-22 09:05:39 -07001827 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001828 if (_PyModuleSpec_IsInitializing(spec)) {
1829 PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1830 &PyId__lock_unlock_module, abs_name,
1831 NULL);
1832 if (value == NULL) {
1833 Py_DECREF(spec);
1834 goto error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001835 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001836 Py_DECREF(value);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001837 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001838 Py_XDECREF(spec);
Brett Cannonfd074152012-04-14 14:10:13 -04001839 }
1840 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001841 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001842 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001843 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001844 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001845 }
1846 }
1847
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001848 has_from = 0;
1849 if (fromlist != NULL && fromlist != Py_None) {
1850 has_from = PyObject_IsTrue(fromlist);
1851 if (has_from < 0)
1852 goto error;
1853 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001854 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001855 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1856 if (level == 0 || len > 0) {
1857 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001858
Victor Stinner744c34e2016-05-20 11:36:13 +02001859 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1860 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001861 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001862 }
1863
Victor Stinner744c34e2016-05-20 11:36:13 +02001864 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001865 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001866 final_mod = mod;
1867 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001868 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001869 }
1870
Brett Cannonfd074152012-04-14 14:10:13 -04001871 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001872 PyObject *front = PyUnicode_Substring(name, 0, dot);
1873 if (front == NULL) {
1874 goto error;
1875 }
1876
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001877 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001878 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001879 }
1880 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001881 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001882 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001883 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001884 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001885 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001886 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001887 }
Brett Cannonfd074152012-04-14 14:10:13 -04001888
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001889 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001890 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001891 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001892 if (!_PyErr_Occurred(tstate)) {
1893 _PyErr_Format(tstate, PyExc_KeyError,
1894 "%R not in sys.modules as expected",
1895 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001896 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001897 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001898 }
Brett Cannonfd074152012-04-14 14:10:13 -04001899 }
1900 }
1901 else {
1902 final_mod = mod;
1903 Py_INCREF(mod);
1904 }
1905 }
1906 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001907 _Py_IDENTIFIER(__path__);
1908 PyObject *path;
1909 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1910 goto error;
1911 }
1912 if (path) {
1913 Py_DECREF(path);
1914 final_mod = _PyObject_CallMethodIdObjArgs(
1915 interp->importlib, &PyId__handle_fromlist,
1916 mod, fromlist, interp->import_func, NULL);
1917 }
1918 else {
1919 final_mod = mod;
1920 Py_INCREF(mod);
1921 }
Brett Cannonfd074152012-04-14 14:10:13 -04001922 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001923
Brett Cannonfd074152012-04-14 14:10:13 -04001924 error:
1925 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001926 Py_XDECREF(mod);
1927 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001928 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001929 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001930 }
Brett Cannonfd074152012-04-14 14:10:13 -04001931 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001932}
1933
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001934PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001935PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001936 PyObject *fromlist, int level)
1937{
1938 PyObject *nameobj, *mod;
1939 nameobj = PyUnicode_FromString(name);
1940 if (nameobj == NULL)
1941 return NULL;
1942 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1943 fromlist, level);
1944 Py_DECREF(nameobj);
1945 return mod;
1946}
1947
1948
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001949/* Re-import a module of any kind and return its module object, WITH
1950 INCREMENTED REFERENCE COUNT */
1951
Guido van Rossum79f25d91997-04-29 20:08:16 +00001952PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001953PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001954{
Eric Snow3f9eee62017-09-15 16:35:20 -06001955 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001956 _Py_IDENTIFIER(reload);
1957 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001958 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001959 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001960 if (PyErr_Occurred()) {
1961 return NULL;
1962 }
1963
Brett Cannon62228db2012-04-29 14:38:11 -04001964 imp = PyImport_ImportModule("imp");
1965 if (imp == NULL) {
1966 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001969
Victor Stinner55ba38a2016-12-09 16:09:30 +01001970 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001971 Py_DECREF(imp);
1972 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001973}
1974
1975
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001976/* Higher-level import emulator which emulates the "import" statement
1977 more accurately -- it invokes the __import__() function from the
1978 builtins of the current globals. This means that the import is
1979 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001980 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001981 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001982 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001983 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001984
1985PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001986PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001987{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001988 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 static PyObject *silly_list = NULL;
1990 static PyObject *builtins_str = NULL;
1991 static PyObject *import_str = NULL;
1992 PyObject *globals = NULL;
1993 PyObject *import = NULL;
1994 PyObject *builtins = NULL;
1995 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 /* Initialize constant string objects */
1998 if (silly_list == NULL) {
1999 import_str = PyUnicode_InternFromString("__import__");
2000 if (import_str == NULL)
2001 return NULL;
2002 builtins_str = PyUnicode_InternFromString("__builtins__");
2003 if (builtins_str == NULL)
2004 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002005 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (silly_list == NULL)
2007 return NULL;
2008 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* Get the builtins from current globals */
2011 globals = PyEval_GetGlobals();
2012 if (globals != NULL) {
2013 Py_INCREF(globals);
2014 builtins = PyObject_GetItem(globals, builtins_str);
2015 if (builtins == NULL)
2016 goto err;
2017 }
2018 else {
2019 /* No globals -- use standard builtins, and fake globals */
2020 builtins = PyImport_ImportModuleLevel("builtins",
2021 NULL, NULL, NULL, 0);
2022 if (builtins == NULL)
2023 return NULL;
2024 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2025 if (globals == NULL)
2026 goto err;
2027 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* Get the __import__ function from the builtins */
2030 if (PyDict_Check(builtins)) {
2031 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002032 if (import == NULL) {
2033 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2034 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 }
2036 else
2037 import = PyObject_GetAttr(builtins, import_str);
2038 if (import == NULL)
2039 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002042 Always use absolute import here.
2043 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2045 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002046 if (r == NULL)
2047 goto err;
2048 Py_DECREF(r);
2049
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002050 r = import_get_module(tstate, module_name);
2051 if (r == NULL && !_PyErr_Occurred(tstate)) {
2052 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002053 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002054
2055 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 Py_XDECREF(globals);
2057 Py_XDECREF(builtins);
2058 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002061}
2062
Brett Cannon4caa61d2014-01-09 19:03:32 -05002063/*[clinic input]
2064_imp.extension_suffixes
2065
2066Returns the list of file suffixes used to identify extension modules.
2067[clinic start generated code]*/
2068
Brett Cannon4caa61d2014-01-09 19:03:32 -05002069static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002070_imp_extension_suffixes_impl(PyObject *module)
2071/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 list = PyList_New(0);
2076 if (list == NULL)
2077 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002078#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002079 const char *suffix;
2080 unsigned int index = 0;
2081
Brett Cannon2657df42012-05-04 15:20:40 -04002082 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2083 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 if (item == NULL) {
2085 Py_DECREF(list);
2086 return NULL;
2087 }
2088 if (PyList_Append(list, item) < 0) {
2089 Py_DECREF(list);
2090 Py_DECREF(item);
2091 return NULL;
2092 }
2093 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002094 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 }
Brett Cannon2657df42012-05-04 15:20:40 -04002096#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002098}
2099
Brett Cannon4caa61d2014-01-09 19:03:32 -05002100/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002101_imp.init_frozen
2102
2103 name: unicode
2104 /
2105
2106Initializes a frozen module.
2107[clinic start generated code]*/
2108
Brett Cannon4caa61d2014-01-09 19:03:32 -05002109static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002110_imp_init_frozen_impl(PyObject *module, PyObject *name)
2111/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002112{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002113 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 int ret;
2115 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002116
Victor Stinner53dc7352011-03-20 01:50:21 +01002117 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 if (ret < 0)
2119 return NULL;
2120 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002121 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002123 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 Py_XINCREF(m);
2125 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002126}
2127
Brett Cannon4caa61d2014-01-09 19:03:32 -05002128/*[clinic input]
2129_imp.get_frozen_object
2130
2131 name: unicode
2132 /
2133
2134Create a code object for a frozen module.
2135[clinic start generated code]*/
2136
Brett Cannon4caa61d2014-01-09 19:03:32 -05002137static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002138_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2139/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002142}
2143
Brett Cannon4caa61d2014-01-09 19:03:32 -05002144/*[clinic input]
2145_imp.is_frozen_package
2146
2147 name: unicode
2148 /
2149
2150Returns True if the module name is of a frozen package.
2151[clinic start generated code]*/
2152
Brett Cannon4caa61d2014-01-09 19:03:32 -05002153static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002154_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2155/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002158}
2159
Brett Cannon4caa61d2014-01-09 19:03:32 -05002160/*[clinic input]
2161_imp.is_builtin
2162
2163 name: unicode
2164 /
2165
2166Returns True if the module name corresponds to a built-in module.
2167[clinic start generated code]*/
2168
Guido van Rossum79f25d91997-04-29 20:08:16 +00002169static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002170_imp_is_builtin_impl(PyObject *module, PyObject *name)
2171/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002172{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002173 return PyLong_FromLong(is_builtin(name));
2174}
2175
2176/*[clinic input]
2177_imp.is_frozen
2178
2179 name: unicode
2180 /
2181
2182Returns True if the module name corresponds to a frozen module.
2183[clinic start generated code]*/
2184
Brett Cannon4caa61d2014-01-09 19:03:32 -05002185static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002186_imp_is_frozen_impl(PyObject *module, PyObject *name)
2187/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002188{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002189 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 p = find_frozen(name);
2192 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002193}
2194
Larry Hastings1df0b352015-08-24 19:53:56 -07002195/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2196static int
2197exec_builtin_or_dynamic(PyObject *mod) {
2198 PyModuleDef *def;
2199 void *state;
2200
2201 if (!PyModule_Check(mod)) {
2202 return 0;
2203 }
2204
2205 def = PyModule_GetDef(mod);
2206 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002207 return 0;
2208 }
Brett Cannon52794db2016-09-07 17:00:43 -07002209
Larry Hastings1df0b352015-08-24 19:53:56 -07002210 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002211 if (state) {
2212 /* Already initialized; skip reload */
2213 return 0;
2214 }
Brett Cannon52794db2016-09-07 17:00:43 -07002215
Larry Hastings1df0b352015-08-24 19:53:56 -07002216 return PyModule_ExecDef(mod, def);
2217}
2218
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002219#ifdef HAVE_DYNAMIC_LOADING
2220
Brett Cannon4caa61d2014-01-09 19:03:32 -05002221/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002222_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002223
Nick Coghland5cacbb2015-05-23 22:24:10 +10002224 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002225 file: object = NULL
2226 /
2227
Nick Coghland5cacbb2015-05-23 22:24:10 +10002228Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002229[clinic start generated code]*/
2230
Brett Cannon4caa61d2014-01-09 19:03:32 -05002231static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002232_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2233/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002234{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002235 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002236 FILE *fp;
2237
Nick Coghland5cacbb2015-05-23 22:24:10 +10002238 name = PyObject_GetAttrString(spec, "name");
2239 if (name == NULL) {
2240 return NULL;
2241 }
2242
2243 path = PyObject_GetAttrString(spec, "origin");
2244 if (path == NULL) {
2245 Py_DECREF(name);
2246 return NULL;
2247 }
2248
2249 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002250 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002251 Py_DECREF(name);
2252 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002253 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002254 return mod;
2255 }
2256
Brett Cannon4caa61d2014-01-09 19:03:32 -05002257 if (file != NULL) {
2258 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002259 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002260 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002261 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002265 else
2266 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002267
2268 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2269
2270 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002271 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (fp)
2273 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002274 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002275}
2276
Nick Coghland5cacbb2015-05-23 22:24:10 +10002277/*[clinic input]
2278_imp.exec_dynamic -> int
2279
2280 mod: object
2281 /
2282
2283Initialize an extension module.
2284[clinic start generated code]*/
2285
2286static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002287_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2288/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002289{
Larry Hastings1df0b352015-08-24 19:53:56 -07002290 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002291}
2292
2293
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002294#endif /* HAVE_DYNAMIC_LOADING */
2295
Larry Hastings7726ac92014-01-31 22:03:12 -08002296/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002297_imp.exec_builtin -> int
2298
2299 mod: object
2300 /
2301
2302Initialize a built-in module.
2303[clinic start generated code]*/
2304
2305static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002306_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2307/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002308{
2309 return exec_builtin_or_dynamic(mod);
2310}
2311
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002312/*[clinic input]
2313_imp.source_hash
2314
2315 key: long
2316 source: Py_buffer
2317[clinic start generated code]*/
2318
2319static PyObject *
2320_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2321/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2322{
Benjamin Peterson83620772017-12-09 12:18:56 -08002323 union {
2324 uint64_t x;
2325 char data[sizeof(uint64_t)];
2326 } hash;
2327 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002328#if !PY_LITTLE_ENDIAN
2329 // Force to little-endian. There really ought to be a succinct standard way
2330 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002331 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2332 char tmp = hash.data[i];
2333 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2334 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002335 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002336#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002337 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002338}
2339
Barry Warsaw28a691b2010-04-17 00:19:56 +00002340
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002341PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002342"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002343
Guido van Rossum79f25d91997-04-29 20:08:16 +00002344static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002345 _IMP_EXTENSION_SUFFIXES_METHODDEF
2346 _IMP_LOCK_HELD_METHODDEF
2347 _IMP_ACQUIRE_LOCK_METHODDEF
2348 _IMP_RELEASE_LOCK_METHODDEF
2349 _IMP_GET_FROZEN_OBJECT_METHODDEF
2350 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002351 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002352 _IMP_INIT_FROZEN_METHODDEF
2353 _IMP_IS_BUILTIN_METHODDEF
2354 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002355 _IMP_CREATE_DYNAMIC_METHODDEF
2356 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002357 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002358 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002359 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002360 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002361};
2362
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002363
Martin v. Löwis1a214512008-06-11 05:26:20 +00002364static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002366 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 doc_imp,
2368 0,
2369 imp_methods,
2370 NULL,
2371 NULL,
2372 NULL,
2373 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002374};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002375
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002376PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002377PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002382 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002384 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002386 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002388 }
2389
Victor Stinner331a6a52019-05-27 16:39:22 +02002390 const wchar_t *mode = _PyInterpreterState_Get()->config.check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002391 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002392 if (pyc_mode == NULL) {
2393 goto failure;
2394 }
2395 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2396 Py_DECREF(pyc_mode);
2397 goto failure;
2398 }
2399 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002402 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 Py_XDECREF(m);
2404 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002405}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002406
2407
Guido van Rossumb18618d2000-05-03 23:44:39 +00002408/* API for embedding applications that want to add their own entries
2409 to the table of built-in modules. This should normally be called
2410 *before* Py_Initialize(). When the table resize fails, -1 is
2411 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002412
2413 After a similar function by Just van Rossum. */
2414
2415int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002416PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002419 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002420 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 /* Count the number of entries in both tables */
2423 for (n = 0; newtab[n].name != NULL; n++)
2424 ;
2425 if (n == 0)
2426 return 0; /* Nothing to do */
2427 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2428 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002429
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002430 /* Force default raw memory allocator to get a known allocator to be able
2431 to release the memory in _PyImport_Fini2() */
2432 PyMemAllocatorEx old_alloc;
2433 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002436 p = NULL;
2437 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002438 size_t size = sizeof(struct _inittab) * (i + n + 1);
2439 p = PyMem_RawRealloc(inittab_copy, size);
2440 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002441 if (p == NULL) {
2442 res = -1;
2443 goto done;
2444 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002445
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002446 /* Copy the tables into the new memory at the first call
2447 to PyImport_ExtendInittab(). */
2448 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002450 }
2451 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2452 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002453
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002454done:
2455 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2456 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002457}
2458
2459/* Shorthand to add a single entry given a name and a function */
2460
2461int
Brett Cannona826f322009-04-02 03:41:46 +00002462PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002467
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002468 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002472}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002473
2474#ifdef __cplusplus
2475}
2476#endif