blob: 3937fbe37d94179b2a11aef7c08683f0e1777763 [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);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300542 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
543 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);
836 // For backward-comaptibility we copy the behavior
837 // 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) {
965 pathobj = _PyObject_CallMethodIdObjArgs(external,
966 &PyId__get_sourcefile, cpathobj,
967 NULL);
968 Py_DECREF(external);
969 }
Brett Cannona6473f92012-07-13 13:57:03 -0400970 if (pathobj == NULL)
971 PyErr_Clear();
972 }
973 else
974 pathobj = NULL;
975
Victor Stinner27ee0892011-03-04 12:57:09 +0000976 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
977error:
978 Py_DECREF(nameobj);
979 Py_XDECREF(pathobj);
980 Py_XDECREF(cpathobj);
981 return m;
982}
983
Brett Cannon18fc4e72014-04-04 10:01:46 -0400984static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200985module_dict_for_exec(PyThreadState *tstate, PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000986{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200987 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400988 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000989
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200990 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (m == NULL)
992 return NULL;
993 /* If the module is being reloaded, we get the old module back
994 and re-use its dict to exec the new code. */
995 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200996 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200997 if (_PyErr_Occurred(tstate) ||
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200998 _PyDict_SetItemId(d, &PyId___builtins__,
999 PyEval_GetBuiltins()) != 0)
1000 {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001001 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001002 return NULL;
1003 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001005
Eric Snow08197a42014-05-12 17:54:55 -06001006 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001007}
1008
1009static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001010exec_code_in_module(PyThreadState *tstate, PyObject *name,
1011 PyObject *module_dict, PyObject *code_object)
Brett Cannon18fc4e72014-04-04 10:01:46 -04001012{
Brett Cannon18fc4e72014-04-04 10:01:46 -04001013 PyObject *v, *m;
1014
1015 v = PyEval_EvalCode(code_object, module_dict, module_dict);
1016 if (v == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001017 remove_module(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001018 return NULL;
1019 }
1020 Py_DECREF(v);
1021
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001022 m = import_get_module(tstate, name);
1023 if (m == NULL && !_PyErr_Occurred(tstate)) {
1024 _PyErr_Format(tstate, PyExc_ImportError,
1025 "Loaded module %R not found in sys.modules",
1026 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001027 }
1028
Brett Cannon18fc4e72014-04-04 10:01:46 -04001029 return m;
1030}
1031
1032PyObject*
1033PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1034 PyObject *cpathname)
1035{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001036 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow32439d62015-05-02 19:15:18 -06001037 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -06001038 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001039
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001040 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001041 if (d == NULL) {
1042 return NULL;
1043 }
1044
Eric Snow08197a42014-05-12 17:54:55 -06001045 if (pathname == NULL) {
1046 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001048 external = PyObject_GetAttrString(tstate->interp->importlib,
1049 "_bootstrap_external");
Eric Snow32439d62015-05-02 19:15:18 -06001050 if (external == NULL)
1051 return NULL;
1052 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001053 &PyId__fix_up_module,
1054 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001055 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001056 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001057 Py_DECREF(res);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001058 res = exec_code_in_module(tstate, name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 }
Eric Snow08197a42014-05-12 17:54:55 -06001060 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001061}
1062
1063
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001064static void
1065update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyObject *constants, *tmp;
1068 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (PyUnicode_Compare(co->co_filename, oldname))
1071 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001072
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001073 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001074 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 constants = co->co_consts;
1077 n = PyTuple_GET_SIZE(constants);
1078 for (i = 0; i < n; i++) {
1079 tmp = PyTuple_GET_ITEM(constants, i);
1080 if (PyCode_Check(tmp))
1081 update_code_filenames((PyCodeObject *)tmp,
1082 oldname, newname);
1083 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001084}
1085
Victor Stinner2f42ae52011-03-20 00:41:24 +01001086static void
1087update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001088{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001089 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001090
Victor Stinner2f42ae52011-03-20 00:41:24 +01001091 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1092 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 oldname = co->co_filename;
1095 Py_INCREF(oldname);
1096 update_code_filenames(co, oldname, newname);
1097 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001098}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001099
Brett Cannon4caa61d2014-01-09 19:03:32 -05001100/*[clinic input]
1101_imp._fix_co_filename
1102
1103 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1104 Code object to change.
1105
1106 path: unicode
1107 File path to use.
1108 /
1109
1110Changes code.co_filename to specify the passed-in file path.
1111[clinic start generated code]*/
1112
Brett Cannon4caa61d2014-01-09 19:03:32 -05001113static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001114_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001115 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001116/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001117
Brett Cannon4caa61d2014-01-09 19:03:32 -05001118{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001119 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001120
1121 Py_RETURN_NONE;
1122}
1123
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001124
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001125/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001126static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001127
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001128
1129/* Helper to test for built-in module */
1130
1131static int
Victor Stinner95872862011-03-07 18:20:56 +01001132is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001133{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001134 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001136 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (PyImport_Inittab[i].initfunc == NULL)
1138 return -1;
1139 else
1140 return 1;
1141 }
1142 }
1143 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001144}
1145
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001146
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001147/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001148 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001149 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001150 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001151 this tells our caller that the path based finder could not find
1152 a finder for this path item. Cache the result in
1153 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001154 Returns a borrowed reference. */
1155
1156static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001157get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
1158 PyObject *path_hooks, PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 PyObject *importer;
1161 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 /* These conditions are the caller's responsibility: */
1164 assert(PyList_Check(path_hooks));
1165 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 nhooks = PyList_Size(path_hooks);
1168 if (nhooks < 0)
1169 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001170
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001171 importer = PyDict_GetItemWithError(path_importer_cache, p);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001172 if (importer != NULL || _PyErr_Occurred(tstate))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 /* set path_importer_cache[p] to None to avoid recursion */
1176 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1177 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 for (j = 0; j < nhooks; j++) {
1180 PyObject *hook = PyList_GetItem(path_hooks, j);
1181 if (hook == NULL)
1182 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001183 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (importer != NULL)
1185 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001186
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001187 if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return NULL;
1189 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001190 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 }
1192 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001193 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 }
1195 if (importer != NULL) {
1196 int err = PyDict_SetItem(path_importer_cache, p, importer);
1197 Py_DECREF(importer);
1198 if (err != 0)
1199 return NULL;
1200 }
1201 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001202}
1203
Benjamin Petersone5024512018-09-12 12:06:42 -07001204PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001205PyImport_GetImporter(PyObject *path)
1206{
1207 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001209
Victor Stinner1e53bba2013-07-16 22:26:05 +02001210 path_importer_cache = PySys_GetObject("path_importer_cache");
1211 path_hooks = PySys_GetObject("path_hooks");
1212 if (path_importer_cache != NULL && path_hooks != NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001213 importer = get_path_importer(tstate, path_importer_cache,
Victor Stinner1e53bba2013-07-16 22:26:05 +02001214 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
1216 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1217 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001218}
1219
Nick Coghland5cacbb2015-05-23 22:24:10 +10001220/*[clinic input]
1221_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001222
Nick Coghland5cacbb2015-05-23 22:24:10 +10001223 spec: object
1224 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001225
Nick Coghland5cacbb2015-05-23 22:24:10 +10001226Create an extension module.
1227[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001228
Nick Coghland5cacbb2015-05-23 22:24:10 +10001229static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001230_imp_create_builtin(PyObject *module, PyObject *spec)
1231/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001232{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001233 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001235 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001236 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001237 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001238
Nick Coghland5cacbb2015-05-23 22:24:10 +10001239 name = PyObject_GetAttrString(spec, "name");
1240 if (name == NULL) {
1241 return NULL;
1242 }
1243
Victor Stinner5eb4f592013-11-14 22:38:52 +01001244 mod = _PyImport_FindExtensionObject(name, name);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001245 if (mod || _PyErr_Occurred(tstate)) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001246 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001247 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001248 return mod;
1249 }
1250
1251 namestr = PyUnicode_AsUTF8(name);
1252 if (namestr == NULL) {
1253 Py_DECREF(name);
1254 return NULL;
1255 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001256
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001257 PyObject *modules = tstate->interp->modules;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001259 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001260 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001262 /* Cannot re-init internal module ("sys" or "builtins") */
1263 mod = PyImport_AddModule(namestr);
1264 Py_DECREF(name);
1265 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001268 if (mod == NULL) {
1269 Py_DECREF(name);
1270 return NULL;
1271 }
1272 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1273 Py_DECREF(name);
1274 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1275 } else {
1276 /* Remember pointer to module init function. */
1277 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001278 if (def == NULL) {
1279 Py_DECREF(name);
1280 return NULL;
1281 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001282 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001283 if (_PyImport_FixupExtensionObject(mod, name, name,
1284 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001285 Py_DECREF(name);
1286 return NULL;
1287 }
1288 Py_DECREF(name);
1289 return mod;
1290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 }
1292 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001293 Py_DECREF(name);
1294 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001295}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001296
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001297
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001298/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001299
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001300static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001301find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001302{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001303 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001304
Victor Stinner53dc7352011-03-20 01:50:21 +01001305 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 for (p = PyImport_FrozenModules; ; p++) {
1309 if (p->name == NULL)
1310 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001311 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 break;
1313 }
1314 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001315}
1316
Guido van Rossum79f25d91997-04-29 20:08:16 +00001317static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001318get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001319{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001320 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (p == NULL) {
1324 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001325 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 name);
1327 return NULL;
1328 }
1329 if (p->code == NULL) {
1330 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001331 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 name);
1333 return NULL;
1334 }
1335 size = p->size;
1336 if (size < 0)
1337 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001338 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001339}
1340
Brett Cannon8d110132009-03-15 02:20:16 +00001341static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001342is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001343{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001344 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (p == NULL) {
1348 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001349 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 name);
1351 return NULL;
1352 }
Brett Cannon8d110132009-03-15 02:20:16 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 if (size < 0)
1357 Py_RETURN_TRUE;
1358 else
1359 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001360}
1361
1362
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001363/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001364 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001365 an exception set if the initialization failed.
1366 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001367
1368int
Victor Stinner53dc7352011-03-20 01:50:21 +01001369PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001370{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001371 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001372 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001373 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 int ispackage;
1375 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001376
Victor Stinner53dc7352011-03-20 01:50:21 +01001377 p = find_frozen(name);
1378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (p == NULL)
1380 return 0;
1381 if (p->code == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001382 _PyErr_Format(tstate, PyExc_ImportError,
1383 "Excluded frozen object named %R",
1384 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 return -1;
1386 }
1387 size = p->size;
1388 ispackage = (size < 0);
1389 if (ispackage)
1390 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001391 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (co == NULL)
1393 return -1;
1394 if (!PyCode_Check(co)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001395 _PyErr_Format(tstate, PyExc_TypeError,
1396 "frozen object %R is not a code object",
1397 name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 goto err_return;
1399 }
1400 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001401 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001402 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 int err;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001404 m = import_add_module(tstate, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (m == NULL)
1406 goto err_return;
1407 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001408 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 goto err_return;
1411 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 err = PyDict_SetItemString(d, "__path__", l);
1413 Py_DECREF(l);
1414 if (err != 0)
1415 goto err_return;
1416 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001417 d = module_dict_for_exec(tstate, name);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001418 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001419 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001420 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001421 m = exec_code_in_module(tstate, name, d, co);
1422 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 goto err_return;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 Py_DECREF(co);
1426 Py_DECREF(m);
1427 return 1;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001428
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001429err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 Py_DECREF(co);
1431 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001432}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001433
Victor Stinner53dc7352011-03-20 01:50:21 +01001434int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001435PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001436{
1437 PyObject *nameobj;
1438 int ret;
1439 nameobj = PyUnicode_InternFromString(name);
1440 if (nameobj == NULL)
1441 return -1;
1442 ret = PyImport_ImportFrozenModuleObject(nameobj);
1443 Py_DECREF(nameobj);
1444 return ret;
1445}
1446
Guido van Rossum74e6a111994-08-29 12:54:38 +00001447
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001448/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001449 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001450
Guido van Rossum79f25d91997-04-29 20:08:16 +00001451PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001452PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyObject *pname;
1455 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 pname = PyUnicode_FromString(name);
1458 if (pname == NULL)
1459 return NULL;
1460 result = PyImport_Import(pname);
1461 Py_DECREF(pname);
1462 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001463}
1464
Christian Heimes072c0f12008-01-03 23:01:04 +00001465/* Import a module without blocking
1466 *
1467 * At first it tries to fetch the module from sys.modules. If the module was
1468 * never loaded before it loads it with PyImport_ImportModule() unless another
1469 * thread holds the import lock. In the latter case the function raises an
1470 * ImportError instead of blocking.
1471 *
1472 * Returns the module object with incremented ref count.
1473 */
1474PyObject *
1475PyImport_ImportModuleNoBlock(const char *name)
1476{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001477 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001478}
1479
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001480
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001481/* Remove importlib frames from the traceback,
1482 * except in Verbose mode. */
1483static void
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001484remove_importlib_frames(PyThreadState *tstate)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001485{
1486 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001487 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001488 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001489 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001490 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001491 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001492 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001493
1494 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001495 from the traceback. We always trim chunks
1496 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001497
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001498 _PyErr_Fetch(tstate, &exception, &value, &base_tb);
1499 if (!exception || tstate->interp->config.verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001500 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001501 }
1502
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001503 if (PyType_IsSubtype((PyTypeObject *) exception,
1504 (PyTypeObject *) PyExc_ImportError))
1505 always_trim = 1;
1506
1507 prev_link = &base_tb;
1508 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001509 while (tb != NULL) {
1510 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1511 PyObject *next = (PyObject *) traceback->tb_next;
1512 PyFrameObject *frame = traceback->tb_frame;
1513 PyCodeObject *code = frame->f_code;
1514 int now_in_importlib;
1515
1516 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001517 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1518 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001519 if (now_in_importlib && !in_importlib) {
1520 /* This is the link to this chunk of importlib tracebacks */
1521 outer_link = prev_link;
1522 }
1523 in_importlib = now_in_importlib;
1524
1525 if (in_importlib &&
1526 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001527 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001528 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001529 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001530 prev_link = outer_link;
1531 }
1532 else {
1533 prev_link = (PyObject **) &traceback->tb_next;
1534 }
1535 tb = next;
1536 }
1537done:
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001538 _PyErr_Restore(tstate, exception, value, base_tb);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001539}
1540
1541
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001542static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001543resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001544{
Eric Snowb523f842013-11-22 09:05:39 -07001545 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001546 _Py_IDENTIFIER(__package__);
1547 _Py_IDENTIFIER(__path__);
1548 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001549 _Py_IDENTIFIER(parent);
1550 PyObject *abs_name;
1551 PyObject *package = NULL;
1552 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001553 Py_ssize_t last_dot;
1554 PyObject *base;
1555 int level_up;
1556
1557 if (globals == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001558 _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001559 goto error;
1560 }
1561 if (!PyDict_Check(globals)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001562 _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001563 goto error;
1564 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001565 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001566 if (package == Py_None) {
1567 package = NULL;
1568 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001569 else if (package == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001570 goto error;
1571 }
1572 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001573 if (spec == NULL && _PyErr_Occurred(tstate)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001574 goto error;
1575 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001576
1577 if (package != NULL) {
1578 Py_INCREF(package);
1579 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001580 _PyErr_SetString(tstate, PyExc_TypeError,
1581 "package must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001582 goto error;
1583 }
1584 else if (spec != NULL && spec != Py_None) {
1585 int equal;
1586 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1587 if (parent == NULL) {
1588 goto error;
1589 }
1590
1591 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1592 Py_DECREF(parent);
1593 if (equal < 0) {
1594 goto error;
1595 }
1596 else if (equal == 0) {
1597 if (PyErr_WarnEx(PyExc_ImportWarning,
1598 "__package__ != __spec__.parent", 1) < 0) {
1599 goto error;
1600 }
1601 }
1602 }
1603 }
1604 else if (spec != NULL && spec != Py_None) {
1605 package = _PyObject_GetAttrId(spec, &PyId_parent);
1606 if (package == NULL) {
1607 goto error;
1608 }
1609 else if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001610 _PyErr_SetString(tstate, PyExc_TypeError,
1611 "__spec__.parent must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001612 goto error;
1613 }
1614 }
1615 else {
1616 if (PyErr_WarnEx(PyExc_ImportWarning,
1617 "can't resolve package from __spec__ or __package__, "
1618 "falling back on __name__ and __path__", 1) < 0) {
1619 goto error;
1620 }
1621
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001622 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001623 if (package == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001624 if (!_PyErr_Occurred(tstate)) {
1625 _PyErr_SetString(tstate, PyExc_KeyError,
1626 "'__name__' not in globals");
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001627 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001628 goto error;
1629 }
1630
1631 Py_INCREF(package);
1632 if (!PyUnicode_Check(package)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001633 _PyErr_SetString(tstate, PyExc_TypeError,
1634 "__name__ must be a string");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001635 goto error;
1636 }
1637
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001638 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001639 Py_ssize_t dot;
1640
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001641 if (_PyErr_Occurred(tstate) || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001642 goto error;
1643 }
1644
1645 dot = PyUnicode_FindChar(package, '.',
1646 0, PyUnicode_GET_LENGTH(package), -1);
1647 if (dot == -2) {
1648 goto error;
1649 }
1650
1651 if (dot >= 0) {
1652 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1653 if (substr == NULL) {
1654 goto error;
1655 }
1656 Py_SETREF(package, substr);
1657 }
1658 }
1659 }
1660
1661 last_dot = PyUnicode_GET_LENGTH(package);
1662 if (last_dot == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001663 _PyErr_SetString(tstate, PyExc_ImportError,
1664 "attempted relative import "
1665 "with no known parent package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001666 goto error;
1667 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001668
1669 for (level_up = 1; level_up < level; level_up += 1) {
1670 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1671 if (last_dot == -2) {
1672 goto error;
1673 }
1674 else if (last_dot == -1) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001675 _PyErr_SetString(tstate, PyExc_ValueError,
1676 "attempted relative import beyond top-level "
1677 "package");
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001678 goto error;
1679 }
1680 }
1681
1682 base = PyUnicode_Substring(package, 0, last_dot);
1683 Py_DECREF(package);
1684 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1685 return base;
1686 }
1687
1688 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1689 Py_DECREF(base);
1690 return abs_name;
1691
1692 error:
1693 Py_XDECREF(package);
1694 return NULL;
1695}
1696
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001697static PyObject *
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001698import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001699{
1700 _Py_IDENTIFIER(_find_and_load);
1701 PyObject *mod = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001702 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +02001703 int import_time = interp->config.import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001704 static int import_level;
1705 static _PyTime_t accumulated;
1706
1707 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1708
Steve Dowerb82e17e2019-05-23 08:45:22 -07001709 PyObject *sys_path = PySys_GetObject("path");
1710 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1711 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1712 if (PySys_Audit("import", "OOOOO",
1713 abs_name, Py_None, sys_path ? sys_path : Py_None,
1714 sys_meta_path ? sys_meta_path : Py_None,
1715 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1716 return NULL;
1717 }
1718
1719
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001720 /* XOptions is initialized after first some imports.
1721 * So we can't have negative cache before completed initialization.
1722 * Anyway, importlib._find_and_load is much slower than
1723 * _PyDict_GetItemIdWithError().
1724 */
1725 if (import_time) {
1726 static int header = 1;
1727 if (header) {
1728 fputs("import time: self [us] | cumulative | imported package\n",
1729 stderr);
1730 header = 0;
1731 }
1732
1733 import_level++;
1734 t1 = _PyTime_GetPerfCounter();
1735 accumulated = 0;
1736 }
1737
1738 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1739 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1740
1741 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1742 &PyId__find_and_load, abs_name,
1743 interp->import_func, NULL);
1744
1745 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1746 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1747 mod != NULL);
1748
1749 if (import_time) {
1750 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1751
1752 import_level--;
1753 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1754 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1755 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1756 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1757
1758 accumulated = accumulated_copy + cum;
1759 }
1760
1761 return mod;
1762}
1763
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001764PyObject *
1765PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1766 PyObject *locals, PyObject *fromlist,
1767 int level)
1768{
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001769 PyThreadState *tstate = _PyThreadState_GET();
Brett Cannonfd074152012-04-14 14:10:13 -04001770 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001771 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001772 PyObject *final_mod = NULL;
1773 PyObject *mod = NULL;
1774 PyObject *package = NULL;
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001775 PyInterpreterState *interp = tstate->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001776 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001777
Brett Cannonfd074152012-04-14 14:10:13 -04001778 if (name == NULL) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001779 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001780 goto error;
1781 }
1782
1783 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1784 for added performance. */
1785
1786 if (!PyUnicode_Check(name)) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001787 _PyErr_SetString(tstate, PyExc_TypeError,
1788 "module name must be a string");
Brett Cannonfd074152012-04-14 14:10:13 -04001789 goto error;
1790 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001791 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001792 goto error;
1793 }
1794 if (level < 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001795 _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
Brett Cannonfd074152012-04-14 14:10:13 -04001796 goto error;
1797 }
Brett Cannon849113a2016-01-22 15:25:50 -08001798
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001799 if (level > 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001800 abs_name = resolve_name(tstate, name, globals, level);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001801 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001802 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001803 }
1804 else { /* level == 0 */
1805 if (PyUnicode_GET_LENGTH(name) == 0) {
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001806 _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
Brett Cannonfd074152012-04-14 14:10:13 -04001807 goto error;
1808 }
Brett Cannonfd074152012-04-14 14:10:13 -04001809 abs_name = name;
1810 Py_INCREF(abs_name);
1811 }
1812
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001813 mod = import_get_module(tstate, abs_name);
1814 if (mod == NULL && _PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001815 goto error;
1816 }
1817
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001818 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001819 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001820 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001821 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001822
Antoine Pitrou03989852012-08-28 00:24:52 +02001823 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001824 __spec__._initializing is true.
1825 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001826 stuffing the new module in sys.modules.
1827 */
Eric Snowb523f842013-11-22 09:05:39 -07001828 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001829 if (_PyModuleSpec_IsInitializing(spec)) {
1830 PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1831 &PyId__lock_unlock_module, abs_name,
1832 NULL);
1833 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
Victor Stinner55ba38a2016-12-09 16:09:30 +01001971 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
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