blob: b4074d1dfc3fab586990d353c638ee4c2cb5e034 [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);
Miss Islington (bot)1205afb2020-05-01 16:06:23 -0700303 inittab_copy = NULL;
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100304
305 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
306}
307
Guido van Rossum25ce5661997-08-02 03:10:38 +0000308/* Helper for sys */
309
310PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000311PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000312{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200313 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow3f9eee62017-09-15 16:35:20 -0600314 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700315 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600316 }
Eric Snow93c92f72017-09-13 23:46:04 -0700317 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318}
319
Eric Snowd393c1b2017-09-14 12:18:12 -0600320/* In some corner cases it is important to be sure that the import
321 machinery has been initialized (or not cleaned up yet). For
322 example, see issue #4236 and PyModule_Create2(). */
323
324int
325_PyImport_IsInitialized(PyInterpreterState *interp)
326{
327 if (interp->modules == NULL)
328 return 0;
329 return 1;
330}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000331
Eric Snow3f9eee62017-09-15 16:35:20 -0600332PyObject *
333_PyImport_GetModuleId(struct _Py_Identifier *nameid)
334{
335 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
336 if (name == NULL) {
337 return NULL;
338 }
339 return PyImport_GetModule(name);
340}
341
342int
343_PyImport_SetModule(PyObject *name, PyObject *m)
344{
345 PyObject *modules = PyImport_GetModuleDict();
346 return PyObject_SetItem(modules, name, m);
347}
348
349int
350_PyImport_SetModuleString(const char *name, PyObject *m)
351{
352 PyObject *modules = PyImport_GetModuleDict();
353 return PyMapping_SetItemString(modules, name, m);
354}
355
356PyObject *
357PyImport_GetModule(PyObject *name)
358{
359 PyObject *m;
360 PyObject *modules = PyImport_GetModuleDict();
361 if (modules == NULL) {
362 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
363 return NULL;
364 }
365 Py_INCREF(modules);
366 if (PyDict_CheckExact(modules)) {
367 m = PyDict_GetItemWithError(modules, name); /* borrowed */
368 Py_XINCREF(m);
369 }
370 else {
371 m = PyObject_GetItem(modules, name);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300372 if (m == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600373 PyErr_Clear();
374 }
375 }
376 Py_DECREF(modules);
377 return m;
378}
379
380
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000381/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200382static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 "path", "argv", "ps1", "ps2",
384 "last_type", "last_value", "last_traceback",
385 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200386 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000388};
389
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200390static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 "stdin", "__stdin__",
392 "stdout", "__stdout__",
393 "stderr", "__stderr__",
394 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000395};
396
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000397/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000398
Guido van Rossum3f5da241990-12-20 15:06:42 +0000399void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000400PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000401{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200402 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyObject *key, *value, *dict;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200404 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snowd393c1b2017-09-14 12:18:12 -0600405 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200406 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200407 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (modules == NULL)
410 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 /* Delete some special variables first. These are common
413 places where user values hide and people complain when their
414 destructors fail. Since the modules containing them are
415 deleted *last* of all, they would come too late in the normal
416 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000417
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200418 /* XXX Perhaps these precautions are obsolete. Who knows? */
419
Victor Stinner331a6a52019-05-27 16:39:22 +0200420 int verbose = interp->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200421 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200422 PySys_WriteStderr("# clear builtins._\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200423 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300424 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300425 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300426 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200427
428 for (p = sys_deletes; *p != NULL; p++) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200429 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200430 PySys_WriteStderr("# clear sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200431 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300432 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300433 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200436 for (p = sys_files; *p != NULL; p+=2) {
Victor Stinner410b85a2019-05-13 17:12:45 +0200437 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200438 PySys_WriteStderr("# restore sys.%s\n", *p);
Victor Stinner410b85a2019-05-13 17:12:45 +0200439 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200440 value = _PyDict_GetItemStringWithError(interp->sysdict, *(p+1));
441 if (value == NULL) {
442 if (PyErr_Occurred()) {
443 PyErr_WriteUnraisable(NULL);
444 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200445 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200446 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300447 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300448 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000451
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200452 /* We prepare a list which will receive (name, weakref) tuples of
453 modules when they are removed from sys.modules. The name is used
454 for diagnosis messages (in verbose mode), while the weakref helps
455 detect those modules which have been held alive. */
456 weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300457 if (weaklist == NULL) {
458 PyErr_WriteUnraisable(NULL);
459 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200460
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200461#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200462 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200463 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300464 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200465 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300466 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300467 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300468 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200469 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300470 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200471 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300472 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300473 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300474 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600476#define CLEAR_MODULE(name, mod) \
477 if (PyModule_Check(mod)) { \
Victor Stinner410b85a2019-05-13 17:12:45 +0200478 if (verbose && PyUnicode_Check(name)) { \
Eric Snow3f9eee62017-09-15 16:35:20 -0600479 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
Victor Stinner410b85a2019-05-13 17:12:45 +0200480 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600481 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300482 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300483 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300484 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600485 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000486
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200487 /* Remove all modules from sys.modules, hoping that garbage collection
488 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600489 if (PyDict_CheckExact(modules)) {
490 pos = 0;
491 while (PyDict_Next(modules, &pos, &key, &value)) {
492 CLEAR_MODULE(key, value);
493 }
494 }
495 else {
496 PyObject *iterator = PyObject_GetIter(modules);
497 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300498 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600499 }
500 else {
501 while ((key = PyIter_Next(iterator))) {
502 value = PyObject_GetItem(modules, key);
503 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300504 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600505 continue;
506 }
507 CLEAR_MODULE(key, value);
508 Py_DECREF(value);
509 Py_DECREF(key);
510 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300511 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300512 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300513 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600514 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 }
516 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000517
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200518 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600519 if (PyDict_CheckExact(modules)) {
520 PyDict_Clear(modules);
521 }
522 else {
523 _Py_IDENTIFIER(clear);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300524 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
525 PyErr_WriteUnraisable(NULL);
526 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600527 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200528 /* Restore the original builtins dict, to ensure that any
529 user data gets cleared. */
530 dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300531 if (dict == NULL) {
532 PyErr_WriteUnraisable(NULL);
533 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200534 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300535 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200536 PyErr_Clear();
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300537 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200538 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200539 /* Clear module dict copies stored in the interpreter state */
540 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200541 /* Collect references */
542 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200543 /* Dump GC stats before it's too late, since it uses the warnings
544 machinery. */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200545 _PyGC_DumpShutdownStats(&_PyRuntime);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200546
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200547 /* Now, if there are any modules left alive, clear their globals to
548 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200549 up here, since they are kept alive in the interpreter state.
550
551 The special treatment of "builtins" here is because even
552 when it's not referenced as a module, its dictionary is
553 referenced by almost every module's __builtins__. Since
554 deleting a module clears its dictionary (even if there are
555 references left to it), we need to delete the "builtins"
556 module last. Likewise, we don't delete sys until the very
557 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200558 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200559 Py_ssize_t i;
560 /* Since dict is ordered in CPython 3.6+, modules are saved in
561 importing order. First clear modules imported later. */
562 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200563 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200564 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200565 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
566 if (mod == Py_None)
567 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200568 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200569 dict = PyModule_GetDict(mod);
570 if (dict == interp->builtins || dict == interp->sysdict)
571 continue;
572 Py_INCREF(mod);
Victor Stinner410b85a2019-05-13 17:12:45 +0200573 if (verbose && PyUnicode_Check(name)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200574 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Victor Stinner410b85a2019-05-13 17:12:45 +0200575 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200576 _PyModule_Clear(mod);
577 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200578 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200579 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000581
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200582 /* Next, delete sys and builtins (in that order) */
Victor Stinner410b85a2019-05-13 17:12:45 +0200583 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200584 PySys_FormatStderr("# cleanup[3] wiping sys\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200585 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200586 _PyModule_ClearDict(interp->sysdict);
Victor Stinner410b85a2019-05-13 17:12:45 +0200587 if (verbose) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200588 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
Victor Stinner410b85a2019-05-13 17:12:45 +0200589 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200590 _PyModule_ClearDict(interp->builtins);
591
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200592 /* Clear and delete the modules directory. Actual modules will
593 still be there only if imported during the execution of some
594 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700595 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200597
598 /* Once more */
599 _PyGC_CollectNoFail();
600
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300601#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200602#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000603}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000604
605
Barry Warsaw28a691b2010-04-17 00:19:56 +0000606/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000607
608long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000609PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200611 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200612 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600613 PyObject *external, *pyc_magic;
614
615 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
616 if (external == NULL)
617 return -1;
618 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
619 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400620 if (pyc_magic == NULL)
621 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200622 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700623 Py_DECREF(pyc_magic);
624 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000625}
626
627
Brett Cannon3adc7b72012-07-09 14:22:12 -0400628extern const char * _PySys_ImplCacheTag;
629
Barry Warsaw28a691b2010-04-17 00:19:56 +0000630const char *
631PyImport_GetMagicTag(void)
632{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400633 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000634}
635
Brett Cannon98979b82012-07-02 15:13:11 -0400636
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637/* Magic for extension modules (built-in as well as dynamically
638 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200639 once, we keep a static dictionary 'extensions' keyed by the tuple
640 (module name, module name) (for built-in modules) or by
641 (filename, module name) (for dynamically loaded modules), containing these
642 modules. A copy of the module's dictionary is stored by calling
643 _PyImport_FixupExtensionObject() immediately after the module initialization
644 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100645 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000646
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000647 Modules which do support multiple initialization set their m_size
648 field to a non-negative number (indicating the size of the
649 module-specific state). They are still recorded in the extensions
650 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000651*/
652
653int
Victor Stinner95872862011-03-07 18:20:56 +0100654_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600655 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656{
Eric Snowd393c1b2017-09-14 12:18:12 -0600657 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500659 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (extensions == NULL) {
661 extensions = PyDict_New();
662 if (extensions == NULL)
663 return -1;
664 }
665 if (mod == NULL || !PyModule_Check(mod)) {
666 PyErr_BadInternalCall();
667 return -1;
668 }
669 def = PyModule_GetDef(mod);
670 if (!def) {
671 PyErr_BadInternalCall();
672 return -1;
673 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600674 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return -1;
676 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600677 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 return -1;
679 }
680 if (def->m_size == -1) {
681 if (def->m_base.m_copy) {
682 /* Somebody already imported the module,
683 likely under a different name.
684 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200685 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 }
687 dict = PyModule_GetDict(mod);
688 if (dict == NULL)
689 return -1;
690 def->m_base.m_copy = PyDict_Copy(dict);
691 if (def->m_base.m_copy == NULL)
692 return -1;
693 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500694 key = PyTuple_Pack(2, filename, name);
695 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200696 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500697 res = PyDict_SetItem(extensions, key, (PyObject *)def);
698 Py_DECREF(key);
699 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200700 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000702}
703
Victor Stinner49d3f252010-10-17 01:24:53 +0000704int
Eric Snowd393c1b2017-09-14 12:18:12 -0600705_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000706{
707 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100708 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100709 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100710 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000711 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600712 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100713 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000714 return res;
715}
716
Guido van Rossum25ce5661997-08-02 03:10:38 +0000717PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100718_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000719{
Eric Snowd393c1b2017-09-14 12:18:12 -0600720 PyObject *modules = PyImport_GetModuleDict();
721 return _PyImport_FindExtensionObjectEx(name, filename, modules);
722}
723
724PyObject *
725_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
726 PyObject *modules)
727{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500728 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyModuleDef* def;
730 if (extensions == NULL)
731 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500732 key = PyTuple_Pack(2, filename, name);
733 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200734 return NULL;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200735 def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500736 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 if (def == NULL)
738 return NULL;
739 if (def->m_size == -1) {
740 /* Module does not support repeated initialization */
741 if (def->m_base.m_copy == NULL)
742 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600743 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (mod == NULL)
745 return NULL;
746 mdict = PyModule_GetDict(mod);
747 if (mdict == NULL)
748 return NULL;
749 if (PyDict_Update(mdict, def->m_base.m_copy))
750 return NULL;
751 }
752 else {
753 if (def->m_base.m_init == NULL)
754 return NULL;
755 mod = def->m_base.m_init();
756 if (mod == NULL)
757 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600758 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200759 Py_DECREF(mod);
760 return NULL;
761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 Py_DECREF(mod);
763 }
764 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600765 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 return NULL;
767 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200768 int verbose = _PyInterpreterState_Get()->config.verbose;
Victor Stinner410b85a2019-05-13 17:12:45 +0200769 if (verbose) {
Victor Stinner95872862011-03-07 18:20:56 +0100770 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Victor Stinner410b85a2019-05-13 17:12:45 +0200771 name, filename);
772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000774
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000775}
776
Victor Stinner49d3f252010-10-17 01:24:53 +0000777PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600778_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000779{
Victor Stinner95872862011-03-07 18:20:56 +0100780 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100781 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100782 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000783 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600784 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100785 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000786 return res;
787}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788
789/* Get the module object corresponding to a module name.
790 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000791 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000792 Because the former action is most common, THIS DOES NOT RETURN A
793 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000794
Guido van Rossum79f25d91997-04-29 20:08:16 +0000795PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000796PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600799 return _PyImport_AddModuleObject(name, modules);
800}
801
802PyObject *
803_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
804{
Eric Snow86b7afd2017-09-04 17:54:09 -0600805 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600806 if (PyDict_CheckExact(modules)) {
807 m = PyDict_GetItemWithError(modules, name);
808 }
809 else {
810 m = PyObject_GetItem(modules, name);
811 // For backward-comaptibility we copy the behavior
812 // of PyDict_GetItemWithError().
813 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
814 PyErr_Clear();
815 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200816 }
817 if (PyErr_Occurred()) {
818 return NULL;
819 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600820 if (m != NULL && PyModule_Check(m)) {
821 return m;
822 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000823 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (m == NULL)
825 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600826 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 Py_DECREF(m);
828 return NULL;
829 }
830 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000833}
834
Victor Stinner27ee0892011-03-04 12:57:09 +0000835PyObject *
836PyImport_AddModule(const char *name)
837{
838 PyObject *nameobj, *module;
839 nameobj = PyUnicode_FromString(name);
840 if (nameobj == NULL)
841 return NULL;
842 module = PyImport_AddModuleObject(nameobj);
843 Py_DECREF(nameobj);
844 return module;
845}
846
847
Tim Peters1cd70172004-08-02 03:52:12 +0000848/* Remove name from sys.modules, if it's there. */
849static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000850remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000851{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600852 PyObject *type, *value, *traceback;
853 PyErr_Fetch(&type, &value, &traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 PyObject *modules = PyImport_GetModuleDict();
Zackery Spytz94a64e92019-05-08 10:31:23 -0600855 if (!PyMapping_HasKey(modules, name)) {
856 goto out;
857 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600858 if (PyMapping_DelItem(modules, name) < 0) {
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200859 Py_FatalError("import: deleting existing key in "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600861 }
Zackery Spytz94a64e92019-05-08 10:31:23 -0600862out:
863 PyErr_Restore(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000864}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000865
Christian Heimes3b06e532008-01-07 20:12:44 +0000866
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000867/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000868 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
869 * removed from sys.modules, to avoid leaving damaged module objects
870 * in sys.modules. The caller may wish to restore the original
871 * module object (if any) in this case; PyImport_ReloadModule is an
872 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000873 *
874 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
875 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000876 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000877PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300878PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 return PyImport_ExecCodeModuleWithPathnames(
881 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000882}
883
884PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300885PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return PyImport_ExecCodeModuleWithPathnames(
888 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000889}
890
891PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300892PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
893 const char *pathname,
894 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000895{
Victor Stinner27ee0892011-03-04 12:57:09 +0000896 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600897 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000898
899 nameobj = PyUnicode_FromString(name);
900 if (nameobj == NULL)
901 return NULL;
902
Victor Stinner27ee0892011-03-04 12:57:09 +0000903 if (cpathname != NULL) {
904 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
905 if (cpathobj == NULL)
906 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400907 }
908 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000909 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400910
911 if (pathname != NULL) {
912 pathobj = PyUnicode_DecodeFSDefault(pathname);
913 if (pathobj == NULL)
914 goto error;
915 }
916 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200917 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400918 _Py_IDENTIFIER(_get_sourcefile);
919
920 if (interp == NULL) {
921 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
922 "no interpreter!");
923 }
924
Eric Snow32439d62015-05-02 19:15:18 -0600925 external= PyObject_GetAttrString(interp->importlib,
926 "_bootstrap_external");
927 if (external != NULL) {
928 pathobj = _PyObject_CallMethodIdObjArgs(external,
929 &PyId__get_sourcefile, cpathobj,
930 NULL);
931 Py_DECREF(external);
932 }
Brett Cannona6473f92012-07-13 13:57:03 -0400933 if (pathobj == NULL)
934 PyErr_Clear();
935 }
936 else
937 pathobj = NULL;
938
Victor Stinner27ee0892011-03-04 12:57:09 +0000939 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
940error:
941 Py_DECREF(nameobj);
942 Py_XDECREF(pathobj);
943 Py_XDECREF(cpathobj);
944 return m;
945}
946
Brett Cannon18fc4e72014-04-04 10:01:46 -0400947static PyObject *
948module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000949{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200950 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400951 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000952
Victor Stinner27ee0892011-03-04 12:57:09 +0000953 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (m == NULL)
955 return NULL;
956 /* If the module is being reloaded, we get the old module back
957 and re-use its dict to exec the new code. */
958 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200959 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
960 if (PyErr_Occurred() ||
961 _PyDict_SetItemId(d, &PyId___builtins__,
962 PyEval_GetBuiltins()) != 0)
963 {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400964 remove_module(name);
965 return NULL;
966 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400968
Eric Snow08197a42014-05-12 17:54:55 -0600969 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400970}
971
972static PyObject *
973exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
974{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400975 PyObject *v, *m;
976
977 v = PyEval_EvalCode(code_object, module_dict, module_dict);
978 if (v == NULL) {
979 remove_module(name);
980 return NULL;
981 }
982 Py_DECREF(v);
983
Eric Snow3f9eee62017-09-15 16:35:20 -0600984 m = PyImport_GetModule(name);
Stefan Krah027b09c2019-03-25 21:50:58 +0100985 if (m == NULL && !PyErr_Occurred()) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400986 PyErr_Format(PyExc_ImportError,
987 "Loaded module %R not found in sys.modules",
988 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400989 }
990
Brett Cannon18fc4e72014-04-04 10:01:46 -0400991 return m;
992}
993
994PyObject*
995PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
996 PyObject *cpathname)
997{
Eric Snow32439d62015-05-02 19:15:18 -0600998 PyObject *d, *external, *res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200999 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow08197a42014-05-12 17:54:55 -06001000 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -04001001
1002 d = module_dict_for_exec(name);
1003 if (d == NULL) {
1004 return NULL;
1005 }
1006
Eric Snow08197a42014-05-12 17:54:55 -06001007 if (pathname == NULL) {
1008 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 }
Eric Snow32439d62015-05-02 19:15:18 -06001010 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
1011 if (external == NULL)
1012 return NULL;
1013 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001014 &PyId__fix_up_module,
1015 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001016 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001017 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001018 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -06001019 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 }
Eric Snow08197a42014-05-12 17:54:55 -06001021 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001022}
1023
1024
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001025static void
1026update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyObject *constants, *tmp;
1029 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (PyUnicode_Compare(co->co_filename, oldname))
1032 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001033
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001034 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001035 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 constants = co->co_consts;
1038 n = PyTuple_GET_SIZE(constants);
1039 for (i = 0; i < n; i++) {
1040 tmp = PyTuple_GET_ITEM(constants, i);
1041 if (PyCode_Check(tmp))
1042 update_code_filenames((PyCodeObject *)tmp,
1043 oldname, newname);
1044 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001045}
1046
Victor Stinner2f42ae52011-03-20 00:41:24 +01001047static void
1048update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001049{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001050 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001051
Victor Stinner2f42ae52011-03-20 00:41:24 +01001052 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1053 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 oldname = co->co_filename;
1056 Py_INCREF(oldname);
1057 update_code_filenames(co, oldname, newname);
1058 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001059}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001060
Brett Cannon4caa61d2014-01-09 19:03:32 -05001061/*[clinic input]
1062_imp._fix_co_filename
1063
1064 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1065 Code object to change.
1066
1067 path: unicode
1068 File path to use.
1069 /
1070
1071Changes code.co_filename to specify the passed-in file path.
1072[clinic start generated code]*/
1073
Brett Cannon4caa61d2014-01-09 19:03:32 -05001074static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001075_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001076 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001077/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001078
Brett Cannon4caa61d2014-01-09 19:03:32 -05001079{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001080 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001081
1082 Py_RETURN_NONE;
1083}
1084
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001085
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001086/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001087static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001088
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001089
1090/* Helper to test for built-in module */
1091
1092static int
Victor Stinner95872862011-03-07 18:20:56 +01001093is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001094{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001095 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001097 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (PyImport_Inittab[i].initfunc == NULL)
1099 return -1;
1100 else
1101 return 1;
1102 }
1103 }
1104 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001105}
1106
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001107
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001108/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001109 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001110 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001111 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001112 this tells our caller that the path based finder could not find
1113 a finder for this path item. Cache the result in
1114 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001115 Returns a borrowed reference. */
1116
1117static PyObject *
1118get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyObject *importer;
1122 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* These conditions are the caller's responsibility: */
1125 assert(PyList_Check(path_hooks));
1126 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 nhooks = PyList_Size(path_hooks);
1129 if (nhooks < 0)
1130 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001131
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001132 importer = PyDict_GetItemWithError(path_importer_cache, p);
1133 if (importer != NULL || PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* set path_importer_cache[p] to None to avoid recursion */
1137 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1138 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 for (j = 0; j < nhooks; j++) {
1141 PyObject *hook = PyList_GetItem(path_hooks, j);
1142 if (hook == NULL)
1143 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001144 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (importer != NULL)
1146 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1149 return NULL;
1150 }
1151 PyErr_Clear();
1152 }
1153 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001154 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 }
1156 if (importer != NULL) {
1157 int err = PyDict_SetItem(path_importer_cache, p, importer);
1158 Py_DECREF(importer);
1159 if (err != 0)
1160 return NULL;
1161 }
1162 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001163}
1164
Benjamin Petersone5024512018-09-12 12:06:42 -07001165PyObject *
Christian Heimes9cd17752007-11-18 19:35:23 +00001166PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001168
Victor Stinner1e53bba2013-07-16 22:26:05 +02001169 path_importer_cache = PySys_GetObject("path_importer_cache");
1170 path_hooks = PySys_GetObject("path_hooks");
1171 if (path_importer_cache != NULL && path_hooks != NULL) {
1172 importer = get_path_importer(path_importer_cache,
1173 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
1175 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1176 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001177}
1178
Nick Coghland5cacbb2015-05-23 22:24:10 +10001179/*[clinic input]
1180_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001181
Nick Coghland5cacbb2015-05-23 22:24:10 +10001182 spec: object
1183 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001184
Nick Coghland5cacbb2015-05-23 22:24:10 +10001185Create an extension module.
1186[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001187
Nick Coghland5cacbb2015-05-23 22:24:10 +10001188static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001189_imp_create_builtin(PyObject *module, PyObject *spec)
1190/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001193 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001194 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001195 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001196
Nick Coghland5cacbb2015-05-23 22:24:10 +10001197 name = PyObject_GetAttrString(spec, "name");
1198 if (name == NULL) {
1199 return NULL;
1200 }
1201
Victor Stinner5eb4f592013-11-14 22:38:52 +01001202 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001203 if (mod || PyErr_Occurred()) {
1204 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001205 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001206 return mod;
1207 }
1208
1209 namestr = PyUnicode_AsUTF8(name);
1210 if (namestr == NULL) {
1211 Py_DECREF(name);
1212 return NULL;
1213 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001214
Eric Snowd393c1b2017-09-14 12:18:12 -06001215 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001217 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001218 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001220 /* Cannot re-init internal module ("sys" or "builtins") */
1221 mod = PyImport_AddModule(namestr);
1222 Py_DECREF(name);
1223 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001226 if (mod == NULL) {
1227 Py_DECREF(name);
1228 return NULL;
1229 }
1230 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1231 Py_DECREF(name);
1232 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1233 } else {
1234 /* Remember pointer to module init function. */
1235 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001236 if (def == NULL) {
1237 Py_DECREF(name);
1238 return NULL;
1239 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001240 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001241 if (modules == NULL) {
1242 modules = PyImport_GetModuleDict();
1243 }
1244 if (_PyImport_FixupExtensionObject(mod, name, name,
1245 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001246 Py_DECREF(name);
1247 return NULL;
1248 }
1249 Py_DECREF(name);
1250 return mod;
1251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 }
1253 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001254 Py_DECREF(name);
1255 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001256}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001257
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001258
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001259/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001260
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001261static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001262find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001263{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001264 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001265
Victor Stinner53dc7352011-03-20 01:50:21 +01001266 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 for (p = PyImport_FrozenModules; ; p++) {
1270 if (p->name == NULL)
1271 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001272 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 break;
1274 }
1275 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001276}
1277
Guido van Rossum79f25d91997-04-29 20:08:16 +00001278static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001279get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001280{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001281 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (p == NULL) {
1285 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001286 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 name);
1288 return NULL;
1289 }
1290 if (p->code == NULL) {
1291 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001292 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 name);
1294 return NULL;
1295 }
1296 size = p->size;
1297 if (size < 0)
1298 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001299 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001300}
1301
Brett Cannon8d110132009-03-15 02:20:16 +00001302static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001303is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001304{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001305 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (p == NULL) {
1309 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001310 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 name);
1312 return NULL;
1313 }
Brett Cannon8d110132009-03-15 02:20:16 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (size < 0)
1318 Py_RETURN_TRUE;
1319 else
1320 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001321}
1322
1323
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001324/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001325 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001326 an exception set if the initialization failed.
1327 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001328
1329int
Victor Stinner53dc7352011-03-20 01:50:21 +01001330PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001331{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001332 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001333 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 int ispackage;
1335 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001336
Victor Stinner53dc7352011-03-20 01:50:21 +01001337 p = find_frozen(name);
1338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (p == NULL)
1340 return 0;
1341 if (p->code == NULL) {
1342 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001343 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 name);
1345 return -1;
1346 }
1347 size = p->size;
1348 ispackage = (size < 0);
1349 if (ispackage)
1350 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001351 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (co == NULL)
1353 return -1;
1354 if (!PyCode_Check(co)) {
1355 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001356 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 name);
1358 goto err_return;
1359 }
1360 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001361 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001362 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001364 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 if (m == NULL)
1366 goto err_return;
1367 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001368 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 goto err_return;
1371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 err = PyDict_SetItemString(d, "__path__", l);
1373 Py_DECREF(l);
1374 if (err != 0)
1375 goto err_return;
1376 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001377 d = module_dict_for_exec(name);
1378 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001379 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001380 }
1381 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (m == NULL)
1383 goto err_return;
1384 Py_DECREF(co);
1385 Py_DECREF(m);
1386 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 Py_DECREF(co);
1389 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001390}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001391
Victor Stinner53dc7352011-03-20 01:50:21 +01001392int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001393PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001394{
1395 PyObject *nameobj;
1396 int ret;
1397 nameobj = PyUnicode_InternFromString(name);
1398 if (nameobj == NULL)
1399 return -1;
1400 ret = PyImport_ImportFrozenModuleObject(nameobj);
1401 Py_DECREF(nameobj);
1402 return ret;
1403}
1404
Guido van Rossum74e6a111994-08-29 12:54:38 +00001405
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001406/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001407 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001408
Guido van Rossum79f25d91997-04-29 20:08:16 +00001409PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001410PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyObject *pname;
1413 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 pname = PyUnicode_FromString(name);
1416 if (pname == NULL)
1417 return NULL;
1418 result = PyImport_Import(pname);
1419 Py_DECREF(pname);
1420 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001421}
1422
Christian Heimes072c0f12008-01-03 23:01:04 +00001423/* Import a module without blocking
1424 *
1425 * At first it tries to fetch the module from sys.modules. If the module was
1426 * never loaded before it loads it with PyImport_ImportModule() unless another
1427 * thread holds the import lock. In the latter case the function raises an
1428 * ImportError instead of blocking.
1429 *
1430 * Returns the module object with incremented ref count.
1431 */
1432PyObject *
1433PyImport_ImportModuleNoBlock(const char *name)
1434{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001435 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001436}
1437
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001438
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001439/* Remove importlib frames from the traceback,
1440 * except in Verbose mode. */
1441static void
Victor Stinner410b85a2019-05-13 17:12:45 +02001442remove_importlib_frames(PyInterpreterState *interp)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001443{
1444 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001445 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001446 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001447 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001448 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001449 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001450 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001451
1452 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001453 from the traceback. We always trim chunks
1454 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001455
1456 PyErr_Fetch(&exception, &value, &base_tb);
Victor Stinner331a6a52019-05-27 16:39:22 +02001457 if (!exception || interp->config.verbose) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001458 goto done;
Victor Stinner410b85a2019-05-13 17:12:45 +02001459 }
1460
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001461 if (PyType_IsSubtype((PyTypeObject *) exception,
1462 (PyTypeObject *) PyExc_ImportError))
1463 always_trim = 1;
1464
1465 prev_link = &base_tb;
1466 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001467 while (tb != NULL) {
1468 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1469 PyObject *next = (PyObject *) traceback->tb_next;
1470 PyFrameObject *frame = traceback->tb_frame;
1471 PyCodeObject *code = frame->f_code;
1472 int now_in_importlib;
1473
1474 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001475 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1476 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001477 if (now_in_importlib && !in_importlib) {
1478 /* This is the link to this chunk of importlib tracebacks */
1479 outer_link = prev_link;
1480 }
1481 in_importlib = now_in_importlib;
1482
1483 if (in_importlib &&
1484 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001485 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001486 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001487 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001488 prev_link = outer_link;
1489 }
1490 else {
1491 prev_link = (PyObject **) &traceback->tb_next;
1492 }
1493 tb = next;
1494 }
1495done:
1496 PyErr_Restore(exception, value, base_tb);
1497}
1498
1499
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001500static PyObject *
1501resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001502{
Eric Snowb523f842013-11-22 09:05:39 -07001503 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001504 _Py_IDENTIFIER(__package__);
1505 _Py_IDENTIFIER(__path__);
1506 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001507 _Py_IDENTIFIER(parent);
1508 PyObject *abs_name;
1509 PyObject *package = NULL;
1510 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001511 Py_ssize_t last_dot;
1512 PyObject *base;
1513 int level_up;
1514
1515 if (globals == NULL) {
1516 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1517 goto error;
1518 }
1519 if (!PyDict_Check(globals)) {
1520 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1521 goto error;
1522 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001523 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001524 if (package == Py_None) {
1525 package = NULL;
1526 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001527 else if (package == NULL && PyErr_Occurred()) {
1528 goto error;
1529 }
1530 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
1531 if (spec == NULL && PyErr_Occurred()) {
1532 goto error;
1533 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001534
1535 if (package != NULL) {
1536 Py_INCREF(package);
1537 if (!PyUnicode_Check(package)) {
1538 PyErr_SetString(PyExc_TypeError, "package must be a string");
1539 goto error;
1540 }
1541 else if (spec != NULL && spec != Py_None) {
1542 int equal;
1543 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1544 if (parent == NULL) {
1545 goto error;
1546 }
1547
1548 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1549 Py_DECREF(parent);
1550 if (equal < 0) {
1551 goto error;
1552 }
1553 else if (equal == 0) {
1554 if (PyErr_WarnEx(PyExc_ImportWarning,
1555 "__package__ != __spec__.parent", 1) < 0) {
1556 goto error;
1557 }
1558 }
1559 }
1560 }
1561 else if (spec != NULL && spec != Py_None) {
1562 package = _PyObject_GetAttrId(spec, &PyId_parent);
1563 if (package == NULL) {
1564 goto error;
1565 }
1566 else if (!PyUnicode_Check(package)) {
1567 PyErr_SetString(PyExc_TypeError,
1568 "__spec__.parent must be a string");
1569 goto error;
1570 }
1571 }
1572 else {
1573 if (PyErr_WarnEx(PyExc_ImportWarning,
1574 "can't resolve package from __spec__ or __package__, "
1575 "falling back on __name__ and __path__", 1) < 0) {
1576 goto error;
1577 }
1578
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001579 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001580 if (package == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001581 if (!PyErr_Occurred()) {
1582 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1583 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001584 goto error;
1585 }
1586
1587 Py_INCREF(package);
1588 if (!PyUnicode_Check(package)) {
1589 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1590 goto error;
1591 }
1592
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001593 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001594 Py_ssize_t dot;
1595
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001596 if (PyErr_Occurred() || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001597 goto error;
1598 }
1599
1600 dot = PyUnicode_FindChar(package, '.',
1601 0, PyUnicode_GET_LENGTH(package), -1);
1602 if (dot == -2) {
1603 goto error;
1604 }
Brett Cannon0a6693a2019-09-11 12:38:22 +01001605 else if (dot == -1) {
1606 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001607 }
Brett Cannon0a6693a2019-09-11 12:38:22 +01001608 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1609 if (substr == NULL) {
1610 goto error;
1611 }
1612 Py_SETREF(package, substr);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001613 }
1614 }
1615
1616 last_dot = PyUnicode_GET_LENGTH(package);
1617 if (last_dot == 0) {
Brett Cannon0a6693a2019-09-11 12:38:22 +01001618 goto no_parent_error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001619 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001620
1621 for (level_up = 1; level_up < level; level_up += 1) {
1622 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1623 if (last_dot == -2) {
1624 goto error;
1625 }
1626 else if (last_dot == -1) {
1627 PyErr_SetString(PyExc_ValueError,
1628 "attempted relative import beyond top-level "
1629 "package");
1630 goto error;
1631 }
1632 }
1633
1634 base = PyUnicode_Substring(package, 0, last_dot);
1635 Py_DECREF(package);
1636 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1637 return base;
1638 }
1639
1640 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1641 Py_DECREF(base);
1642 return abs_name;
1643
Brett Cannon0a6693a2019-09-11 12:38:22 +01001644 no_parent_error:
1645 PyErr_SetString(PyExc_ImportError,
1646 "attempted relative import "
1647 "with no known parent package");
1648
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001649 error:
1650 Py_XDECREF(package);
1651 return NULL;
1652}
1653
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001654static PyObject *
1655import_find_and_load(PyObject *abs_name)
1656{
1657 _Py_IDENTIFIER(_find_and_load);
1658 PyObject *mod = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001659 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +02001660 int import_time = interp->config.import_time;
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001661 static int import_level;
1662 static _PyTime_t accumulated;
1663
1664 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1665
Steve Dowerb82e17e2019-05-23 08:45:22 -07001666 PyObject *sys_path = PySys_GetObject("path");
1667 PyObject *sys_meta_path = PySys_GetObject("meta_path");
1668 PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1669 if (PySys_Audit("import", "OOOOO",
1670 abs_name, Py_None, sys_path ? sys_path : Py_None,
1671 sys_meta_path ? sys_meta_path : Py_None,
1672 sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1673 return NULL;
1674 }
1675
1676
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001677 /* XOptions is initialized after first some imports.
1678 * So we can't have negative cache before completed initialization.
1679 * Anyway, importlib._find_and_load is much slower than
1680 * _PyDict_GetItemIdWithError().
1681 */
1682 if (import_time) {
1683 static int header = 1;
1684 if (header) {
1685 fputs("import time: self [us] | cumulative | imported package\n",
1686 stderr);
1687 header = 0;
1688 }
1689
1690 import_level++;
1691 t1 = _PyTime_GetPerfCounter();
1692 accumulated = 0;
1693 }
1694
1695 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1696 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1697
1698 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1699 &PyId__find_and_load, abs_name,
1700 interp->import_func, NULL);
1701
1702 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1703 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1704 mod != NULL);
1705
1706 if (import_time) {
1707 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1708
1709 import_level--;
1710 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1711 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1712 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1713 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1714
1715 accumulated = accumulated_copy + cum;
1716 }
1717
1718 return mod;
1719}
1720
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001721PyObject *
1722PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1723 PyObject *locals, PyObject *fromlist,
1724 int level)
1725{
Brett Cannonfd074152012-04-14 14:10:13 -04001726 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001727 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001728 PyObject *final_mod = NULL;
1729 PyObject *mod = NULL;
1730 PyObject *package = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001731 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001732 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001733
Brett Cannonfd074152012-04-14 14:10:13 -04001734 if (name == NULL) {
1735 PyErr_SetString(PyExc_ValueError, "Empty module name");
1736 goto error;
1737 }
1738
1739 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1740 for added performance. */
1741
1742 if (!PyUnicode_Check(name)) {
1743 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1744 goto error;
1745 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001746 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001747 goto error;
1748 }
1749 if (level < 0) {
1750 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1751 goto error;
1752 }
Brett Cannon849113a2016-01-22 15:25:50 -08001753
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001754 if (level > 0) {
1755 abs_name = resolve_name(name, globals, level);
1756 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001757 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001758 }
1759 else { /* level == 0 */
1760 if (PyUnicode_GET_LENGTH(name) == 0) {
1761 PyErr_SetString(PyExc_ValueError, "Empty module name");
1762 goto error;
1763 }
Brett Cannonfd074152012-04-14 14:10:13 -04001764 abs_name = name;
1765 Py_INCREF(abs_name);
1766 }
1767
Eric Snow3f9eee62017-09-15 16:35:20 -06001768 mod = PyImport_GetModule(abs_name);
Stefan Krah027b09c2019-03-25 21:50:58 +01001769 if (mod == NULL && PyErr_Occurred()) {
1770 goto error;
1771 }
1772
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001773 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001774 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001775 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001776 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001777
Antoine Pitrou03989852012-08-28 00:24:52 +02001778 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001779 __spec__._initializing is true.
1780 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001781 stuffing the new module in sys.modules.
1782 */
Eric Snowb523f842013-11-22 09:05:39 -07001783 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001784 if (_PyModuleSpec_IsInitializing(spec)) {
1785 PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1786 &PyId__lock_unlock_module, abs_name,
1787 NULL);
1788 if (value == NULL) {
1789 Py_DECREF(spec);
1790 goto error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001791 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001792 Py_DECREF(value);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001793 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001794 Py_XDECREF(spec);
Brett Cannonfd074152012-04-14 14:10:13 -04001795 }
1796 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001797 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001798 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001799 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001800 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001801 }
1802 }
1803
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001804 has_from = 0;
1805 if (fromlist != NULL && fromlist != Py_None) {
1806 has_from = PyObject_IsTrue(fromlist);
1807 if (has_from < 0)
1808 goto error;
1809 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001810 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001811 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1812 if (level == 0 || len > 0) {
1813 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001814
Victor Stinner744c34e2016-05-20 11:36:13 +02001815 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1816 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001817 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001818 }
1819
Victor Stinner744c34e2016-05-20 11:36:13 +02001820 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001821 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001822 final_mod = mod;
1823 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001824 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001825 }
1826
Brett Cannonfd074152012-04-14 14:10:13 -04001827 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001828 PyObject *front = PyUnicode_Substring(name, 0, dot);
1829 if (front == NULL) {
1830 goto error;
1831 }
1832
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001833 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001834 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001835 }
1836 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001837 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001838 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001839 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001840 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001841 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001842 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001843 }
Brett Cannonfd074152012-04-14 14:10:13 -04001844
Eric Snow3f9eee62017-09-15 16:35:20 -06001845 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001846 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001847 if (final_mod == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001848 if (!PyErr_Occurred()) {
1849 PyErr_Format(PyExc_KeyError,
1850 "%R not in sys.modules as expected",
1851 to_return);
1852 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001853 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001854 }
Brett Cannonfd074152012-04-14 14:10:13 -04001855 }
1856 }
1857 else {
1858 final_mod = mod;
1859 Py_INCREF(mod);
1860 }
1861 }
1862 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001863 _Py_IDENTIFIER(__path__);
1864 PyObject *path;
1865 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1866 goto error;
1867 }
1868 if (path) {
1869 Py_DECREF(path);
1870 final_mod = _PyObject_CallMethodIdObjArgs(
1871 interp->importlib, &PyId__handle_fromlist,
1872 mod, fromlist, interp->import_func, NULL);
1873 }
1874 else {
1875 final_mod = mod;
1876 Py_INCREF(mod);
1877 }
Brett Cannonfd074152012-04-14 14:10:13 -04001878 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001879
Brett Cannonfd074152012-04-14 14:10:13 -04001880 error:
1881 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001882 Py_XDECREF(mod);
1883 Py_XDECREF(package);
Victor Stinner410b85a2019-05-13 17:12:45 +02001884 if (final_mod == NULL) {
1885 remove_importlib_frames(interp);
1886 }
Brett Cannonfd074152012-04-14 14:10:13 -04001887 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001888}
1889
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001890PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001891PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001892 PyObject *fromlist, int level)
1893{
1894 PyObject *nameobj, *mod;
1895 nameobj = PyUnicode_FromString(name);
1896 if (nameobj == NULL)
1897 return NULL;
1898 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1899 fromlist, level);
1900 Py_DECREF(nameobj);
1901 return mod;
1902}
1903
1904
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001905/* Re-import a module of any kind and return its module object, WITH
1906 INCREMENTED REFERENCE COUNT */
1907
Guido van Rossum79f25d91997-04-29 20:08:16 +00001908PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001909PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001910{
Eric Snow3f9eee62017-09-15 16:35:20 -06001911 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001912 _Py_IDENTIFIER(reload);
1913 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001914 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001915 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001916 if (PyErr_Occurred()) {
1917 return NULL;
1918 }
1919
Brett Cannon62228db2012-04-29 14:38:11 -04001920 imp = PyImport_ImportModule("imp");
1921 if (imp == NULL) {
1922 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001925
Victor Stinner55ba38a2016-12-09 16:09:30 +01001926 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001927 Py_DECREF(imp);
1928 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001929}
1930
1931
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001932/* Higher-level import emulator which emulates the "import" statement
1933 more accurately -- it invokes the __import__() function from the
1934 builtins of the current globals. This means that the import is
1935 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001936 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001937 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001938 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001939 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001940
1941PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001942PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 static PyObject *silly_list = NULL;
1945 static PyObject *builtins_str = NULL;
1946 static PyObject *import_str = NULL;
1947 PyObject *globals = NULL;
1948 PyObject *import = NULL;
1949 PyObject *builtins = NULL;
1950 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 /* Initialize constant string objects */
1953 if (silly_list == NULL) {
1954 import_str = PyUnicode_InternFromString("__import__");
1955 if (import_str == NULL)
1956 return NULL;
1957 builtins_str = PyUnicode_InternFromString("__builtins__");
1958 if (builtins_str == NULL)
1959 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001960 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 if (silly_list == NULL)
1962 return NULL;
1963 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 /* Get the builtins from current globals */
1966 globals = PyEval_GetGlobals();
1967 if (globals != NULL) {
1968 Py_INCREF(globals);
1969 builtins = PyObject_GetItem(globals, builtins_str);
1970 if (builtins == NULL)
1971 goto err;
1972 }
1973 else {
1974 /* No globals -- use standard builtins, and fake globals */
1975 builtins = PyImport_ImportModuleLevel("builtins",
1976 NULL, NULL, NULL, 0);
1977 if (builtins == NULL)
1978 return NULL;
1979 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1980 if (globals == NULL)
1981 goto err;
1982 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 /* Get the __import__ function from the builtins */
1985 if (PyDict_Check(builtins)) {
1986 import = PyObject_GetItem(builtins, import_str);
1987 if (import == NULL)
1988 PyErr_SetObject(PyExc_KeyError, import_str);
1989 }
1990 else
1991 import = PyObject_GetAttr(builtins, import_str);
1992 if (import == NULL)
1993 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001996 Always use absolute import here.
1997 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1999 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002000 if (r == NULL)
2001 goto err;
2002 Py_DECREF(r);
2003
Eric Snow3f9eee62017-09-15 16:35:20 -06002004 r = PyImport_GetModule(module_name);
2005 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03002006 PyErr_SetObject(PyExc_KeyError, module_name);
2007 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002008
2009 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 Py_XDECREF(globals);
2011 Py_XDECREF(builtins);
2012 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002015}
2016
Brett Cannon4caa61d2014-01-09 19:03:32 -05002017/*[clinic input]
2018_imp.extension_suffixes
2019
2020Returns the list of file suffixes used to identify extension modules.
2021[clinic start generated code]*/
2022
Brett Cannon4caa61d2014-01-09 19:03:32 -05002023static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002024_imp_extension_suffixes_impl(PyObject *module)
2025/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 list = PyList_New(0);
2030 if (list == NULL)
2031 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002032#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002033 const char *suffix;
2034 unsigned int index = 0;
2035
Brett Cannon2657df42012-05-04 15:20:40 -04002036 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2037 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (item == NULL) {
2039 Py_DECREF(list);
2040 return NULL;
2041 }
2042 if (PyList_Append(list, item) < 0) {
2043 Py_DECREF(list);
2044 Py_DECREF(item);
2045 return NULL;
2046 }
2047 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002048 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 }
Brett Cannon2657df42012-05-04 15:20:40 -04002050#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002052}
2053
Brett Cannon4caa61d2014-01-09 19:03:32 -05002054/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002055_imp.init_frozen
2056
2057 name: unicode
2058 /
2059
2060Initializes a frozen module.
2061[clinic start generated code]*/
2062
Brett Cannon4caa61d2014-01-09 19:03:32 -05002063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002064_imp_init_frozen_impl(PyObject *module, PyObject *name)
2065/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 int ret;
2068 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002069
Victor Stinner53dc7352011-03-20 01:50:21 +01002070 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (ret < 0)
2072 return NULL;
2073 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002074 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002076 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 Py_XINCREF(m);
2078 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002079}
2080
Brett Cannon4caa61d2014-01-09 19:03:32 -05002081/*[clinic input]
2082_imp.get_frozen_object
2083
2084 name: unicode
2085 /
2086
2087Create a code object for a frozen module.
2088[clinic start generated code]*/
2089
Brett Cannon4caa61d2014-01-09 19:03:32 -05002090static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002091_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2092/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002095}
2096
Brett Cannon4caa61d2014-01-09 19:03:32 -05002097/*[clinic input]
2098_imp.is_frozen_package
2099
2100 name: unicode
2101 /
2102
2103Returns True if the module name is of a frozen package.
2104[clinic start generated code]*/
2105
Brett Cannon4caa61d2014-01-09 19:03:32 -05002106static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002107_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2108/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002111}
2112
Brett Cannon4caa61d2014-01-09 19:03:32 -05002113/*[clinic input]
2114_imp.is_builtin
2115
2116 name: unicode
2117 /
2118
2119Returns True if the module name corresponds to a built-in module.
2120[clinic start generated code]*/
2121
Guido van Rossum79f25d91997-04-29 20:08:16 +00002122static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002123_imp_is_builtin_impl(PyObject *module, PyObject *name)
2124/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002125{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002126 return PyLong_FromLong(is_builtin(name));
2127}
2128
2129/*[clinic input]
2130_imp.is_frozen
2131
2132 name: unicode
2133 /
2134
2135Returns True if the module name corresponds to a frozen module.
2136[clinic start generated code]*/
2137
Brett Cannon4caa61d2014-01-09 19:03:32 -05002138static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002139_imp_is_frozen_impl(PyObject *module, PyObject *name)
2140/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002141{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002142 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 p = find_frozen(name);
2145 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002146}
2147
Larry Hastings1df0b352015-08-24 19:53:56 -07002148/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2149static int
2150exec_builtin_or_dynamic(PyObject *mod) {
2151 PyModuleDef *def;
2152 void *state;
2153
2154 if (!PyModule_Check(mod)) {
2155 return 0;
2156 }
2157
2158 def = PyModule_GetDef(mod);
2159 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002160 return 0;
2161 }
Brett Cannon52794db2016-09-07 17:00:43 -07002162
Larry Hastings1df0b352015-08-24 19:53:56 -07002163 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002164 if (state) {
2165 /* Already initialized; skip reload */
2166 return 0;
2167 }
Brett Cannon52794db2016-09-07 17:00:43 -07002168
Larry Hastings1df0b352015-08-24 19:53:56 -07002169 return PyModule_ExecDef(mod, def);
2170}
2171
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002172#ifdef HAVE_DYNAMIC_LOADING
2173
Brett Cannon4caa61d2014-01-09 19:03:32 -05002174/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002175_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002176
Nick Coghland5cacbb2015-05-23 22:24:10 +10002177 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002178 file: object = NULL
2179 /
2180
Nick Coghland5cacbb2015-05-23 22:24:10 +10002181Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002182[clinic start generated code]*/
2183
Brett Cannon4caa61d2014-01-09 19:03:32 -05002184static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002185_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2186/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002187{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002188 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002189 FILE *fp;
2190
Nick Coghland5cacbb2015-05-23 22:24:10 +10002191 name = PyObject_GetAttrString(spec, "name");
2192 if (name == NULL) {
2193 return NULL;
2194 }
2195
2196 path = PyObject_GetAttrString(spec, "origin");
2197 if (path == NULL) {
2198 Py_DECREF(name);
2199 return NULL;
2200 }
2201
2202 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002203 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002204 Py_DECREF(name);
2205 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002206 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002207 return mod;
2208 }
2209
Brett Cannon4caa61d2014-01-09 19:03:32 -05002210 if (file != NULL) {
2211 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002212 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002213 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002214 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002216 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002218 else
2219 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002220
2221 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2222
2223 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002224 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (fp)
2226 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002227 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002228}
2229
Nick Coghland5cacbb2015-05-23 22:24:10 +10002230/*[clinic input]
2231_imp.exec_dynamic -> int
2232
2233 mod: object
2234 /
2235
2236Initialize an extension module.
2237[clinic start generated code]*/
2238
2239static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002240_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2241/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002242{
Larry Hastings1df0b352015-08-24 19:53:56 -07002243 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002244}
2245
2246
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002247#endif /* HAVE_DYNAMIC_LOADING */
2248
Larry Hastings7726ac92014-01-31 22:03:12 -08002249/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002250_imp.exec_builtin -> int
2251
2252 mod: object
2253 /
2254
2255Initialize a built-in module.
2256[clinic start generated code]*/
2257
2258static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002259_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2260/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002261{
2262 return exec_builtin_or_dynamic(mod);
2263}
2264
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002265/*[clinic input]
2266_imp.source_hash
2267
2268 key: long
2269 source: Py_buffer
2270[clinic start generated code]*/
2271
2272static PyObject *
2273_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2274/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2275{
Benjamin Peterson83620772017-12-09 12:18:56 -08002276 union {
2277 uint64_t x;
2278 char data[sizeof(uint64_t)];
2279 } hash;
2280 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002281#if !PY_LITTLE_ENDIAN
2282 // Force to little-endian. There really ought to be a succinct standard way
2283 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002284 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2285 char tmp = hash.data[i];
2286 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2287 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002288 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002289#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002290 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002291}
2292
Barry Warsaw28a691b2010-04-17 00:19:56 +00002293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002294PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002295"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002296
Guido van Rossum79f25d91997-04-29 20:08:16 +00002297static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002298 _IMP_EXTENSION_SUFFIXES_METHODDEF
2299 _IMP_LOCK_HELD_METHODDEF
2300 _IMP_ACQUIRE_LOCK_METHODDEF
2301 _IMP_RELEASE_LOCK_METHODDEF
2302 _IMP_GET_FROZEN_OBJECT_METHODDEF
2303 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002304 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002305 _IMP_INIT_FROZEN_METHODDEF
2306 _IMP_IS_BUILTIN_METHODDEF
2307 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002308 _IMP_CREATE_DYNAMIC_METHODDEF
2309 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002310 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002311 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002312 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002313 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002314};
2315
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002316
Martin v. Löwis1a214512008-06-11 05:26:20 +00002317static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002319 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 doc_imp,
2321 0,
2322 imp_methods,
2323 NULL,
2324 NULL,
2325 NULL,
2326 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002327};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002328
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002329PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002330PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 m = PyModule_Create(&impmodule);
Victor Stinner410b85a2019-05-13 17:12:45 +02002335 if (m == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002337 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 d = PyModule_GetDict(m);
Victor Stinner410b85a2019-05-13 17:12:45 +02002339 if (d == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 goto failure;
Victor Stinner410b85a2019-05-13 17:12:45 +02002341 }
2342
Victor Stinner331a6a52019-05-27 16:39:22 +02002343 const wchar_t *mode = _PyInterpreterState_Get()->config.check_hash_pycs_mode;
Victor Stinner410b85a2019-05-13 17:12:45 +02002344 PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002345 if (pyc_mode == NULL) {
2346 goto failure;
2347 }
2348 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2349 Py_DECREF(pyc_mode);
2350 goto failure;
2351 }
2352 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002355 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 Py_XDECREF(m);
2357 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002358}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002359
2360
Guido van Rossumb18618d2000-05-03 23:44:39 +00002361/* API for embedding applications that want to add their own entries
2362 to the table of built-in modules. This should normally be called
2363 *before* Py_Initialize(). When the table resize fails, -1 is
2364 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002365
2366 After a similar function by Just van Rossum. */
2367
2368int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002369PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002372 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002373 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Count the number of entries in both tables */
2376 for (n = 0; newtab[n].name != NULL; n++)
2377 ;
2378 if (n == 0)
2379 return 0; /* Nothing to do */
2380 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2381 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002382
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002383 /* Force default raw memory allocator to get a known allocator to be able
2384 to release the memory in _PyImport_Fini2() */
2385 PyMemAllocatorEx old_alloc;
2386 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002389 p = NULL;
2390 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002391 size_t size = sizeof(struct _inittab) * (i + n + 1);
2392 p = PyMem_RawRealloc(inittab_copy, size);
2393 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002394 if (p == NULL) {
2395 res = -1;
2396 goto done;
2397 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002398
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002399 /* Copy the tables into the new memory at the first call
2400 to PyImport_ExtendInittab(). */
2401 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002403 }
2404 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2405 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002406
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002407done:
2408 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2409 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002410}
2411
2412/* Shorthand to add a single entry given a name and a function */
2413
2414int
Brett Cannona826f322009-04-02 03:41:46 +00002415PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002420
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002421 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002425}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002426
2427#ifdef __cplusplus
2428}
2429#endif