blob: 5be4d196a35537d96c3867f8dfa301fed32d5efd [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 Stinnerb45d2592019-06-20 00:05:23 +020051_PyImport_Init(PyThreadState *tstate)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052{
Victor Stinnerb45d2592019-06-20 00:05:23 +020053 PyInterpreterState *interp = tstate->interp;
Serhiy Storchaka013bb912014-02-10 18:21:34 +020054 interp->builtins_copy = PyDict_Copy(interp->builtins);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080055 if (interp->builtins_copy == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020056 return _PyStatus_ERR("Can't backup builtins dict");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080057 }
Victor Stinner331a6a52019-05-27 16:39:22 +020058 return _PyStatus_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059}
60
Victor Stinner331a6a52019-05-27 16:39:22 +020061PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020062_PyImportHooks_Init(PyThreadState *tstate)
Just van Rossum52e14d62002-12-30 22:08:05 +000063{
Brett Cannonfd074152012-04-14 14:10:13 -040064 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000066
Brett Cannonfd074152012-04-14 14:10:13 -040067 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 v = PyList_New(0);
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("meta_path", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 v = PyDict_New();
76 if (v == NULL)
77 goto error;
78 err = PySys_SetObject("path_importer_cache", v);
79 Py_DECREF(v);
80 if (err)
81 goto error;
82 path_hooks = PyList_New(0);
83 if (path_hooks == NULL)
84 goto error;
85 err = PySys_SetObject("path_hooks", path_hooks);
86 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 }
Brett Cannonfd074152012-04-14 14:10:13 -040089 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020090 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091
92 error:
Victor Stinnerb45d2592019-06-20 00:05:23 +020093 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020094 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040096}
97
Victor Stinner331a6a52019-05-27 16:39:22 +020098PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +020099_PyImportZip_Init(PyThreadState *tstate)
Brett Cannonfd074152012-04-14 14:10:13 -0400100{
ukwksk5e6312c2018-05-15 04:10:52 +0900101 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -0400102 int err = 0;
103
104 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200105 if (path_hooks == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200106 _PyErr_SetString(tstate, PyExc_RuntimeError,
107 "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400108 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200109 }
Brett Cannonfd074152012-04-14 14:10:13 -0400110
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200111 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200112 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400113 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200114 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000115
ukwksk5e6312c2018-05-15 04:10:52 +0900116 zipimport = PyImport_ImportModule("zipimport");
117 if (zipimport == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200118 _PyErr_Clear(tstate); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200119 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 }
123 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200124 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900125 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200126 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900127 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (zipimporter == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200129 _PyErr_Clear(tstate); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200130 if (verbose) {
131 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
132 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 }
134 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400135 /* sys.path_hooks.insert(0, zipimporter) */
136 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400138 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400140 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200141 if (verbose) {
142 PySys_WriteStderr("# installed zipimport hook\n");
143 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 }
145 }
Brett Cannonfd074152012-04-14 14:10:13 -0400146
Victor Stinner331a6a52019-05-27 16:39:22 +0200147 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400148
149 error:
150 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200151 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000152}
153
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154/* Locking primitives to prevent parallel imports of the same module
155 in different threads to return with a partially loaded module.
156 These calls are serialized by the global interpreter lock. */
157
Guido van Rossum49b56061998-10-01 20:42:43 +0000158#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000159
Guido van Rossum65d5b571998-12-21 19:32:43 +0000160static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200161static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000162static int import_lock_level = 0;
163
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000164void
165_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000166{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200167 unsigned long me = PyThread_get_thread_ident();
168 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 return; /* Too bad */
170 if (import_lock == NULL) {
171 import_lock = PyThread_allocate_lock();
172 if (import_lock == NULL)
173 return; /* Nothing much we can do. */
174 }
175 if (import_lock_thread == me) {
176 import_lock_level++;
177 return;
178 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200179 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
180 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 {
182 PyThreadState *tstate = PyEval_SaveThread();
183 PyThread_acquire_lock(import_lock, 1);
184 PyEval_RestoreThread(tstate);
185 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100186 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 import_lock_thread = me;
188 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000189}
190
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000191int
192_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000193{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200194 unsigned long me = PyThread_get_thread_ident();
195 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 return 0; /* Too bad */
197 if (import_lock_thread != me)
198 return -1;
199 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100200 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200202 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 PyThread_release_lock(import_lock);
204 }
205 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000206}
207
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200208/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000209 created child processes do not share locks with the parent.
210 We now acquire the import lock around fork() calls but on some platforms
211 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000212
213void
214_PyImport_ReInitLock(void)
215{
Christian Heimes418fd742015-04-19 21:08:42 +0200216 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200218 if (import_lock == NULL) {
219 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
220 }
221 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000222 if (import_lock_level > 1) {
223 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200224 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500225 /* The following could fail if the lock is already held, but forking as
226 a side-effect of an import is a) rare, b) nuts, and c) difficult to
227 do thanks to the lock only being held when doing individual module
228 locks per import. */
229 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000230 import_lock_thread = me;
231 import_lock_level--;
232 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200233 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000234 import_lock_level = 0;
235 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000236}
237
Brett Cannon4caa61d2014-01-09 19:03:32 -0500238/*[clinic input]
239_imp.lock_held
240
241Return True if the import lock is currently held, else False.
242
243On platforms without threads, return False.
244[clinic start generated code]*/
245
Brett Cannon4caa61d2014-01-09 19:03:32 -0500246static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300247_imp_lock_held_impl(PyObject *module)
248/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000249{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200250 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000251}
252
Brett Cannon4caa61d2014-01-09 19:03:32 -0500253/*[clinic input]
254_imp.acquire_lock
255
256Acquires the interpreter's import lock for the current thread.
257
258This lock should be used by import hooks to ensure thread-safety when importing
259modules. On platforms without threads, this function does nothing.
260[clinic start generated code]*/
261
Brett Cannon4caa61d2014-01-09 19:03:32 -0500262static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300263_imp_acquire_lock_impl(PyObject *module)
264/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200267 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000268}
269
Brett Cannon4caa61d2014-01-09 19:03:32 -0500270/*[clinic input]
271_imp.release_lock
272
273Release the interpreter's import lock.
274
275On platforms without threads, this function does nothing.
276[clinic start generated code]*/
277
Brett Cannon4caa61d2014-01-09 19:03:32 -0500278static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300279_imp_release_lock_impl(PyObject *module)
280/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 if (_PyImport_ReleaseLock() < 0) {
283 PyErr_SetString(PyExc_RuntimeError,
284 "not holding the import lock");
285 return NULL;
286 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200287 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000288}
289
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100290void
291_PyImport_Fini(void)
292{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200293 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100294 if (import_lock != NULL) {
295 PyThread_free_lock(import_lock);
296 import_lock = NULL;
297 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100298}
299
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100300void
301_PyImport_Fini2(void)
302{
303 /* Use the same memory allocator than PyImport_ExtendInittab(). */
304 PyMemAllocatorEx old_alloc;
305 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
306
307 /* Free memory allocated by PyImport_ExtendInittab() */
308 PyMem_RawFree(inittab_copy);
309
310 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
311}
312
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313/* Helper for sys */
314
315PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000316PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200318 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow3f9eee62017-09-15 16:35:20 -0600319 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700320 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600321 }
Eric Snow93c92f72017-09-13 23:46:04 -0700322 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323}
324
Eric Snowd393c1b2017-09-14 12:18:12 -0600325/* In some corner cases it is important to be sure that the import
326 machinery has been initialized (or not cleaned up yet). For
327 example, see issue #4236 and PyModule_Create2(). */
328
329int
330_PyImport_IsInitialized(PyInterpreterState *interp)
331{
332 if (interp->modules == NULL)
333 return 0;
334 return 1;
335}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000336
Eric Snow3f9eee62017-09-15 16:35:20 -0600337PyObject *
338_PyImport_GetModuleId(struct _Py_Identifier *nameid)
339{
340 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
341 if (name == NULL) {
342 return NULL;
343 }
344 return PyImport_GetModule(name);
345}
346
347int
348_PyImport_SetModule(PyObject *name, PyObject *m)
349{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200350 PyThreadState *tstate = _PyThreadState_GET();
351 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600352 return PyObject_SetItem(modules, name, m);
353}
354
355int
356_PyImport_SetModuleString(const char *name, PyObject *m)
357{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200358 PyThreadState *tstate = _PyThreadState_GET();
359 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600360 return PyMapping_SetItemString(modules, name, m);
361}
362
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200363static PyObject *
364import_get_module(PyThreadState *tstate, PyObject *name)
Eric Snow3f9eee62017-09-15 16:35:20 -0600365{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200366 PyObject *modules = tstate->interp->modules;
Eric Snow3f9eee62017-09-15 16:35:20 -0600367 if (modules == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200368 _PyErr_SetString(tstate, PyExc_RuntimeError,
369 "unable to get sys.modules");
Eric Snow3f9eee62017-09-15 16:35:20 -0600370 return NULL;
371 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200372
373 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600374 Py_INCREF(modules);
375 if (PyDict_CheckExact(modules)) {
376 m = PyDict_GetItemWithError(modules, name); /* borrowed */
377 Py_XINCREF(m);
378 }
379 else {
380 m = PyObject_GetItem(modules, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200381 if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
382 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600383 }
384 }
385 Py_DECREF(modules);
386 return m;
387}
388
389
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200390PyObject *
391PyImport_GetModule(PyObject *name)
392{
393 PyThreadState *tstate = _PyThreadState_GET();
394 return import_get_module(tstate, name);
395}
396
397
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000398/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200399static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 "path", "argv", "ps1", "ps2",
401 "last_type", "last_value", "last_traceback",
402 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200403 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405};
406
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200407static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 "stdin", "__stdin__",
409 "stdout", "__stdout__",
410 "stderr", "__stderr__",
411 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000412};
413
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000414/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000415
Guido van Rossum3f5da241990-12-20 15:06:42 +0000416void
Victor Stinner987a0dc2019-06-19 10:36:10 +0200417_PyImport_Cleanup(PyThreadState *tstate)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000418{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200419 PyInterpreterState *interp = tstate->interp;
420 PyObject *modules = interp->modules;
421 if (modules == NULL) {
422 /* Already done */
423 return;
424 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 /* Delete some special variables first. These are common
427 places where user values hide and people complain when their
428 destructors fail. Since the modules containing them are
429 deleted *last* of all, they would come too late in the normal
430 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000431
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200432 /* XXX Perhaps these precautions are obsolete. Who knows? */
433
Victor Stinner331a6a52019-05-27 16:39:22 +0200434 int verbose = interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200435 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200436 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200437 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300438 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300439 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300440 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200441
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200442 const char * const *p;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200443 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200444 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200445 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200446 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300447 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300448 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200451 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200452 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200453 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200454 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200455 PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
456 *(p+1));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200457 if (value == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200458 if (_PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200459 PyErr_WriteUnraisable(NULL);
460 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200461 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200462 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300463 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300464 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000467
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200468 /* We prepare a list which will receive (name, weakref) tuples of
469 modules when they are removed from sys.modules. The name is used
470 for diagnosis messages (in verbose mode), while the weakref helps
471 detect those modules which have been held alive. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200472 PyObject *weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300473 if (weaklist == NULL) {
474 PyErr_WriteUnraisable(NULL);
475 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200476
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200477#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200478 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200479 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300480 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200481 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300482 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300483 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300484 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200485 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300486 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200487 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300488 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300489 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300490 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600492#define CLEAR_MODULE(name, mod) \
493 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200494 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600495 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200496 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600497 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300498 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300499 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300500 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600501 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000502
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200503 /* Remove all modules from sys.modules, hoping that garbage collection
504 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600505 if (PyDict_CheckExact(modules)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200506 Py_ssize_t pos = 0;
507 PyObject *key, *value;
Eric Snow3f9eee62017-09-15 16:35:20 -0600508 while (PyDict_Next(modules, &pos, &key, &value)) {
509 CLEAR_MODULE(key, value);
510 }
511 }
512 else {
513 PyObject *iterator = PyObject_GetIter(modules);
514 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300515 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600516 }
517 else {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200518 PyObject *key;
Eric Snow3f9eee62017-09-15 16:35:20 -0600519 while ((key = PyIter_Next(iterator))) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200520 PyObject *value = PyObject_GetItem(modules, key);
Eric Snow3f9eee62017-09-15 16:35:20 -0600521 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300522 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600523 continue;
524 }
525 CLEAR_MODULE(key, value);
526 Py_DECREF(value);
527 Py_DECREF(key);
528 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300529 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300530 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300531 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600532 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 }
534 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000535
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200536 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600537 if (PyDict_CheckExact(modules)) {
538 PyDict_Clear(modules);
539 }
540 else {
541 _Py_IDENTIFIER(clear);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200542 if (_PyObject_CallMethodIdNoArgs(modules, &PyId_clear) == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300543 PyErr_WriteUnraisable(NULL);
544 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600545 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200546 /* Restore the original builtins dict, to ensure that any
547 user data gets cleared. */
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200548 PyObject *dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300549 if (dict == NULL) {
550 PyErr_WriteUnraisable(NULL);
551 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200552 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300553 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200554 _PyErr_Clear(tstate);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300555 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200556 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200557 /* Clear module dict copies stored in the interpreter state */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200558 _PyInterpreterState_ClearModules(interp);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200559 /* Collect references */
560 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200561 /* Dump GC stats before it's too late, since it uses the warnings
562 machinery. */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200563 _PyGC_DumpShutdownStats(&_PyRuntime);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200564
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200565 /* Now, if there are any modules left alive, clear their globals to
566 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200567 up here, since they are kept alive in the interpreter state.
568
569 The special treatment of "builtins" here is because even
570 when it's not referenced as a module, its dictionary is
571 referenced by almost every module's __builtins__. Since
572 deleting a module clears its dictionary (even if there are
573 references left to it), we need to delete the "builtins"
574 module last. Likewise, we don't delete sys until the very
575 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200576 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200577 Py_ssize_t i;
578 /* Since dict is ordered in CPython 3.6+, modules are saved in
579 importing order. First clear modules imported later. */
580 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200581 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200582 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200583 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
584 if (mod == Py_None)
585 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200586 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200587 dict = PyModule_GetDict(mod);
588 if (dict == interp->builtins || dict == interp->sysdict)
589 continue;
590 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200591 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200592 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200593 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200594 _PyModule_Clear(mod);
595 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200596 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200597 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000599
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200600 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200601 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200602 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200603 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200604 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200605 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200606 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200607 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200608 _PyModule_ClearDict(interp->builtins);
609
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200610 /* Clear and delete the modules directory. Actual modules will
611 still be there only if imported during the execution of some
612 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700613 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200615
616 /* Once more */
617 _PyGC_CollectNoFail();
618
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300619#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200620#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000621}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000622
623
Barry Warsaw28a691b2010-04-17 00:19:56 +0000624/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000625
626long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000627PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000628{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200629 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200630 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600631 PyObject *external, *pyc_magic;
632
633 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
634 if (external == NULL)
635 return -1;
636 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
637 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400638 if (pyc_magic == NULL)
639 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200640 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700641 Py_DECREF(pyc_magic);
642 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000643}
644
645
Brett Cannon3adc7b72012-07-09 14:22:12 -0400646extern const char * _PySys_ImplCacheTag;
647
Barry Warsaw28a691b2010-04-17 00:19:56 +0000648const char *
649PyImport_GetMagicTag(void)
650{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400651 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000652}
653
Brett Cannon98979b82012-07-02 15:13:11 -0400654
Guido van Rossum25ce5661997-08-02 03:10:38 +0000655/* Magic for extension modules (built-in as well as dynamically
656 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200657 once, we keep a static dictionary 'extensions' keyed by the tuple
658 (module name, module name) (for built-in modules) or by
659 (filename, module name) (for dynamically loaded modules), containing these
660 modules. A copy of the module's dictionary is stored by calling
661 _PyImport_FixupExtensionObject() immediately after the module initialization
662 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100663 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000664
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000665 Modules which do support multiple initialization set their m_size
666 field to a non-negative number (indicating the size of the
667 module-specific state). They are still recorded in the extensions
668 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000669*/
670
671int
Victor Stinner95872862011-03-07 18:20:56 +0100672_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200673 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000674{
Eric Snowd393c1b2017-09-14 12:18:12 -0600675 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500677 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (extensions == NULL) {
679 extensions = PyDict_New();
680 if (extensions == NULL)
681 return -1;
682 }
683 if (mod == NULL || !PyModule_Check(mod)) {
684 PyErr_BadInternalCall();
685 return -1;
686 }
687 def = PyModule_GetDef(mod);
688 if (!def) {
689 PyErr_BadInternalCall();
690 return -1;
691 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600692 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 return -1;
694 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600695 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 return -1;
697 }
698 if (def->m_size == -1) {
699 if (def->m_base.m_copy) {
700 /* Somebody already imported the module,
701 likely under a different name.
702 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200703 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 }
705 dict = PyModule_GetDict(mod);
706 if (dict == NULL)
707 return -1;
708 def->m_base.m_copy = PyDict_Copy(dict);
709 if (def->m_base.m_copy == NULL)
710 return -1;
711 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500712 key = PyTuple_Pack(2, filename, name);
713 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200714 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500715 res = PyDict_SetItem(extensions, key, (PyObject *)def);
716 Py_DECREF(key);
717 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200718 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000720}
721
Victor Stinner49d3f252010-10-17 01:24:53 +0000722int
Eric Snowd393c1b2017-09-14 12:18:12 -0600723_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000724{
725 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100726 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100727 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100728 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000729 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600730 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100731 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000732 return res;
733}
734
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200735static PyObject *
736import_find_extension(PyThreadState *tstate, PyObject *name,
737 PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000738{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200739 if (extensions == NULL) {
740 return NULL;
741 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600742
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200743 PyObject *key = PyTuple_Pack(2, filename, name);
744 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200746 }
747 PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500748 Py_DECREF(key);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200749 if (def == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200751 }
752
753 PyObject *mod, *mdict;
754 PyObject *modules = tstate->interp->modules;
755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (def->m_size == -1) {
757 /* Module does not support repeated initialization */
758 if (def->m_base.m_copy == NULL)
759 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200760 mod = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 if (mod == NULL)
762 return NULL;
763 mdict = PyModule_GetDict(mod);
764 if (mdict == NULL)
765 return NULL;
766 if (PyDict_Update(mdict, def->m_base.m_copy))
767 return NULL;
768 }
769 else {
770 if (def->m_base.m_init == NULL)
771 return NULL;
772 mod = def->m_base.m_init();
773 if (mod == NULL)
774 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600775 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200776 Py_DECREF(mod);
777 return NULL;
778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 Py_DECREF(mod);
780 }
781 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600782 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 return NULL;
784 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200785
786 int verbose = tstate->interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200787 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100788 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200789 name, filename);
790 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000792}
793
Victor Stinner49d3f252010-10-17 01:24:53 +0000794PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200795_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
796{
797 PyThreadState *tstate = _PyThreadState_GET();
798 return import_find_extension(tstate, name, filename);
799}
800
801
802PyObject *
803_PyImport_FindBuiltin(PyThreadState *tstate, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000804{
Victor Stinner95872862011-03-07 18:20:56 +0100805 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100806 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100807 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000808 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200809 res = import_find_extension(tstate, nameobj, nameobj);
Victor Stinner95872862011-03-07 18:20:56 +0100810 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000811 return res;
812}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813
814/* Get the module object corresponding to a module name.
815 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000816 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000817 Because the former action is most common, THIS DOES NOT RETURN A
818 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000819
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200820static PyObject *
821import_add_module(PyThreadState *tstate, PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000822{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200823 PyObject *modules = tstate->interp->modules;
824 if (modules == NULL) {
825 _PyErr_SetString(tstate, PyExc_RuntimeError,
826 "no import module dictionary");
827 return NULL;
828 }
Eric Snowd393c1b2017-09-14 12:18:12 -0600829
Eric Snow86b7afd2017-09-04 17:54:09 -0600830 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600831 if (PyDict_CheckExact(modules)) {
832 m = PyDict_GetItemWithError(modules, name);
833 }
834 else {
835 m = PyObject_GetItem(modules, name);
Min ho Kimc4cacc82019-07-31 08:16:13 +1000836 // For backward-compatibility we copy the behavior
Eric Snow3f9eee62017-09-15 16:35:20 -0600837 // of PyDict_GetItemWithError().
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200838 if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
839 _PyErr_Clear(tstate);
Eric Snow3f9eee62017-09-15 16:35:20 -0600840 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200841 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200842 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200843 return NULL;
844 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600845 if (m != NULL && PyModule_Check(m)) {
846 return m;
847 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000848 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (m == NULL)
850 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600851 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 Py_DECREF(m);
853 return NULL;
854 }
855 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000858}
859
Victor Stinner27ee0892011-03-04 12:57:09 +0000860PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200861PyImport_AddModuleObject(PyObject *name)
862{
863 PyThreadState *tstate = _PyThreadState_GET();
864 return import_add_module(tstate, name);
865}
866
867
868PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000869PyImport_AddModule(const char *name)
870{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200871 PyObject *nameobj = PyUnicode_FromString(name);
872 if (nameobj == NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000873 return NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200874 }
875 PyObject *module = PyImport_AddModuleObject(nameobj);
Victor Stinner27ee0892011-03-04 12:57:09 +0000876 Py_DECREF(nameobj);
877 return module;
878}
879
880
Tim Peters1cd70172004-08-02 03:52:12 +0000881/* Remove name from sys.modules, if it's there. */
882static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200883remove_module(PyThreadState *tstate, PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000884{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600885 PyObject *type, *value, *traceback;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200886 _PyErr_Fetch(tstate, &type, &value, &traceback);
887
888 PyObject *modules = tstate->interp->modules;
Zackery Spytz94a64e92019-05-08 10:31:23 -0600889 if (!PyMapping_HasKey(modules, name)) {
890 goto out;
891 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600892 if (PyMapping_DelItem(modules, name) < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200893 _PyErr_SetString(tstate, PyExc_RuntimeError,
894 "deleting key in sys.modules failed");
895 _PyErr_ChainExceptions(type, value, traceback);
896 return;
Eric Snow3f9eee62017-09-15 16:35:20 -0600897 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200898
Zackery Spytz94a64e92019-05-08 10:31:23 -0600899out:
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200900 _PyErr_Restore(tstate, type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000901}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000902
Christian Heimes3b06e532008-01-07 20:12:44 +0000903
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000904/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000905 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
906 * removed from sys.modules, to avoid leaving damaged module objects
907 * in sys.modules. The caller may wish to restore the original
908 * module object (if any) in this case; PyImport_ReloadModule is an
909 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000910 *
911 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
912 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000913 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000914PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300915PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 return PyImport_ExecCodeModuleWithPathnames(
918 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000919}
920
921PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300922PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 return PyImport_ExecCodeModuleWithPathnames(
925 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000926}
927
928PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300929PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
930 const char *pathname,
931 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000932{
Victor Stinner27ee0892011-03-04 12:57:09 +0000933 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600934 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000935
936 nameobj = PyUnicode_FromString(name);
937 if (nameobj == NULL)
938 return NULL;
939
Victor Stinner27ee0892011-03-04 12:57:09 +0000940 if (cpathname != NULL) {
941 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
942 if (cpathobj == NULL)
943 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400944 }
945 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000946 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400947
948 if (pathname != NULL) {
949 pathobj = PyUnicode_DecodeFSDefault(pathname);
950 if (pathobj == NULL)
951 goto error;
952 }
953 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200954 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400955 _Py_IDENTIFIER(_get_sourcefile);
956
957 if (interp == NULL) {
958 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
959 "no interpreter!");
960 }
961
Eric Snow32439d62015-05-02 19:15:18 -0600962 external= PyObject_GetAttrString(interp->importlib,
963 "_bootstrap_external");
964 if (external != NULL) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200965 pathobj = _PyObject_CallMethodIdOneArg(
966 external, &PyId__get_sourcefile, cpathobj);
Eric Snow32439d62015-05-02 19:15:18 -0600967 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;
Jeroen Demeyer196a5302019-07-04 12:31:34 +02001182 importer = _PyObject_CallOneArg(hook, p);
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 }
Ben Lewis92420b32019-09-11 20:09:47 +10001649 else if (dot == -1) {
1650 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001651 }
Ben Lewis92420b32019-09-11 20:09:47 +10001652 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1653 if (substr == NULL) {
1654 goto error;
1655 }
1656 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001657 }
1658 }
1659
1660 last_dot = PyUnicode_GET_LENGTH(package);
1661 if (last_dot == 0) {
Ben Lewis92420b32019-09-11 20:09:47 +10001662 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001663 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001664
1665 for (level_up = 1; level_up < level; level_up += 1) {
1666 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1667 if (last_dot == -2) {
1668 goto error;
1669 }
1670 else if (last_dot == -1) {
Ngalim Siregarc5fa4492019-08-03 12:46:02 +07001671 _PyErr_SetString(tstate, PyExc_ImportError,
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001672 "attempted relative import beyond top-level "
1673 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001674 goto error;
1675 }
1676 }
1677
1678 base = PyUnicode_Substring(package, 0, last_dot);
1679 Py_DECREF(package);
1680 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1681 return base;
1682 }
1683
1684 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1685 Py_DECREF(base);
1686 return abs_name;
1687
Ben Lewis92420b32019-09-11 20:09:47 +10001688 no_parent_error:
1689 _PyErr_SetString(tstate, PyExc_ImportError,
1690 "attempted relative import "
1691 "with no known parent package");
1692
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001693 error:
1694 Py_XDECREF(package);
1695 return NULL;
1696}
1697
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001698static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001699import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001700{
1701 _Py_IDENTIFIER(_find_and_load);
1702 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001703 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +02001704 int import_time = interp->config.import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001705 static int import_level;
1706 static _PyTime_t accumulated;
1707
1708 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1709
Steve Dowerb82e17e2019-05-23 08:45:22 -07001710 PyObject *sys_path = PySys_GetObject("path");
1711 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1712 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1713 if (PySys_Audit("import", "OOOOO",
1714 abs_name, Py_None, sys_path ? sys_path : Py_None,
1715 sys_meta_path ? sys_meta_path : Py_None,
1716 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1717 return NULL;
1718 }
1719
1720
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001721 /* XOptions is initialized after first some imports.
1722 * So we can't have negative cache before completed initialization.
1723 * Anyway, importlib._find_and_load is much slower than
1724 * _PyDict_GetItemIdWithError().
1725 */
1726 if (import_time) {
1727 static int header = 1;
1728 if (header) {
1729 fputs("import time: self [us] | cumulative | imported package\n",
1730 stderr);
1731 header = 0;
1732 }
1733
1734 import_level++;
1735 t1 = _PyTime_GetPerfCounter();
1736 accumulated = 0;
1737 }
1738
1739 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1740 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1741
1742 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1743 &PyId__find_and_load, abs_name,
1744 interp->import_func, NULL);
1745
1746 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1747 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1748 mod != NULL);
1749
1750 if (import_time) {
1751 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1752
1753 import_level--;
1754 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1755 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1756 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1757 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1758
1759 accumulated = accumulated_copy + cum;
1760 }
1761
1762 return mod;
1763}
1764
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001765PyObject *
1766PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1767 PyObject *locals, PyObject *fromlist,
1768 int level)
1769{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001770 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001771 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001772 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001773 PyObject *final_mod = NULL;
1774 PyObject *mod = NULL;
1775 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001776 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001777 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001778
Brett Cannonfd074152012-04-14 14:10:13 -04001779 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001780 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001781 goto error;
1782 }
1783
1784 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1785 for added performance. */
1786
1787 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001788 _PyErr_SetString(tstate, PyExc_TypeError,
1789 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001790 goto error;
1791 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001792 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001793 goto error;
1794 }
1795 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001796 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001797 goto error;
1798 }
Brett Cannon849113a2016-01-22 15:25:50 -08001799
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001800 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001801 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001802 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001803 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001804 }
1805 else { /* level == 0 */
1806 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001807 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001808 goto error;
1809 }
Brett Cannonfd074152012-04-14 14:10:13 -04001810 abs_name = name;
1811 Py_INCREF(abs_name);
1812 }
1813
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001814 mod = import_get_module(tstate, abs_name);
1815 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001816 goto error;
1817 }
1818
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001819 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001820 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001821 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001822 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001823
Antoine Pitrou03989852012-08-28 00:24:52 +02001824 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001825 __spec__._initializing is true.
1826 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001827 stuffing the new module in sys.modules.
1828 */
Eric Snowb523f842013-11-22 09:05:39 -07001829 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001830 if (_PyModuleSpec_IsInitializing(spec)) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001831 PyObject *value = _PyObject_CallMethodIdOneArg(
1832 interp->importlib, &PyId__lock_unlock_module, abs_name);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001833 if (value == NULL) {
1834 Py_DECREF(spec);
1835 goto error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001836 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001837 Py_DECREF(value);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001838 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001839 Py_XDECREF(spec);
Brett Cannonfd074152012-04-14 14:10:13 -04001840 }
1841 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001842 Py_XDECREF(mod);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001843 mod = import_find_and_load(tstate, abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001844 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001845 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001846 }
1847 }
1848
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001849 has_from = 0;
1850 if (fromlist != NULL && fromlist != Py_None) {
1851 has_from = PyObject_IsTrue(fromlist);
1852 if (has_from < 0)
1853 goto error;
1854 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001855 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001856 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1857 if (level == 0 || len > 0) {
1858 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001859
Victor Stinner744c34e2016-05-20 11:36:13 +02001860 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1861 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001862 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001863 }
1864
Victor Stinner744c34e2016-05-20 11:36:13 +02001865 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001866 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001867 final_mod = mod;
1868 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001869 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001870 }
1871
Brett Cannonfd074152012-04-14 14:10:13 -04001872 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001873 PyObject *front = PyUnicode_Substring(name, 0, dot);
1874 if (front == NULL) {
1875 goto error;
1876 }
1877
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001878 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001879 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001880 }
1881 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001882 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001883 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001884 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001885 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001886 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001887 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001888 }
Brett Cannonfd074152012-04-14 14:10:13 -04001889
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001890 final_mod = import_get_module(tstate, to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001891 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001892 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001893 if (!_PyErr_Occurred(tstate)) {
1894 _PyErr_Format(tstate, PyExc_KeyError,
1895 "%R not in sys.modules as expected",
1896 to_return);
Stefan Krah027b09c2019-03-25 21:50:58 +01001897 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001898 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001899 }
Brett Cannonfd074152012-04-14 14:10:13 -04001900 }
1901 }
1902 else {
1903 final_mod = mod;
1904 Py_INCREF(mod);
1905 }
1906 }
1907 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001908 _Py_IDENTIFIER(__path__);
1909 PyObject *path;
1910 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1911 goto error;
1912 }
1913 if (path) {
1914 Py_DECREF(path);
1915 final_mod = _PyObject_CallMethodIdObjArgs(
1916 interp->importlib, &PyId__handle_fromlist,
1917 mod, fromlist, interp->import_func, NULL);
1918 }
1919 else {
1920 final_mod = mod;
1921 Py_INCREF(mod);
1922 }
Brett Cannonfd074152012-04-14 14:10:13 -04001923 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001924
Brett Cannonfd074152012-04-14 14:10:13 -04001925 error:
1926 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001927 Py_XDECREF(mod);
1928 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001929 if (final_mod == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001930 remove_importlib_frames(tstate);
Victor Stinner410b85a2019-05-13 17:12:45 +02001931 }
Brett Cannonfd074152012-04-14 14:10:13 -04001932 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001933}
1934
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001935PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001936PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001937 PyObject *fromlist, int level)
1938{
1939 PyObject *nameobj, *mod;
1940 nameobj = PyUnicode_FromString(name);
1941 if (nameobj == NULL)
1942 return NULL;
1943 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1944 fromlist, level);
1945 Py_DECREF(nameobj);
1946 return mod;
1947}
1948
1949
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001950/* Re-import a module of any kind and return its module object, WITH
1951 INCREMENTED REFERENCE COUNT */
1952
Guido van Rossum79f25d91997-04-29 20:08:16 +00001953PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001954PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001955{
Eric Snow3f9eee62017-09-15 16:35:20 -06001956 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001957 _Py_IDENTIFIER(reload);
1958 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001959 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001960 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001961 if (PyErr_Occurred()) {
1962 return NULL;
1963 }
1964
Brett Cannon62228db2012-04-29 14:38:11 -04001965 imp = PyImport_ImportModule("imp");
1966 if (imp == NULL) {
1967 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001970
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001971 reloaded_module = _PyObject_CallMethodIdOneArg(imp, &PyId_reload, m);
Brett Cannon62228db2012-04-29 14:38:11 -04001972 Py_DECREF(imp);
1973 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001974}
1975
1976
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001977/* Higher-level import emulator which emulates the "import" statement
1978 more accurately -- it invokes the __import__() function from the
1979 builtins of the current globals. This means that the import is
1980 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001981 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001982 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001983 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001984 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001985
1986PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001987PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001988{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001989 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 static PyObject *silly_list = NULL;
1991 static PyObject *builtins_str = NULL;
1992 static PyObject *import_str = NULL;
1993 PyObject *globals = NULL;
1994 PyObject *import = NULL;
1995 PyObject *builtins = NULL;
1996 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* Initialize constant string objects */
1999 if (silly_list == NULL) {
2000 import_str = PyUnicode_InternFromString("__import__");
2001 if (import_str == NULL)
2002 return NULL;
2003 builtins_str = PyUnicode_InternFromString("__builtins__");
2004 if (builtins_str == NULL)
2005 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002006 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (silly_list == NULL)
2008 return NULL;
2009 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 /* Get the builtins from current globals */
2012 globals = PyEval_GetGlobals();
2013 if (globals != NULL) {
2014 Py_INCREF(globals);
2015 builtins = PyObject_GetItem(globals, builtins_str);
2016 if (builtins == NULL)
2017 goto err;
2018 }
2019 else {
2020 /* No globals -- use standard builtins, and fake globals */
2021 builtins = PyImport_ImportModuleLevel("builtins",
2022 NULL, NULL, NULL, 0);
2023 if (builtins == NULL)
2024 return NULL;
2025 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2026 if (globals == NULL)
2027 goto err;
2028 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* Get the __import__ function from the builtins */
2031 if (PyDict_Check(builtins)) {
2032 import = PyObject_GetItem(builtins, import_str);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002033 if (import == NULL) {
2034 _PyErr_SetObject(tstate, PyExc_KeyError, import_str);
2035 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 }
2037 else
2038 import = PyObject_GetAttr(builtins, import_str);
2039 if (import == NULL)
2040 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002043 Always use absolute import here.
2044 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2046 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002047 if (r == NULL)
2048 goto err;
2049 Py_DECREF(r);
2050
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002051 r = import_get_module(tstate, module_name);
2052 if (r == NULL && !_PyErr_Occurred(tstate)) {
2053 _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002054 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002055
2056 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 Py_XDECREF(globals);
2058 Py_XDECREF(builtins);
2059 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002062}
2063
Brett Cannon4caa61d2014-01-09 19:03:32 -05002064/*[clinic input]
2065_imp.extension_suffixes
2066
2067Returns the list of file suffixes used to identify extension modules.
2068[clinic start generated code]*/
2069
Brett Cannon4caa61d2014-01-09 19:03:32 -05002070static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002071_imp_extension_suffixes_impl(PyObject *module)
2072/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 list = PyList_New(0);
2077 if (list == NULL)
2078 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002079#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002080 const char *suffix;
2081 unsigned int index = 0;
2082
Brett Cannon2657df42012-05-04 15:20:40 -04002083 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2084 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if (item == NULL) {
2086 Py_DECREF(list);
2087 return NULL;
2088 }
2089 if (PyList_Append(list, item) < 0) {
2090 Py_DECREF(list);
2091 Py_DECREF(item);
2092 return NULL;
2093 }
2094 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002095 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 }
Brett Cannon2657df42012-05-04 15:20:40 -04002097#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002099}
2100
Brett Cannon4caa61d2014-01-09 19:03:32 -05002101/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002102_imp.init_frozen
2103
2104 name: unicode
2105 /
2106
2107Initializes a frozen module.
2108[clinic start generated code]*/
2109
Brett Cannon4caa61d2014-01-09 19:03:32 -05002110static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002111_imp_init_frozen_impl(PyObject *module, PyObject *name)
2112/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002113{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002114 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 int ret;
2116 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002117
Victor Stinner53dc7352011-03-20 01:50:21 +01002118 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (ret < 0)
2120 return NULL;
2121 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002122 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02002124 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 Py_XINCREF(m);
2126 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002127}
2128
Brett Cannon4caa61d2014-01-09 19:03:32 -05002129/*[clinic input]
2130_imp.get_frozen_object
2131
2132 name: unicode
2133 /
2134
2135Create a code object for a frozen module.
2136[clinic start generated code]*/
2137
Brett Cannon4caa61d2014-01-09 19:03:32 -05002138static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002139_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2140/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002143}
2144
Brett Cannon4caa61d2014-01-09 19:03:32 -05002145/*[clinic input]
2146_imp.is_frozen_package
2147
2148 name: unicode
2149 /
2150
2151Returns True if the module name is of a frozen package.
2152[clinic start generated code]*/
2153
Brett Cannon4caa61d2014-01-09 19:03:32 -05002154static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002155_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2156/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002159}
2160
Brett Cannon4caa61d2014-01-09 19:03:32 -05002161/*[clinic input]
2162_imp.is_builtin
2163
2164 name: unicode
2165 /
2166
2167Returns True if the module name corresponds to a built-in module.
2168[clinic start generated code]*/
2169
Guido van Rossum79f25d91997-04-29 20:08:16 +00002170static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002171_imp_is_builtin_impl(PyObject *module, PyObject *name)
2172/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002173{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002174 return PyLong_FromLong(is_builtin(name));
2175}
2176
2177/*[clinic input]
2178_imp.is_frozen
2179
2180 name: unicode
2181 /
2182
2183Returns True if the module name corresponds to a frozen module.
2184[clinic start generated code]*/
2185
Brett Cannon4caa61d2014-01-09 19:03:32 -05002186static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002187_imp_is_frozen_impl(PyObject *module, PyObject *name)
2188/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002189{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002190 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 p = find_frozen(name);
2193 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002194}
2195
Larry Hastings1df0b352015-08-24 19:53:56 -07002196/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2197static int
2198exec_builtin_or_dynamic(PyObject *mod) {
2199 PyModuleDef *def;
2200 void *state;
2201
2202 if (!PyModule_Check(mod)) {
2203 return 0;
2204 }
2205
2206 def = PyModule_GetDef(mod);
2207 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002208 return 0;
2209 }
Brett Cannon52794db2016-09-07 17:00:43 -07002210
Larry Hastings1df0b352015-08-24 19:53:56 -07002211 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002212 if (state) {
2213 /* Already initialized; skip reload */
2214 return 0;
2215 }
Brett Cannon52794db2016-09-07 17:00:43 -07002216
Larry Hastings1df0b352015-08-24 19:53:56 -07002217 return PyModule_ExecDef(mod, def);
2218}
2219
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002220#ifdef HAVE_DYNAMIC_LOADING
2221
Brett Cannon4caa61d2014-01-09 19:03:32 -05002222/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002223_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002224
Nick Coghland5cacbb2015-05-23 22:24:10 +10002225 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002226 file: object = NULL
2227 /
2228
Nick Coghland5cacbb2015-05-23 22:24:10 +10002229Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002230[clinic start generated code]*/
2231
Brett Cannon4caa61d2014-01-09 19:03:32 -05002232static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002233_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2234/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002235{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002236 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002237 FILE *fp;
2238
Nick Coghland5cacbb2015-05-23 22:24:10 +10002239 name = PyObject_GetAttrString(spec, "name");
2240 if (name == NULL) {
2241 return NULL;
2242 }
2243
2244 path = PyObject_GetAttrString(spec, "origin");
2245 if (path == NULL) {
2246 Py_DECREF(name);
2247 return NULL;
2248 }
2249
2250 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002251 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002252 Py_DECREF(name);
2253 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002254 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002255 return mod;
2256 }
2257
Brett Cannon4caa61d2014-01-09 19:03:32 -05002258 if (file != NULL) {
2259 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002260 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002261 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002262 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002266 else
2267 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002268
2269 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2270
2271 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002272 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (fp)
2274 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002275 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002276}
2277
Nick Coghland5cacbb2015-05-23 22:24:10 +10002278/*[clinic input]
2279_imp.exec_dynamic -> int
2280
2281 mod: object
2282 /
2283
2284Initialize an extension module.
2285[clinic start generated code]*/
2286
2287static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002288_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2289/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002290{
Larry Hastings1df0b352015-08-24 19:53:56 -07002291 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002292}
2293
2294
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002295#endif /* HAVE_DYNAMIC_LOADING */
2296
Larry Hastings7726ac92014-01-31 22:03:12 -08002297/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002298_imp.exec_builtin -> int
2299
2300 mod: object
2301 /
2302
2303Initialize a built-in module.
2304[clinic start generated code]*/
2305
2306static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002307_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2308/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002309{
2310 return exec_builtin_or_dynamic(mod);
2311}
2312
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002313/*[clinic input]
2314_imp.source_hash
2315
2316 key: long
2317 source: Py_buffer
2318[clinic start generated code]*/
2319
2320static PyObject *
2321_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2322/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2323{
Benjamin Peterson83620772017-12-09 12:18:56 -08002324 union {
2325 uint64_t x;
2326 char data[sizeof(uint64_t)];
2327 } hash;
2328 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002329#if !PY_LITTLE_ENDIAN
2330 // Force to little-endian. There really ought to be a succinct standard way
2331 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002332 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2333 char tmp = hash.data[i];
2334 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2335 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002336 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002337#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002338 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002339}
2340
Barry Warsaw28a691b2010-04-17 00:19:56 +00002341
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002342PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002343"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002344
Guido van Rossum79f25d91997-04-29 20:08:16 +00002345static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002346 _IMP_EXTENSION_SUFFIXES_METHODDEF
2347 _IMP_LOCK_HELD_METHODDEF
2348 _IMP_ACQUIRE_LOCK_METHODDEF
2349 _IMP_RELEASE_LOCK_METHODDEF
2350 _IMP_GET_FROZEN_OBJECT_METHODDEF
2351 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002352 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002353 _IMP_INIT_FROZEN_METHODDEF
2354 _IMP_IS_BUILTIN_METHODDEF
2355 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002356 _IMP_CREATE_DYNAMIC_METHODDEF
2357 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002358 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002359 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002360 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002361 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002362};
2363
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002364
Martin v. Löwis1a214512008-06-11 05:26:20 +00002365static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002367 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 doc_imp,
2369 0,
2370 imp_methods,
2371 NULL,
2372 NULL,
2373 NULL,
2374 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002375};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002376
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002377PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002378PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002383 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002385 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002387 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002389 }
2390
Victor Stinner331a6a52019-05-27 16:39:22 +02002391 const wchar_t *mode = _PyInterpreterState_Get()->config.check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002392 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002393 if (pyc_mode == NULL) {
2394 goto failure;
2395 }
2396 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2397 Py_DECREF(pyc_mode);
2398 goto failure;
2399 }
2400 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002403 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 Py_XDECREF(m);
2405 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002406}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002407
2408
Guido van Rossumb18618d2000-05-03 23:44:39 +00002409/* API for embedding applications that want to add their own entries
2410 to the table of built-in modules. This should normally be called
2411 *before* Py_Initialize(). When the table resize fails, -1 is
2412 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002413
2414 After a similar function by Just van Rossum. */
2415
2416int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002417PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002420 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002421 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 /* Count the number of entries in both tables */
2424 for (n = 0; newtab[n].name != NULL; n++)
2425 ;
2426 if (n == 0)
2427 return 0; /* Nothing to do */
2428 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2429 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002430
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002431 /* Force default raw memory allocator to get a known allocator to be able
2432 to release the memory in _PyImport_Fini2() */
2433 PyMemAllocatorEx old_alloc;
2434 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002437 p = NULL;
2438 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002439 size_t size = sizeof(struct _inittab) * (i + n + 1);
2440 p = PyMem_RawRealloc(inittab_copy, size);
2441 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002442 if (p == NULL) {
2443 res = -1;
2444 goto done;
2445 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002446
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002447 /* Copy the tables into the new memory at the first call
2448 to PyImport_ExtendInittab(). */
2449 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002451 }
2452 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2453 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002454
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002455done:
2456 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2457 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002458}
2459
2460/* Shorthand to add a single entry given a name and a function */
2461
2462int
Brett Cannona826f322009-04-02 03:41:46 +00002463PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002468
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002469 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002473}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002474
2475#ifdef __cplusplus
2476}
2477#endif