blob: 495012d1c7da6642c900d2045a65a1941e23376a [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 Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pyhash.h"
8#include "pycore_pylifecycle.h"
9#include "pycore_pymem.h"
10#include "pycore_pystate.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000012#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020014#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020017#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000018
Guido van Rossum55a83382000-09-20 20:31:38 +000019#ifdef HAVE_FCNTL_H
20#include <fcntl.h>
21#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000022#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000023extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000025
Barry Warsaw28a691b2010-04-17 00:19:56 +000026#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000027
Victor Stinner95872862011-03-07 18:20:56 +010028/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000029static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000030
Guido van Rossum771c6c81997-10-31 18:37:24 +000031/* This table is defined in config.c: */
32extern struct _inittab _PyImport_Inittab[];
33
34struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010035static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000036
Brett Cannon4caa61d2014-01-09 19:03:32 -050037/*[clinic input]
38module _imp
39[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030040/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040041
42#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050043
Guido van Rossum1ae940a1995-01-02 19:04:15 +000044/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000045
Victor Stinner331a6a52019-05-27 16:39:22 +020046PyStatus
Victor Stinner672b6ba2017-12-06 17:25:50 +010047_PyImport_Init(PyInterpreterState *interp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000048{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020049 interp->builtins_copy = PyDict_Copy(interp->builtins);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080050 if (interp->builtins_copy == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020051 return _PyStatus_ERR("Can't backup builtins dict");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080052 }
Victor Stinner331a6a52019-05-27 16:39:22 +020053 return _PyStatus_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054}
55
Victor Stinner331a6a52019-05-27 16:39:22 +020056PyStatus
Just van Rossum52e14d62002-12-30 22:08:05 +000057_PyImportHooks_Init(void)
58{
Brett Cannonfd074152012-04-14 14:10:13 -040059 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000061
Brett Cannonfd074152012-04-14 14:10:13 -040062 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 v = PyList_New(0);
64 if (v == NULL)
65 goto error;
66 err = PySys_SetObject("meta_path", v);
67 Py_DECREF(v);
68 if (err)
69 goto error;
70 v = PyDict_New();
71 if (v == NULL)
72 goto error;
73 err = PySys_SetObject("path_importer_cache", v);
74 Py_DECREF(v);
75 if (err)
76 goto error;
77 path_hooks = PyList_New(0);
78 if (path_hooks == NULL)
79 goto error;
80 err = PySys_SetObject("path_hooks", path_hooks);
81 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080082 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 }
Brett Cannonfd074152012-04-14 14:10:13 -040084 Py_DECREF(path_hooks);
Victor Stinner331a6a52019-05-27 16:39:22 +020085 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086
87 error:
88 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +020089 return _PyStatus_ERR("initializing sys.meta_path, sys.path_hooks, "
Victor Stinnerf7e5b562017-11-15 15:48:08 -080090 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040091}
92
Victor Stinner331a6a52019-05-27 16:39:22 +020093PyStatus
Victor Stinner410b85a2019-05-13 17:12:45 +020094_PyImportZip_Init(PyInterpreterState *interp)
Brett Cannonfd074152012-04-14 14:10:13 -040095{
ukwksk5e6312c2018-05-15 04:10:52 +090096 PyObject *path_hooks, *zipimport;
Brett Cannonfd074152012-04-14 14:10:13 -040097 int err = 0;
98
99 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200100 if (path_hooks == NULL) {
101 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400102 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200103 }
Brett Cannonfd074152012-04-14 14:10:13 -0400104
Victor Stinner331a6a52019-05-27 16:39:22 +0200105 int verbose = interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200106 if (verbose) {
Brett Cannonfd074152012-04-14 14:10:13 -0400107 PySys_WriteStderr("# installing zipimport hook\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200108 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109
ukwksk5e6312c2018-05-15 04:10:52 +0900110 zipimport = PyImport_ImportModule("zipimport");
111 if (zipimport == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 PyErr_Clear(); /* No zip import module -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200113 if (verbose) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 PySys_WriteStderr("# can't import zipimport\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 }
117 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200118 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900119 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200120 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900121 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 if (zipimporter == NULL) {
123 PyErr_Clear(); /* No zipimporter object -- okay */
Victor Stinner410b85a2019-05-13 17:12:45 +0200124 if (verbose) {
125 PySys_WriteStderr("# can't import zipimport.zipimporter\n");
126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 }
128 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400129 /* sys.path_hooks.insert(0, zipimporter) */
130 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400132 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400134 }
Victor Stinner410b85a2019-05-13 17:12:45 +0200135 if (verbose) {
136 PySys_WriteStderr("# installed zipimport hook\n");
137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 }
139 }
Brett Cannonfd074152012-04-14 14:10:13 -0400140
Victor Stinner331a6a52019-05-27 16:39:22 +0200141 return _PyStatus_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400142
143 error:
144 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200145 return _PyStatus_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000146}
147
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148/* Locking primitives to prevent parallel imports of the same module
149 in different threads to return with a partially loaded module.
150 These calls are serialized by the global interpreter lock. */
151
Guido van Rossum49b56061998-10-01 20:42:43 +0000152#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153
Guido van Rossum65d5b571998-12-21 19:32:43 +0000154static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200155static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156static int import_lock_level = 0;
157
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000158void
159_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000160{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200161 unsigned long me = PyThread_get_thread_ident();
162 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 return; /* Too bad */
164 if (import_lock == NULL) {
165 import_lock = PyThread_allocate_lock();
166 if (import_lock == NULL)
167 return; /* Nothing much we can do. */
168 }
169 if (import_lock_thread == me) {
170 import_lock_level++;
171 return;
172 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200173 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
174 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 {
176 PyThreadState *tstate = PyEval_SaveThread();
177 PyThread_acquire_lock(import_lock, 1);
178 PyEval_RestoreThread(tstate);
179 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100180 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 import_lock_thread = me;
182 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000183}
184
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000185int
186_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000187{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200188 unsigned long me = PyThread_get_thread_ident();
189 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 return 0; /* Too bad */
191 if (import_lock_thread != me)
192 return -1;
193 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100194 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200196 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 PyThread_release_lock(import_lock);
198 }
199 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000200}
201
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200202/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000203 created child processes do not share locks with the parent.
204 We now acquire the import lock around fork() calls but on some platforms
205 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000206
207void
208_PyImport_ReInitLock(void)
209{
Christian Heimes418fd742015-04-19 21:08:42 +0200210 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200212 if (import_lock == NULL) {
213 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
214 }
215 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000216 if (import_lock_level > 1) {
217 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200218 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500219 /* The following could fail if the lock is already held, but forking as
220 a side-effect of an import is a) rare, b) nuts, and c) difficult to
221 do thanks to the lock only being held when doing individual module
222 locks per import. */
223 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000224 import_lock_thread = me;
225 import_lock_level--;
226 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200227 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000228 import_lock_level = 0;
229 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000230}
231
Brett Cannon4caa61d2014-01-09 19:03:32 -0500232/*[clinic input]
233_imp.lock_held
234
235Return True if the import lock is currently held, else False.
236
237On platforms without threads, return False.
238[clinic start generated code]*/
239
Brett Cannon4caa61d2014-01-09 19:03:32 -0500240static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300241_imp_lock_held_impl(PyObject *module)
242/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000243{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200244 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000245}
246
Brett Cannon4caa61d2014-01-09 19:03:32 -0500247/*[clinic input]
248_imp.acquire_lock
249
250Acquires the interpreter's import lock for the current thread.
251
252This lock should be used by import hooks to ensure thread-safety when importing
253modules. On platforms without threads, this function does nothing.
254[clinic start generated code]*/
255
Brett Cannon4caa61d2014-01-09 19:03:32 -0500256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300257_imp_acquire_lock_impl(PyObject *module)
258/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200261 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000262}
263
Brett Cannon4caa61d2014-01-09 19:03:32 -0500264/*[clinic input]
265_imp.release_lock
266
267Release the interpreter's import lock.
268
269On platforms without threads, this function does nothing.
270[clinic start generated code]*/
271
Brett Cannon4caa61d2014-01-09 19:03:32 -0500272static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300273_imp_release_lock_impl(PyObject *module)
274/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 if (_PyImport_ReleaseLock() < 0) {
277 PyErr_SetString(PyExc_RuntimeError,
278 "not holding the import lock");
279 return NULL;
280 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200281 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000282}
283
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100284void
285_PyImport_Fini(void)
286{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200287 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100288 if (import_lock != NULL) {
289 PyThread_free_lock(import_lock);
290 import_lock = NULL;
291 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100292}
293
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100294void
295_PyImport_Fini2(void)
296{
297 /* Use the same memory allocator than PyImport_ExtendInittab(). */
298 PyMemAllocatorEx old_alloc;
299 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
300
301 /* Free memory allocated by PyImport_ExtendInittab() */
302 PyMem_RawFree(inittab_copy);
303
304 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
305}
306
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307/* Helper for sys */
308
309PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000310PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000311{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200312 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow3f9eee62017-09-15 16:35:20 -0600313 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700314 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600315 }
Eric Snow93c92f72017-09-13 23:46:04 -0700316 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317}
318
Eric Snowd393c1b2017-09-14 12:18:12 -0600319/* In some corner cases it is important to be sure that the import
320 machinery has been initialized (or not cleaned up yet). For
321 example, see issue #4236 and PyModule_Create2(). */
322
323int
324_PyImport_IsInitialized(PyInterpreterState *interp)
325{
326 if (interp->modules == NULL)
327 return 0;
328 return 1;
329}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000330
Eric Snow3f9eee62017-09-15 16:35:20 -0600331PyObject *
332_PyImport_GetModuleId(struct _Py_Identifier *nameid)
333{
334 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
335 if (name == NULL) {
336 return NULL;
337 }
338 return PyImport_GetModule(name);
339}
340
341int
342_PyImport_SetModule(PyObject *name, PyObject *m)
343{
344 PyObject *modules = PyImport_GetModuleDict();
345 return PyObject_SetItem(modules, name, m);
346}
347
348int
349_PyImport_SetModuleString(const char *name, PyObject *m)
350{
351 PyObject *modules = PyImport_GetModuleDict();
352 return PyMapping_SetItemString(modules, name, m);
353}
354
355PyObject *
356PyImport_GetModule(PyObject *name)
357{
358 PyObject *m;
359 PyObject *modules = PyImport_GetModuleDict();
360 if (modules == NULL) {
361 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
362 return NULL;
363 }
364 Py_INCREF(modules);
365 if (PyDict_CheckExact(modules)) {
366 m = PyDict_GetItemWithError(modules, name); /* borrowed */
367 Py_XINCREF(m);
368 }
369 else {
370 m = PyObject_GetItem(modules, name);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300371 if (m == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600372 PyErr_Clear();
373 }
374 }
375 Py_DECREF(modules);
376 return m;
377}
378
379
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000380/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200381static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 "path", "argv", "ps1", "ps2",
383 "last_type", "last_value", "last_traceback",
384 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200385 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000387};
388
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200389static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 "stdin", "__stdin__",
391 "stdout", "__stdout__",
392 "stderr", "__stderr__",
393 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000394};
395
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000396/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397
Guido van Rossum3f5da241990-12-20 15:06:42 +0000398void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000399PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000400{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200401 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 PyObject *key, *value, *dict;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200403 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snowd393c1b2017-09-14 12:18:12 -0600404 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200405 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200406 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (modules == NULL)
409 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* Delete some special variables first. These are common
412 places where user values hide and people complain when their
413 destructors fail. Since the modules containing them are
414 deleted *last* of all, they would come too late in the normal
415 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000416
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200417 /* XXX Perhaps these precautions are obsolete. Who knows? */
418
Victor Stinner331a6a52019-05-27 16:39:22 +0200419 int verbose = interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200420 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200421 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200422 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300423 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300424 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300425 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200426
427 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200428 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200429 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200430 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300431 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300432 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200435 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200436 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200437 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200438 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200439 value = _PyDict_GetItemStringWithError(interp->sysdict, *(p+1));
440 if (value == NULL) {
441 if (PyErr_Occurred()) {
442 PyErr_WriteUnraisable(NULL);
443 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200444 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200445 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300446 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300447 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000450
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200451 /* We prepare a list which will receive (name, weakref) tuples of
452 modules when they are removed from sys.modules. The name is used
453 for diagnosis messages (in verbose mode), while the weakref helps
454 detect those modules which have been held alive. */
455 weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300456 if (weaklist == NULL) {
457 PyErr_WriteUnraisable(NULL);
458 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200459
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200460#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200461 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200462 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300463 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200464 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300465 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300466 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300467 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200468 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300469 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200470 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300471 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300472 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300473 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600475#define CLEAR_MODULE(name, mod) \
476 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200477 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600478 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200479 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600480 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300481 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300482 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300483 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600484 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000485
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200486 /* Remove all modules from sys.modules, hoping that garbage collection
487 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600488 if (PyDict_CheckExact(modules)) {
489 pos = 0;
490 while (PyDict_Next(modules, &pos, &key, &value)) {
491 CLEAR_MODULE(key, value);
492 }
493 }
494 else {
495 PyObject *iterator = PyObject_GetIter(modules);
496 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300497 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600498 }
499 else {
500 while ((key = PyIter_Next(iterator))) {
501 value = PyObject_GetItem(modules, key);
502 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300503 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600504 continue;
505 }
506 CLEAR_MODULE(key, value);
507 Py_DECREF(value);
508 Py_DECREF(key);
509 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300510 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300511 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300512 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600513 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 }
515 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000516
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200517 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600518 if (PyDict_CheckExact(modules)) {
519 PyDict_Clear(modules);
520 }
521 else {
522 _Py_IDENTIFIER(clear);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300523 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
524 PyErr_WriteUnraisable(NULL);
525 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600526 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200527 /* Restore the original builtins dict, to ensure that any
528 user data gets cleared. */
529 dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300530 if (dict == NULL) {
531 PyErr_WriteUnraisable(NULL);
532 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200533 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300534 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200535 PyErr_Clear();
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300536 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200537 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200538 /* Clear module dict copies stored in the interpreter state */
539 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200540 /* Collect references */
541 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200542 /* Dump GC stats before it's too late, since it uses the warnings
543 machinery. */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200544 _PyGC_DumpShutdownStats(&_PyRuntime);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200545
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200546 /* Now, if there are any modules left alive, clear their globals to
547 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200548 up here, since they are kept alive in the interpreter state.
549
550 The special treatment of "builtins" here is because even
551 when it's not referenced as a module, its dictionary is
552 referenced by almost every module's __builtins__. Since
553 deleting a module clears its dictionary (even if there are
554 references left to it), we need to delete the "builtins"
555 module last. Likewise, we don't delete sys until the very
556 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200557 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200558 Py_ssize_t i;
559 /* Since dict is ordered in CPython 3.6+, modules are saved in
560 importing order. First clear modules imported later. */
561 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200562 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200563 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200564 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
565 if (mod == Py_None)
566 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200567 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200568 dict = PyModule_GetDict(mod);
569 if (dict == interp->builtins || dict == interp->sysdict)
570 continue;
571 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200572 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200573 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200574 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200575 _PyModule_Clear(mod);
576 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200577 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200578 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000580
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200581 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200582 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200583 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200584 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200585 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200586 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200587 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200588 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200589 _PyModule_ClearDict(interp->builtins);
590
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200591 /* Clear and delete the modules directory. Actual modules will
592 still be there only if imported during the execution of some
593 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700594 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200596
597 /* Once more */
598 _PyGC_CollectNoFail();
599
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300600#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200601#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000602}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000603
604
Barry Warsaw28a691b2010-04-17 00:19:56 +0000605/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000606
607long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000608PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200610 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200611 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600612 PyObject *external, *pyc_magic;
613
614 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
615 if (external == NULL)
616 return -1;
617 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
618 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400619 if (pyc_magic == NULL)
620 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200621 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700622 Py_DECREF(pyc_magic);
623 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000624}
625
626
Brett Cannon3adc7b72012-07-09 14:22:12 -0400627extern const char * _PySys_ImplCacheTag;
628
Barry Warsaw28a691b2010-04-17 00:19:56 +0000629const char *
630PyImport_GetMagicTag(void)
631{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400632 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000633}
634
Brett Cannon98979b82012-07-02 15:13:11 -0400635
Guido van Rossum25ce5661997-08-02 03:10:38 +0000636/* Magic for extension modules (built-in as well as dynamically
637 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200638 once, we keep a static dictionary 'extensions' keyed by the tuple
639 (module name, module name) (for built-in modules) or by
640 (filename, module name) (for dynamically loaded modules), containing these
641 modules. A copy of the module's dictionary is stored by calling
642 _PyImport_FixupExtensionObject() immediately after the module initialization
643 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100644 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000645
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000646 Modules which do support multiple initialization set their m_size
647 field to a non-negative number (indicating the size of the
648 module-specific state). They are still recorded in the extensions
649 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000650*/
651
652int
Victor Stinner95872862011-03-07 18:20:56 +0100653_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600654 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000655{
Eric Snowd393c1b2017-09-14 12:18:12 -0600656 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500658 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (extensions == NULL) {
660 extensions = PyDict_New();
661 if (extensions == NULL)
662 return -1;
663 }
664 if (mod == NULL || !PyModule_Check(mod)) {
665 PyErr_BadInternalCall();
666 return -1;
667 }
668 def = PyModule_GetDef(mod);
669 if (!def) {
670 PyErr_BadInternalCall();
671 return -1;
672 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600673 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 return -1;
675 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600676 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return -1;
678 }
679 if (def->m_size == -1) {
680 if (def->m_base.m_copy) {
681 /* Somebody already imported the module,
682 likely under a different name.
683 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200684 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
686 dict = PyModule_GetDict(mod);
687 if (dict == NULL)
688 return -1;
689 def->m_base.m_copy = PyDict_Copy(dict);
690 if (def->m_base.m_copy == NULL)
691 return -1;
692 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500693 key = PyTuple_Pack(2, filename, name);
694 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200695 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500696 res = PyDict_SetItem(extensions, key, (PyObject *)def);
697 Py_DECREF(key);
698 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200699 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000701}
702
Victor Stinner49d3f252010-10-17 01:24:53 +0000703int
Eric Snowd393c1b2017-09-14 12:18:12 -0600704_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000705{
706 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100707 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100708 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100709 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000710 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600711 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100712 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000713 return res;
714}
715
Guido van Rossum25ce5661997-08-02 03:10:38 +0000716PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100717_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000718{
Eric Snowd393c1b2017-09-14 12:18:12 -0600719 PyObject *modules = PyImport_GetModuleDict();
720 return _PyImport_FindExtensionObjectEx(name, filename, modules);
721}
722
723PyObject *
724_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
725 PyObject *modules)
726{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500727 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyModuleDef* def;
729 if (extensions == NULL)
730 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500731 key = PyTuple_Pack(2, filename, name);
732 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200733 return NULL;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200734 def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500735 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (def == NULL)
737 return NULL;
738 if (def->m_size == -1) {
739 /* Module does not support repeated initialization */
740 if (def->m_base.m_copy == NULL)
741 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600742 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (mod == NULL)
744 return NULL;
745 mdict = PyModule_GetDict(mod);
746 if (mdict == NULL)
747 return NULL;
748 if (PyDict_Update(mdict, def->m_base.m_copy))
749 return NULL;
750 }
751 else {
752 if (def->m_base.m_init == NULL)
753 return NULL;
754 mod = def->m_base.m_init();
755 if (mod == NULL)
756 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600757 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200758 Py_DECREF(mod);
759 return NULL;
760 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 Py_DECREF(mod);
762 }
763 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600764 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 return NULL;
766 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200767 int verbose = _PyInterpreterState_Get()->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200768 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100769 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200770 name, filename);
771 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000773
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000774}
775
Victor Stinner49d3f252010-10-17 01:24:53 +0000776PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600777_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000778{
Victor Stinner95872862011-03-07 18:20:56 +0100779 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100780 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100781 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000782 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600783 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100784 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000785 return res;
786}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000787
788/* Get the module object corresponding to a module name.
789 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000790 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000791 Because the former action is most common, THIS DOES NOT RETURN A
792 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793
Guido van Rossum79f25d91997-04-29 20:08:16 +0000794PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000795PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600798 return _PyImport_AddModuleObject(name, modules);
799}
800
801PyObject *
802_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
803{
Eric Snow86b7afd2017-09-04 17:54:09 -0600804 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600805 if (PyDict_CheckExact(modules)) {
806 m = PyDict_GetItemWithError(modules, name);
807 }
808 else {
809 m = PyObject_GetItem(modules, name);
810 // For backward-comaptibility we copy the behavior
811 // of PyDict_GetItemWithError().
812 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
813 PyErr_Clear();
814 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200815 }
816 if (PyErr_Occurred()) {
817 return NULL;
818 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600819 if (m != NULL && PyModule_Check(m)) {
820 return m;
821 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000822 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (m == NULL)
824 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600825 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 Py_DECREF(m);
827 return NULL;
828 }
829 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000832}
833
Victor Stinner27ee0892011-03-04 12:57:09 +0000834PyObject *
835PyImport_AddModule(const char *name)
836{
837 PyObject *nameobj, *module;
838 nameobj = PyUnicode_FromString(name);
839 if (nameobj == NULL)
840 return NULL;
841 module = PyImport_AddModuleObject(nameobj);
842 Py_DECREF(nameobj);
843 return module;
844}
845
846
Tim Peters1cd70172004-08-02 03:52:12 +0000847/* Remove name from sys.modules, if it's there. */
848static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000849remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000850{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600851 PyObject *type, *value, *traceback;
852 PyErr_Fetch(&type, &value, &traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyObject *modules = PyImport_GetModuleDict();
Zackery Spytz94a64e92019-05-08 10:31:23 -0600854 if (!PyMapping_HasKey(modules, name)) {
855 goto out;
856 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600857 if (PyMapping_DelItem(modules, name) < 0) {
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200858 Py_FatalError("import: deleting existing key in "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600860 }
Zackery Spytz94a64e92019-05-08 10:31:23 -0600861out:
862 PyErr_Restore(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000863}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000864
Christian Heimes3b06e532008-01-07 20:12:44 +0000865
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000866/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000867 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
868 * removed from sys.modules, to avoid leaving damaged module objects
869 * in sys.modules. The caller may wish to restore the original
870 * module object (if any) in this case; PyImport_ReloadModule is an
871 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000872 *
873 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
874 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000875 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000876PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300877PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 return PyImport_ExecCodeModuleWithPathnames(
880 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000881}
882
883PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300884PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 return PyImport_ExecCodeModuleWithPathnames(
887 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000888}
889
890PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300891PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
892 const char *pathname,
893 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000894{
Victor Stinner27ee0892011-03-04 12:57:09 +0000895 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600896 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000897
898 nameobj = PyUnicode_FromString(name);
899 if (nameobj == NULL)
900 return NULL;
901
Victor Stinner27ee0892011-03-04 12:57:09 +0000902 if (cpathname != NULL) {
903 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
904 if (cpathobj == NULL)
905 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400906 }
907 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000908 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400909
910 if (pathname != NULL) {
911 pathobj = PyUnicode_DecodeFSDefault(pathname);
912 if (pathobj == NULL)
913 goto error;
914 }
915 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200916 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400917 _Py_IDENTIFIER(_get_sourcefile);
918
919 if (interp == NULL) {
920 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
921 "no interpreter!");
922 }
923
Eric Snow32439d62015-05-02 19:15:18 -0600924 external= PyObject_GetAttrString(interp->importlib,
925 "_bootstrap_external");
926 if (external != NULL) {
927 pathobj = _PyObject_CallMethodIdObjArgs(external,
928 &PyId__get_sourcefile, cpathobj,
929 NULL);
930 Py_DECREF(external);
931 }
Brett Cannona6473f92012-07-13 13:57:03 -0400932 if (pathobj == NULL)
933 PyErr_Clear();
934 }
935 else
936 pathobj = NULL;
937
Victor Stinner27ee0892011-03-04 12:57:09 +0000938 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
939error:
940 Py_DECREF(nameobj);
941 Py_XDECREF(pathobj);
942 Py_XDECREF(cpathobj);
943 return m;
944}
945
Brett Cannon18fc4e72014-04-04 10:01:46 -0400946static PyObject *
947module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000948{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200949 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400950 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000951
Victor Stinner27ee0892011-03-04 12:57:09 +0000952 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (m == NULL)
954 return NULL;
955 /* If the module is being reloaded, we get the old module back
956 and re-use its dict to exec the new code. */
957 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200958 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
959 if (PyErr_Occurred() ||
960 _PyDict_SetItemId(d, &PyId___builtins__,
961 PyEval_GetBuiltins()) != 0)
962 {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400963 remove_module(name);
964 return NULL;
965 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400967
Eric Snow08197a42014-05-12 17:54:55 -0600968 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400969}
970
971static PyObject *
972exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
973{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400974 PyObject *v, *m;
975
976 v = PyEval_EvalCode(code_object, module_dict, module_dict);
977 if (v == NULL) {
978 remove_module(name);
979 return NULL;
980 }
981 Py_DECREF(v);
982
Eric Snow3f9eee62017-09-15 16:35:20 -0600983 m = PyImport_GetModule(name);
Stefan Krah027b09c2019-03-25 21:50:58 +0100984 if (m == NULL && !PyErr_Occurred()) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400985 PyErr_Format(PyExc_ImportError,
986 "Loaded module %R not found in sys.modules",
987 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400988 }
989
Brett Cannon18fc4e72014-04-04 10:01:46 -0400990 return m;
991}
992
993PyObject*
994PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
995 PyObject *cpathname)
996{
Eric Snow32439d62015-05-02 19:15:18 -0600997 PyObject *d, *external, *res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200998 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow08197a42014-05-12 17:54:55 -0600999 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001000
1001 d = module_dict_for_exec(name);
1002 if (d == NULL) {
1003 return NULL;
1004 }
1005
Eric Snow08197a42014-05-12 17:54:55 -06001006 if (pathname == NULL) {
1007 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 }
Eric Snow32439d62015-05-02 19:15:18 -06001009 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
1010 if (external == NULL)
1011 return NULL;
1012 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001013 &PyId__fix_up_module,
1014 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001015 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001016 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001017 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -06001018 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 }
Eric Snow08197a42014-05-12 17:54:55 -06001020 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001021}
1022
1023
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001024static void
1025update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 PyObject *constants, *tmp;
1028 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (PyUnicode_Compare(co->co_filename, oldname))
1031 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001032
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001033 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001034 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 constants = co->co_consts;
1037 n = PyTuple_GET_SIZE(constants);
1038 for (i = 0; i < n; i++) {
1039 tmp = PyTuple_GET_ITEM(constants, i);
1040 if (PyCode_Check(tmp))
1041 update_code_filenames((PyCodeObject *)tmp,
1042 oldname, newname);
1043 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001044}
1045
Victor Stinner2f42ae52011-03-20 00:41:24 +01001046static void
1047update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001048{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001049 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001050
Victor Stinner2f42ae52011-03-20 00:41:24 +01001051 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1052 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 oldname = co->co_filename;
1055 Py_INCREF(oldname);
1056 update_code_filenames(co, oldname, newname);
1057 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001058}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001059
Brett Cannon4caa61d2014-01-09 19:03:32 -05001060/*[clinic input]
1061_imp._fix_co_filename
1062
1063 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1064 Code object to change.
1065
1066 path: unicode
1067 File path to use.
1068 /
1069
1070Changes code.co_filename to specify the passed-in file path.
1071[clinic start generated code]*/
1072
Brett Cannon4caa61d2014-01-09 19:03:32 -05001073static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001074_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001075 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001076/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001077
Brett Cannon4caa61d2014-01-09 19:03:32 -05001078{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001079 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001080
1081 Py_RETURN_NONE;
1082}
1083
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001084
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001085/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001086static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001087
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001088
1089/* Helper to test for built-in module */
1090
1091static int
Victor Stinner95872862011-03-07 18:20:56 +01001092is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001093{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001094 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001096 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (PyImport_Inittab[i].initfunc == NULL)
1098 return -1;
1099 else
1100 return 1;
1101 }
1102 }
1103 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001104}
1105
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001106
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001107/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001108 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001109 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001110 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001111 this tells our caller that the path based finder could not find
1112 a finder for this path item. Cache the result in
1113 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001114 Returns a borrowed reference. */
1115
1116static PyObject *
1117get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyObject *importer;
1121 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* These conditions are the caller's responsibility: */
1124 assert(PyList_Check(path_hooks));
1125 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 nhooks = PyList_Size(path_hooks);
1128 if (nhooks < 0)
1129 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001130
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001131 importer = PyDict_GetItemWithError(path_importer_cache, p);
1132 if (importer != NULL || PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 /* set path_importer_cache[p] to None to avoid recursion */
1136 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1137 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 for (j = 0; j < nhooks; j++) {
1140 PyObject *hook = PyList_GetItem(path_hooks, j);
1141 if (hook == NULL)
1142 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001143 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (importer != NULL)
1145 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1148 return NULL;
1149 }
1150 PyErr_Clear();
1151 }
1152 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001153 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 }
1155 if (importer != NULL) {
1156 int err = PyDict_SetItem(path_importer_cache, p, importer);
1157 Py_DECREF(importer);
1158 if (err != 0)
1159 return NULL;
1160 }
1161 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001162}
1163
Benjamin Petersone5024512018-09-12 12:06:42 -07001164PyObject *
Christian Heimes9cd17752007-11-18 19:35:23 +00001165PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001167
Victor Stinner1e53bba2013-07-16 22:26:05 +02001168 path_importer_cache = PySys_GetObject("path_importer_cache");
1169 path_hooks = PySys_GetObject("path_hooks");
1170 if (path_importer_cache != NULL && path_hooks != NULL) {
1171 importer = get_path_importer(path_importer_cache,
1172 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 }
1174 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1175 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001176}
1177
Nick Coghland5cacbb2015-05-23 22:24:10 +10001178/*[clinic input]
1179_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001180
Nick Coghland5cacbb2015-05-23 22:24:10 +10001181 spec: object
1182 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001183
Nick Coghland5cacbb2015-05-23 22:24:10 +10001184Create an extension module.
1185[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001186
Nick Coghland5cacbb2015-05-23 22:24:10 +10001187static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001188_imp_create_builtin(PyObject *module, PyObject *spec)
1189/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001192 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001193 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001194 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001195
Nick Coghland5cacbb2015-05-23 22:24:10 +10001196 name = PyObject_GetAttrString(spec, "name");
1197 if (name == NULL) {
1198 return NULL;
1199 }
1200
Victor Stinner5eb4f592013-11-14 22:38:52 +01001201 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001202 if (mod || PyErr_Occurred()) {
1203 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001204 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001205 return mod;
1206 }
1207
1208 namestr = PyUnicode_AsUTF8(name);
1209 if (namestr == NULL) {
1210 Py_DECREF(name);
1211 return NULL;
1212 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001213
Eric Snowd393c1b2017-09-14 12:18:12 -06001214 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001216 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001217 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001219 /* Cannot re-init internal module ("sys" or "builtins") */
1220 mod = PyImport_AddModule(namestr);
1221 Py_DECREF(name);
1222 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001225 if (mod == NULL) {
1226 Py_DECREF(name);
1227 return NULL;
1228 }
1229 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1230 Py_DECREF(name);
1231 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1232 } else {
1233 /* Remember pointer to module init function. */
1234 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001235 if (def == NULL) {
1236 Py_DECREF(name);
1237 return NULL;
1238 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001239 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001240 if (modules == NULL) {
1241 modules = PyImport_GetModuleDict();
1242 }
1243 if (_PyImport_FixupExtensionObject(mod, name, name,
1244 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001245 Py_DECREF(name);
1246 return NULL;
1247 }
1248 Py_DECREF(name);
1249 return mod;
1250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 }
1252 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001253 Py_DECREF(name);
1254 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001255}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001256
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001257
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001258/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001259
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001260static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001261find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001262{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001263 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001264
Victor Stinner53dc7352011-03-20 01:50:21 +01001265 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 for (p = PyImport_FrozenModules; ; p++) {
1269 if (p->name == NULL)
1270 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001271 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 break;
1273 }
1274 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001275}
1276
Guido van Rossum79f25d91997-04-29 20:08:16 +00001277static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001278get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001279{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001280 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (p == NULL) {
1284 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001285 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 name);
1287 return NULL;
1288 }
1289 if (p->code == NULL) {
1290 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001291 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 name);
1293 return NULL;
1294 }
1295 size = p->size;
1296 if (size < 0)
1297 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001298 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001299}
1300
Brett Cannon8d110132009-03-15 02:20:16 +00001301static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001302is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001303{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001304 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (p == NULL) {
1308 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001309 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 name);
1311 return NULL;
1312 }
Brett Cannon8d110132009-03-15 02:20:16 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (size < 0)
1317 Py_RETURN_TRUE;
1318 else
1319 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001320}
1321
1322
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001323/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001324 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001325 an exception set if the initialization failed.
1326 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001327
1328int
Victor Stinner53dc7352011-03-20 01:50:21 +01001329PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001330{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001331 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001332 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 int ispackage;
1334 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001335
Victor Stinner53dc7352011-03-20 01:50:21 +01001336 p = find_frozen(name);
1337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 if (p == NULL)
1339 return 0;
1340 if (p->code == NULL) {
1341 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001342 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 name);
1344 return -1;
1345 }
1346 size = p->size;
1347 ispackage = (size < 0);
1348 if (ispackage)
1349 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001350 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (co == NULL)
1352 return -1;
1353 if (!PyCode_Check(co)) {
1354 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001355 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 name);
1357 goto err_return;
1358 }
1359 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001360 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001361 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001363 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 if (m == NULL)
1365 goto err_return;
1366 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001367 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 goto err_return;
1370 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 err = PyDict_SetItemString(d, "__path__", l);
1372 Py_DECREF(l);
1373 if (err != 0)
1374 goto err_return;
1375 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001376 d = module_dict_for_exec(name);
1377 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001378 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001379 }
1380 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (m == NULL)
1382 goto err_return;
1383 Py_DECREF(co);
1384 Py_DECREF(m);
1385 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001386err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 Py_DECREF(co);
1388 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001389}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001390
Victor Stinner53dc7352011-03-20 01:50:21 +01001391int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001392PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001393{
1394 PyObject *nameobj;
1395 int ret;
1396 nameobj = PyUnicode_InternFromString(name);
1397 if (nameobj == NULL)
1398 return -1;
1399 ret = PyImport_ImportFrozenModuleObject(nameobj);
1400 Py_DECREF(nameobj);
1401 return ret;
1402}
1403
Guido van Rossum74e6a111994-08-29 12:54:38 +00001404
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001405/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001406 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001407
Guido van Rossum79f25d91997-04-29 20:08:16 +00001408PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001409PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 PyObject *pname;
1412 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 pname = PyUnicode_FromString(name);
1415 if (pname == NULL)
1416 return NULL;
1417 result = PyImport_Import(pname);
1418 Py_DECREF(pname);
1419 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001420}
1421
Christian Heimes072c0f12008-01-03 23:01:04 +00001422/* Import a module without blocking
1423 *
1424 * At first it tries to fetch the module from sys.modules. If the module was
1425 * never loaded before it loads it with PyImport_ImportModule() unless another
1426 * thread holds the import lock. In the latter case the function raises an
1427 * ImportError instead of blocking.
1428 *
1429 * Returns the module object with incremented ref count.
1430 */
1431PyObject *
1432PyImport_ImportModuleNoBlock(const char *name)
1433{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001434 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001435}
1436
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001437
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001438/* Remove importlib frames from the traceback,
1439 * except in Verbose mode. */
1440static void
Victor Stinner410b85a2019-05-13 17:12:45 +02001441remove_importlib_frames(PyInterpreterState *interp)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001442{
1443 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001444 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001445 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001446 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001447 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001448 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001449 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001450
1451 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001452 from the traceback. We always trim chunks
1453 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001454
1455 PyErr_Fetch(&exception, &value, &base_tb);
Victor Stinner331a6a52019-05-27 16:39:22 +02001456 if (!exception || interp->config.verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001457 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001458 }
1459
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001460 if (PyType_IsSubtype((PyTypeObject *) exception,
1461 (PyTypeObject *) PyExc_ImportError))
1462 always_trim = 1;
1463
1464 prev_link = &base_tb;
1465 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001466 while (tb != NULL) {
1467 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1468 PyObject *next = (PyObject *) traceback->tb_next;
1469 PyFrameObject *frame = traceback->tb_frame;
1470 PyCodeObject *code = frame->f_code;
1471 int now_in_importlib;
1472
1473 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001474 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1475 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001476 if (now_in_importlib && !in_importlib) {
1477 /* This is the link to this chunk of importlib tracebacks */
1478 outer_link = prev_link;
1479 }
1480 in_importlib = now_in_importlib;
1481
1482 if (in_importlib &&
1483 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001484 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001485 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001486 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001487 prev_link = outer_link;
1488 }
1489 else {
1490 prev_link = (PyObject **) &traceback->tb_next;
1491 }
1492 tb = next;
1493 }
1494done:
1495 PyErr_Restore(exception, value, base_tb);
1496}
1497
1498
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001499static PyObject *
1500resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001501{
Eric Snowb523f842013-11-22 09:05:39 -07001502 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001503 _Py_IDENTIFIER(__package__);
1504 _Py_IDENTIFIER(__path__);
1505 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001506 _Py_IDENTIFIER(parent);
1507 PyObject *abs_name;
1508 PyObject *package = NULL;
1509 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001510 Py_ssize_t last_dot;
1511 PyObject *base;
1512 int level_up;
1513
1514 if (globals == NULL) {
1515 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1516 goto error;
1517 }
1518 if (!PyDict_Check(globals)) {
1519 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1520 goto error;
1521 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001522 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001523 if (package == Py_None) {
1524 package = NULL;
1525 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001526 else if (package == NULL && PyErr_Occurred()) {
1527 goto error;
1528 }
1529 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
1530 if (spec == NULL && PyErr_Occurred()) {
1531 goto error;
1532 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001533
1534 if (package != NULL) {
1535 Py_INCREF(package);
1536 if (!PyUnicode_Check(package)) {
1537 PyErr_SetString(PyExc_TypeError, "package must be a string");
1538 goto error;
1539 }
1540 else if (spec != NULL && spec != Py_None) {
1541 int equal;
1542 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1543 if (parent == NULL) {
1544 goto error;
1545 }
1546
1547 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1548 Py_DECREF(parent);
1549 if (equal < 0) {
1550 goto error;
1551 }
1552 else if (equal == 0) {
1553 if (PyErr_WarnEx(PyExc_ImportWarning,
1554 "__package__ != __spec__.parent", 1) < 0) {
1555 goto error;
1556 }
1557 }
1558 }
1559 }
1560 else if (spec != NULL && spec != Py_None) {
1561 package = _PyObject_GetAttrId(spec, &PyId_parent);
1562 if (package == NULL) {
1563 goto error;
1564 }
1565 else if (!PyUnicode_Check(package)) {
1566 PyErr_SetString(PyExc_TypeError,
1567 "__spec__.parent must be a string");
1568 goto error;
1569 }
1570 }
1571 else {
1572 if (PyErr_WarnEx(PyExc_ImportWarning,
1573 "can't resolve package from __spec__ or __package__, "
1574 "falling back on __name__ and __path__", 1) < 0) {
1575 goto error;
1576 }
1577
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001578 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001579 if (package == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001580 if (!PyErr_Occurred()) {
1581 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1582 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001583 goto error;
1584 }
1585
1586 Py_INCREF(package);
1587 if (!PyUnicode_Check(package)) {
1588 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1589 goto error;
1590 }
1591
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001592 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001593 Py_ssize_t dot;
1594
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001595 if (PyErr_Occurred() || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001596 goto error;
1597 }
1598
1599 dot = PyUnicode_FindChar(package, '.',
1600 0, PyUnicode_GET_LENGTH(package), -1);
1601 if (dot == -2) {
1602 goto error;
1603 }
Brett Cannon0a6693a2019-09-11 12:38:22 +01001604 else if (dot == -1) {
1605 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001606 }
Brett Cannon0a6693a2019-09-11 12:38:22 +01001607 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1608 if (substr == NULL) {
1609 goto error;
1610 }
1611 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001612 }
1613 }
1614
1615 last_dot = PyUnicode_GET_LENGTH(package);
1616 if (last_dot == 0) {
Brett Cannon0a6693a2019-09-11 12:38:22 +01001617 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001618 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001619
1620 for (level_up = 1; level_up < level; level_up += 1) {
1621 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1622 if (last_dot == -2) {
1623 goto error;
1624 }
1625 else if (last_dot == -1) {
1626 PyErr_SetString(PyExc_ValueError,
1627 "attempted relative import beyond top-level "
1628 "package");
1629 goto error;
1630 }
1631 }
1632
1633 base = PyUnicode_Substring(package, 0, last_dot);
1634 Py_DECREF(package);
1635 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1636 return base;
1637 }
1638
1639 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1640 Py_DECREF(base);
1641 return abs_name;
1642
Brett Cannon0a6693a2019-09-11 12:38:22 +01001643 no_parent_error:
1644 PyErr_SetString(PyExc_ImportError,
1645 "attempted relative import "
1646 "with no known parent package");
1647
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001648 error:
1649 Py_XDECREF(package);
1650 return NULL;
1651}
1652
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001653static PyObject *
1654import_find_and_load(PyObject *abs_name)
1655{
1656 _Py_IDENTIFIER(_find_and_load);
1657 PyObject *mod = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001658 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +02001659 int import_time = interp->config.import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001660 static int import_level;
1661 static _PyTime_t accumulated;
1662
1663 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1664
Steve Dowerb82e17e2019-05-23 08:45:22 -07001665 PyObject *sys_path = PySys_GetObject("path");
1666 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1667 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1668 if (PySys_Audit("import", "OOOOO",
1669 abs_name, Py_None, sys_path ? sys_path : Py_None,
1670 sys_meta_path ? sys_meta_path : Py_None,
1671 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1672 return NULL;
1673 }
1674
1675
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001676 /* XOptions is initialized after first some imports.
1677 * So we can't have negative cache before completed initialization.
1678 * Anyway, importlib._find_and_load is much slower than
1679 * _PyDict_GetItemIdWithError().
1680 */
1681 if (import_time) {
1682 static int header = 1;
1683 if (header) {
1684 fputs("import time: self [us] | cumulative | imported package\n",
1685 stderr);
1686 header = 0;
1687 }
1688
1689 import_level++;
1690 t1 = _PyTime_GetPerfCounter();
1691 accumulated = 0;
1692 }
1693
1694 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1695 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1696
1697 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1698 &PyId__find_and_load, abs_name,
1699 interp->import_func, NULL);
1700
1701 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1702 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1703 mod != NULL);
1704
1705 if (import_time) {
1706 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1707
1708 import_level--;
1709 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1710 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1711 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1712 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1713
1714 accumulated = accumulated_copy + cum;
1715 }
1716
1717 return mod;
1718}
1719
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001720PyObject *
1721PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1722 PyObject *locals, PyObject *fromlist,
1723 int level)
1724{
Brett Cannonfd074152012-04-14 14:10:13 -04001725 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001726 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001727 PyObject *final_mod = NULL;
1728 PyObject *mod = NULL;
1729 PyObject *package = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001730 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001731 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001732
Brett Cannonfd074152012-04-14 14:10:13 -04001733 if (name == NULL) {
1734 PyErr_SetString(PyExc_ValueError, "Empty module name");
1735 goto error;
1736 }
1737
1738 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1739 for added performance. */
1740
1741 if (!PyUnicode_Check(name)) {
1742 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1743 goto error;
1744 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001745 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001746 goto error;
1747 }
1748 if (level < 0) {
1749 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1750 goto error;
1751 }
Brett Cannon849113a2016-01-22 15:25:50 -08001752
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001753 if (level > 0) {
1754 abs_name = resolve_name(name, globals, level);
1755 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001756 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001757 }
1758 else { /* level == 0 */
1759 if (PyUnicode_GET_LENGTH(name) == 0) {
1760 PyErr_SetString(PyExc_ValueError, "Empty module name");
1761 goto error;
1762 }
Brett Cannonfd074152012-04-14 14:10:13 -04001763 abs_name = name;
1764 Py_INCREF(abs_name);
1765 }
1766
Eric Snow3f9eee62017-09-15 16:35:20 -06001767 mod = PyImport_GetModule(abs_name);
Stefan Krah027b09c2019-03-25 21:50:58 +01001768 if (mod == NULL && PyErr_Occurred()) {
1769 goto error;
1770 }
1771
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001772 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001773 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001774 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001775 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001776
Antoine Pitrou03989852012-08-28 00:24:52 +02001777 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001778 __spec__._initializing is true.
1779 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001780 stuffing the new module in sys.modules.
1781 */
Eric Snowb523f842013-11-22 09:05:39 -07001782 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001783 if (_PyModuleSpec_IsInitializing(spec)) {
1784 PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1785 &PyId__lock_unlock_module, abs_name,
1786 NULL);
1787 if (value == NULL) {
1788 Py_DECREF(spec);
1789 goto error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001790 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001791 Py_DECREF(value);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001792 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001793 Py_XDECREF(spec);
Brett Cannonfd074152012-04-14 14:10:13 -04001794 }
1795 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001796 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001797 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001798 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001799 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001800 }
1801 }
1802
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001803 has_from = 0;
1804 if (fromlist != NULL && fromlist != Py_None) {
1805 has_from = PyObject_IsTrue(fromlist);
1806 if (has_from < 0)
1807 goto error;
1808 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001809 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001810 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1811 if (level == 0 || len > 0) {
1812 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001813
Victor Stinner744c34e2016-05-20 11:36:13 +02001814 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1815 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001816 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001817 }
1818
Victor Stinner744c34e2016-05-20 11:36:13 +02001819 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001820 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001821 final_mod = mod;
1822 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001823 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001824 }
1825
Brett Cannonfd074152012-04-14 14:10:13 -04001826 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001827 PyObject *front = PyUnicode_Substring(name, 0, dot);
1828 if (front == NULL) {
1829 goto error;
1830 }
1831
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001832 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001833 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001834 }
1835 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001836 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001837 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001838 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001839 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001840 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001841 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001842 }
Brett Cannonfd074152012-04-14 14:10:13 -04001843
Eric Snow3f9eee62017-09-15 16:35:20 -06001844 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001845 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001846 if (final_mod == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001847 if (!PyErr_Occurred()) {
1848 PyErr_Format(PyExc_KeyError,
1849 "%R not in sys.modules as expected",
1850 to_return);
1851 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001852 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001853 }
Brett Cannonfd074152012-04-14 14:10:13 -04001854 }
1855 }
1856 else {
1857 final_mod = mod;
1858 Py_INCREF(mod);
1859 }
1860 }
1861 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001862 _Py_IDENTIFIER(__path__);
1863 PyObject *path;
1864 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1865 goto error;
1866 }
1867 if (path) {
1868 Py_DECREF(path);
1869 final_mod = _PyObject_CallMethodIdObjArgs(
1870 interp->importlib, &PyId__handle_fromlist,
1871 mod, fromlist, interp->import_func, NULL);
1872 }
1873 else {
1874 final_mod = mod;
1875 Py_INCREF(mod);
1876 }
Brett Cannonfd074152012-04-14 14:10:13 -04001877 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001878
Brett Cannonfd074152012-04-14 14:10:13 -04001879 error:
1880 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001881 Py_XDECREF(mod);
1882 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001883 if (final_mod == NULL) {
1884 remove_importlib_frames(interp);
1885 }
Brett Cannonfd074152012-04-14 14:10:13 -04001886 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001887}
1888
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001889PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001890PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001891 PyObject *fromlist, int level)
1892{
1893 PyObject *nameobj, *mod;
1894 nameobj = PyUnicode_FromString(name);
1895 if (nameobj == NULL)
1896 return NULL;
1897 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1898 fromlist, level);
1899 Py_DECREF(nameobj);
1900 return mod;
1901}
1902
1903
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001904/* Re-import a module of any kind and return its module object, WITH
1905 INCREMENTED REFERENCE COUNT */
1906
Guido van Rossum79f25d91997-04-29 20:08:16 +00001907PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001908PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001909{
Eric Snow3f9eee62017-09-15 16:35:20 -06001910 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001911 _Py_IDENTIFIER(reload);
1912 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001913 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001914 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001915 if (PyErr_Occurred()) {
1916 return NULL;
1917 }
1918
Brett Cannon62228db2012-04-29 14:38:11 -04001919 imp = PyImport_ImportModule("imp");
1920 if (imp == NULL) {
1921 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001924
Victor Stinner55ba38a2016-12-09 16:09:30 +01001925 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001926 Py_DECREF(imp);
1927 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001928}
1929
1930
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001931/* Higher-level import emulator which emulates the "import" statement
1932 more accurately -- it invokes the __import__() function from the
1933 builtins of the current globals. This means that the import is
1934 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001935 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001936 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001937 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001938 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001939
1940PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001941PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 static PyObject *silly_list = NULL;
1944 static PyObject *builtins_str = NULL;
1945 static PyObject *import_str = NULL;
1946 PyObject *globals = NULL;
1947 PyObject *import = NULL;
1948 PyObject *builtins = NULL;
1949 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 /* Initialize constant string objects */
1952 if (silly_list == NULL) {
1953 import_str = PyUnicode_InternFromString("__import__");
1954 if (import_str == NULL)
1955 return NULL;
1956 builtins_str = PyUnicode_InternFromString("__builtins__");
1957 if (builtins_str == NULL)
1958 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001959 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (silly_list == NULL)
1961 return NULL;
1962 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* Get the builtins from current globals */
1965 globals = PyEval_GetGlobals();
1966 if (globals != NULL) {
1967 Py_INCREF(globals);
1968 builtins = PyObject_GetItem(globals, builtins_str);
1969 if (builtins == NULL)
1970 goto err;
1971 }
1972 else {
1973 /* No globals -- use standard builtins, and fake globals */
1974 builtins = PyImport_ImportModuleLevel("builtins",
1975 NULL, NULL, NULL, 0);
1976 if (builtins == NULL)
1977 return NULL;
1978 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1979 if (globals == NULL)
1980 goto err;
1981 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 /* Get the __import__ function from the builtins */
1984 if (PyDict_Check(builtins)) {
1985 import = PyObject_GetItem(builtins, import_str);
1986 if (import == NULL)
1987 PyErr_SetObject(PyExc_KeyError, import_str);
1988 }
1989 else
1990 import = PyObject_GetAttr(builtins, import_str);
1991 if (import == NULL)
1992 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001995 Always use absolute import here.
1996 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1998 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001999 if (r == NULL)
2000 goto err;
2001 Py_DECREF(r);
2002
Eric Snow3f9eee62017-09-15 16:35:20 -06002003 r = PyImport_GetModule(module_name);
2004 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002005 PyErr_SetObject(PyExc_KeyError, module_name);
2006 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002007
2008 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 Py_XDECREF(globals);
2010 Py_XDECREF(builtins);
2011 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002014}
2015
Brett Cannon4caa61d2014-01-09 19:03:32 -05002016/*[clinic input]
2017_imp.extension_suffixes
2018
2019Returns the list of file suffixes used to identify extension modules.
2020[clinic start generated code]*/
2021
Brett Cannon4caa61d2014-01-09 19:03:32 -05002022static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002023_imp_extension_suffixes_impl(PyObject *module)
2024/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 list = PyList_New(0);
2029 if (list == NULL)
2030 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002031#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002032 const char *suffix;
2033 unsigned int index = 0;
2034
Brett Cannon2657df42012-05-04 15:20:40 -04002035 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2036 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (item == NULL) {
2038 Py_DECREF(list);
2039 return NULL;
2040 }
2041 if (PyList_Append(list, item) < 0) {
2042 Py_DECREF(list);
2043 Py_DECREF(item);
2044 return NULL;
2045 }
2046 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002047 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 }
Brett Cannon2657df42012-05-04 15:20:40 -04002049#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002051}
2052
Brett Cannon4caa61d2014-01-09 19:03:32 -05002053/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002054_imp.init_frozen
2055
2056 name: unicode
2057 /
2058
2059Initializes a frozen module.
2060[clinic start generated code]*/
2061
Brett Cannon4caa61d2014-01-09 19:03:32 -05002062static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002063_imp_init_frozen_impl(PyObject *module, PyObject *name)
2064/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 int ret;
2067 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002068
Victor Stinner53dc7352011-03-20 01:50:21 +01002069 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (ret < 0)
2071 return NULL;
2072 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002073 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002075 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 Py_XINCREF(m);
2077 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002078}
2079
Brett Cannon4caa61d2014-01-09 19:03:32 -05002080/*[clinic input]
2081_imp.get_frozen_object
2082
2083 name: unicode
2084 /
2085
2086Create a code object for a frozen module.
2087[clinic start generated code]*/
2088
Brett Cannon4caa61d2014-01-09 19:03:32 -05002089static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002090_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2091/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002094}
2095
Brett Cannon4caa61d2014-01-09 19:03:32 -05002096/*[clinic input]
2097_imp.is_frozen_package
2098
2099 name: unicode
2100 /
2101
2102Returns True if the module name is of a frozen package.
2103[clinic start generated code]*/
2104
Brett Cannon4caa61d2014-01-09 19:03:32 -05002105static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002106_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2107/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002110}
2111
Brett Cannon4caa61d2014-01-09 19:03:32 -05002112/*[clinic input]
2113_imp.is_builtin
2114
2115 name: unicode
2116 /
2117
2118Returns True if the module name corresponds to a built-in module.
2119[clinic start generated code]*/
2120
Guido van Rossum79f25d91997-04-29 20:08:16 +00002121static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002122_imp_is_builtin_impl(PyObject *module, PyObject *name)
2123/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002124{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002125 return PyLong_FromLong(is_builtin(name));
2126}
2127
2128/*[clinic input]
2129_imp.is_frozen
2130
2131 name: unicode
2132 /
2133
2134Returns True if the module name corresponds to a frozen module.
2135[clinic start generated code]*/
2136
Brett Cannon4caa61d2014-01-09 19:03:32 -05002137static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002138_imp_is_frozen_impl(PyObject *module, PyObject *name)
2139/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002140{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002141 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 p = find_frozen(name);
2144 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002145}
2146
Larry Hastings1df0b352015-08-24 19:53:56 -07002147/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2148static int
2149exec_builtin_or_dynamic(PyObject *mod) {
2150 PyModuleDef *def;
2151 void *state;
2152
2153 if (!PyModule_Check(mod)) {
2154 return 0;
2155 }
2156
2157 def = PyModule_GetDef(mod);
2158 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002159 return 0;
2160 }
Brett Cannon52794db2016-09-07 17:00:43 -07002161
Larry Hastings1df0b352015-08-24 19:53:56 -07002162 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002163 if (state) {
2164 /* Already initialized; skip reload */
2165 return 0;
2166 }
Brett Cannon52794db2016-09-07 17:00:43 -07002167
Larry Hastings1df0b352015-08-24 19:53:56 -07002168 return PyModule_ExecDef(mod, def);
2169}
2170
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002171#ifdef HAVE_DYNAMIC_LOADING
2172
Brett Cannon4caa61d2014-01-09 19:03:32 -05002173/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002174_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002175
Nick Coghland5cacbb2015-05-23 22:24:10 +10002176 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002177 file: object = NULL
2178 /
2179
Nick Coghland5cacbb2015-05-23 22:24:10 +10002180Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002181[clinic start generated code]*/
2182
Brett Cannon4caa61d2014-01-09 19:03:32 -05002183static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002184_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2185/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002186{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002187 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002188 FILE *fp;
2189
Nick Coghland5cacbb2015-05-23 22:24:10 +10002190 name = PyObject_GetAttrString(spec, "name");
2191 if (name == NULL) {
2192 return NULL;
2193 }
2194
2195 path = PyObject_GetAttrString(spec, "origin");
2196 if (path == NULL) {
2197 Py_DECREF(name);
2198 return NULL;
2199 }
2200
2201 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002202 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002203 Py_DECREF(name);
2204 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002205 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002206 return mod;
2207 }
2208
Brett Cannon4caa61d2014-01-09 19:03:32 -05002209 if (file != NULL) {
2210 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002211 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002212 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002213 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002215 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002217 else
2218 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002219
2220 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2221
2222 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002223 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (fp)
2225 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002226 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002227}
2228
Nick Coghland5cacbb2015-05-23 22:24:10 +10002229/*[clinic input]
2230_imp.exec_dynamic -> int
2231
2232 mod: object
2233 /
2234
2235Initialize an extension module.
2236[clinic start generated code]*/
2237
2238static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002239_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2240/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002241{
Larry Hastings1df0b352015-08-24 19:53:56 -07002242 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002243}
2244
2245
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002246#endif /* HAVE_DYNAMIC_LOADING */
2247
Larry Hastings7726ac92014-01-31 22:03:12 -08002248/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002249_imp.exec_builtin -> int
2250
2251 mod: object
2252 /
2253
2254Initialize a built-in module.
2255[clinic start generated code]*/
2256
2257static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002258_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2259/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002260{
2261 return exec_builtin_or_dynamic(mod);
2262}
2263
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002264/*[clinic input]
2265_imp.source_hash
2266
2267 key: long
2268 source: Py_buffer
2269[clinic start generated code]*/
2270
2271static PyObject *
2272_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2273/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2274{
Benjamin Peterson83620772017-12-09 12:18:56 -08002275 union {
2276 uint64_t x;
2277 char data[sizeof(uint64_t)];
2278 } hash;
2279 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002280#if !PY_LITTLE_ENDIAN
2281 // Force to little-endian. There really ought to be a succinct standard way
2282 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002283 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2284 char tmp = hash.data[i];
2285 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2286 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002287 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002288#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002289 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002290}
2291
Barry Warsaw28a691b2010-04-17 00:19:56 +00002292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002293PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002294"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002295
Guido van Rossum79f25d91997-04-29 20:08:16 +00002296static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002297 _IMP_EXTENSION_SUFFIXES_METHODDEF
2298 _IMP_LOCK_HELD_METHODDEF
2299 _IMP_ACQUIRE_LOCK_METHODDEF
2300 _IMP_RELEASE_LOCK_METHODDEF
2301 _IMP_GET_FROZEN_OBJECT_METHODDEF
2302 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002303 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002304 _IMP_INIT_FROZEN_METHODDEF
2305 _IMP_IS_BUILTIN_METHODDEF
2306 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002307 _IMP_CREATE_DYNAMIC_METHODDEF
2308 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002309 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002310 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002311 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002312 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002313};
2314
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002315
Martin v. Löwis1a214512008-06-11 05:26:20 +00002316static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002318 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 doc_imp,
2320 0,
2321 imp_methods,
2322 NULL,
2323 NULL,
2324 NULL,
2325 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002326};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002327
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002328PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002329PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002334 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002338 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002340 }
2341
Victor Stinner331a6a52019-05-27 16:39:22 +02002342 const wchar_t *mode = _PyInterpreterState_Get()->config.check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002343 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002344 if (pyc_mode == NULL) {
2345 goto failure;
2346 }
2347 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2348 Py_DECREF(pyc_mode);
2349 goto failure;
2350 }
2351 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002354 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 Py_XDECREF(m);
2356 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002357}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002358
2359
Guido van Rossumb18618d2000-05-03 23:44:39 +00002360/* API for embedding applications that want to add their own entries
2361 to the table of built-in modules. This should normally be called
2362 *before* Py_Initialize(). When the table resize fails, -1 is
2363 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002364
2365 After a similar function by Just van Rossum. */
2366
2367int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002368PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002371 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002372 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* Count the number of entries in both tables */
2375 for (n = 0; newtab[n].name != NULL; n++)
2376 ;
2377 if (n == 0)
2378 return 0; /* Nothing to do */
2379 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2380 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002381
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002382 /* Force default raw memory allocator to get a known allocator to be able
2383 to release the memory in _PyImport_Fini2() */
2384 PyMemAllocatorEx old_alloc;
2385 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002388 p = NULL;
2389 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002390 size_t size = sizeof(struct _inittab) * (i + n + 1);
2391 p = PyMem_RawRealloc(inittab_copy, size);
2392 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002393 if (p == NULL) {
2394 res = -1;
2395 goto done;
2396 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002397
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002398 /* Copy the tables into the new memory at the first call
2399 to PyImport_ExtendInittab(). */
2400 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002402 }
2403 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2404 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002405
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002406done:
2407 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2408 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002409}
2410
2411/* Shorthand to add a single entry given a name and a function */
2412
2413int
Brett Cannona826f322009-04-02 03:41:46 +00002414PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002419
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002420 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002424}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002425
2426#ifdef __cplusplus
2427}
2428#endif