blob: 9290f39c0ae28435d1700e4c15aef0b831ee3bc5 [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 Stinnerf7e5b562017-11-15 15:48:08 -080046_PyInitError
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) {
51 return _Py_INIT_ERR("Can't backup builtins dict");
52 }
53 return _Py_INIT_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054}
55
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056_PyInitError
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 Stinnerf7e5b562017-11-15 15:48:08 -080085 return _Py_INIT_OK();
86
87 error:
88 PyErr_Print();
89 return _Py_INIT_ERR("initializing sys.meta_path, sys.path_hooks, "
90 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040091}
92
Victor Stinnerf7e5b562017-11-15 15:48:08 -080093_PyInitError
Brett Cannonfd074152012-04-14 14:10:13 -040094_PyImportZip_Init(void)
95{
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
105 if (Py_VerboseFlag)
106 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107
ukwksk5e6312c2018-05-15 04:10:52 +0900108 zipimport = PyImport_ImportModule("zipimport");
109 if (zipimport == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 PyErr_Clear(); /* No zip import module -- okay */
111 if (Py_VerboseFlag)
112 PySys_WriteStderr("# can't import zipimport\n");
113 }
114 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200115 _Py_IDENTIFIER(zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900116 PyObject *zipimporter = _PyObject_GetAttrId(zipimport,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200117 &PyId_zipimporter);
ukwksk5e6312c2018-05-15 04:10:52 +0900118 Py_DECREF(zipimport);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 if (zipimporter == NULL) {
120 PyErr_Clear(); /* No zipimporter object -- okay */
121 if (Py_VerboseFlag)
122 PySys_WriteStderr(
123 "# can't import zipimport.zipimporter\n");
124 }
125 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400126 /* sys.path_hooks.insert(0, zipimporter) */
127 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400129 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 if (Py_VerboseFlag)
133 PySys_WriteStderr(
134 "# installed zipimport hook\n");
135 }
136 }
Brett Cannonfd074152012-04-14 14:10:13 -0400137
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800138 return _Py_INIT_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400139
140 error:
141 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800142 return _Py_INIT_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000143}
144
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000145/* Locking primitives to prevent parallel imports of the same module
146 in different threads to return with a partially loaded module.
147 These calls are serialized by the global interpreter lock. */
148
Guido van Rossum49b56061998-10-01 20:42:43 +0000149#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000150
Guido van Rossum65d5b571998-12-21 19:32:43 +0000151static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200152static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153static int import_lock_level = 0;
154
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000155void
156_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000157{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200158 unsigned long me = PyThread_get_thread_ident();
159 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 return; /* Too bad */
161 if (import_lock == NULL) {
162 import_lock = PyThread_allocate_lock();
163 if (import_lock == NULL)
164 return; /* Nothing much we can do. */
165 }
166 if (import_lock_thread == me) {
167 import_lock_level++;
168 return;
169 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200170 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
171 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 {
173 PyThreadState *tstate = PyEval_SaveThread();
174 PyThread_acquire_lock(import_lock, 1);
175 PyEval_RestoreThread(tstate);
176 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100177 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 import_lock_thread = me;
179 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000180}
181
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000182int
183_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000184{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200185 unsigned long me = PyThread_get_thread_ident();
186 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return 0; /* Too bad */
188 if (import_lock_thread != me)
189 return -1;
190 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100191 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200193 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyThread_release_lock(import_lock);
195 }
196 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000197}
198
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200199/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000200 created child processes do not share locks with the parent.
201 We now acquire the import lock around fork() calls but on some platforms
202 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000203
204void
205_PyImport_ReInitLock(void)
206{
Christian Heimes418fd742015-04-19 21:08:42 +0200207 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200209 if (import_lock == NULL) {
210 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
211 }
212 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000213 if (import_lock_level > 1) {
214 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200215 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500216 /* The following could fail if the lock is already held, but forking as
217 a side-effect of an import is a) rare, b) nuts, and c) difficult to
218 do thanks to the lock only being held when doing individual module
219 locks per import. */
220 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000221 import_lock_thread = me;
222 import_lock_level--;
223 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200224 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000225 import_lock_level = 0;
226 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000227}
228
Brett Cannon4caa61d2014-01-09 19:03:32 -0500229/*[clinic input]
230_imp.lock_held
231
232Return True if the import lock is currently held, else False.
233
234On platforms without threads, return False.
235[clinic start generated code]*/
236
Brett Cannon4caa61d2014-01-09 19:03:32 -0500237static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300238_imp_lock_held_impl(PyObject *module)
239/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000240{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200241 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000242}
243
Brett Cannon4caa61d2014-01-09 19:03:32 -0500244/*[clinic input]
245_imp.acquire_lock
246
247Acquires the interpreter's import lock for the current thread.
248
249This lock should be used by import hooks to ensure thread-safety when importing
250modules. On platforms without threads, this function does nothing.
251[clinic start generated code]*/
252
Brett Cannon4caa61d2014-01-09 19:03:32 -0500253static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300254_imp_acquire_lock_impl(PyObject *module)
255/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200258 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000259}
260
Brett Cannon4caa61d2014-01-09 19:03:32 -0500261/*[clinic input]
262_imp.release_lock
263
264Release the interpreter's import lock.
265
266On platforms without threads, this function does nothing.
267[clinic start generated code]*/
268
Brett Cannon4caa61d2014-01-09 19:03:32 -0500269static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300270_imp_release_lock_impl(PyObject *module)
271/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (_PyImport_ReleaseLock() < 0) {
274 PyErr_SetString(PyExc_RuntimeError,
275 "not holding the import lock");
276 return NULL;
277 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200278 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000279}
280
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100281void
282_PyImport_Fini(void)
283{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200284 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100285 if (import_lock != NULL) {
286 PyThread_free_lock(import_lock);
287 import_lock = NULL;
288 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100289}
290
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100291void
292_PyImport_Fini2(void)
293{
294 /* Use the same memory allocator than PyImport_ExtendInittab(). */
295 PyMemAllocatorEx old_alloc;
296 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
297
298 /* Free memory allocated by PyImport_ExtendInittab() */
299 PyMem_RawFree(inittab_copy);
300
301 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
302}
303
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304/* Helper for sys */
305
306PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000307PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000308{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200309 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow3f9eee62017-09-15 16:35:20 -0600310 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700311 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600312 }
Eric Snow93c92f72017-09-13 23:46:04 -0700313 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000314}
315
Eric Snowd393c1b2017-09-14 12:18:12 -0600316/* In some corner cases it is important to be sure that the import
317 machinery has been initialized (or not cleaned up yet). For
318 example, see issue #4236 and PyModule_Create2(). */
319
320int
321_PyImport_IsInitialized(PyInterpreterState *interp)
322{
323 if (interp->modules == NULL)
324 return 0;
325 return 1;
326}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000327
Eric Snow3f9eee62017-09-15 16:35:20 -0600328PyObject *
329_PyImport_GetModuleId(struct _Py_Identifier *nameid)
330{
331 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
332 if (name == NULL) {
333 return NULL;
334 }
335 return PyImport_GetModule(name);
336}
337
338int
339_PyImport_SetModule(PyObject *name, PyObject *m)
340{
341 PyObject *modules = PyImport_GetModuleDict();
342 return PyObject_SetItem(modules, name, m);
343}
344
345int
346_PyImport_SetModuleString(const char *name, PyObject *m)
347{
348 PyObject *modules = PyImport_GetModuleDict();
349 return PyMapping_SetItemString(modules, name, m);
350}
351
352PyObject *
353PyImport_GetModule(PyObject *name)
354{
355 PyObject *m;
356 PyObject *modules = PyImport_GetModuleDict();
357 if (modules == NULL) {
358 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
359 return NULL;
360 }
361 Py_INCREF(modules);
362 if (PyDict_CheckExact(modules)) {
363 m = PyDict_GetItemWithError(modules, name); /* borrowed */
364 Py_XINCREF(m);
365 }
366 else {
367 m = PyObject_GetItem(modules, name);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300368 if (m == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600369 PyErr_Clear();
370 }
371 }
372 Py_DECREF(modules);
373 return m;
374}
375
376
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000377/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200378static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 "path", "argv", "ps1", "ps2",
380 "last_type", "last_value", "last_traceback",
381 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200382 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 /* misc stuff */
384 "flags", "float_info",
385 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000386};
387
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200388static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 "stdin", "__stdin__",
390 "stdout", "__stdout__",
391 "stderr", "__stderr__",
392 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000393};
394
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000395/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000398PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000399{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200400 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject *key, *value, *dict;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200402 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snowd393c1b2017-09-14 12:18:12 -0600403 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200404 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200405 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (modules == NULL)
408 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* Delete some special variables first. These are common
411 places where user values hide and people complain when their
412 destructors fail. Since the modules containing them are
413 deleted *last* of all, they would come too late in the normal
414 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000415
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200416 /* XXX Perhaps these precautions are obsolete. Who knows? */
417
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200418 if (Py_VerboseFlag)
419 PySys_WriteStderr("# clear builtins._\n");
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300420 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300421 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300422 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200423
424 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200426 PySys_WriteStderr("# clear sys.%s\n", *p);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300427 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300428 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200431 for (p = sys_files; *p != NULL; p+=2) {
432 if (Py_VerboseFlag)
433 PySys_WriteStderr("# restore sys.%s\n", *p);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200434 value = _PyDict_GetItemStringWithError(interp->sysdict, *(p+1));
435 if (value == NULL) {
436 if (PyErr_Occurred()) {
437 PyErr_WriteUnraisable(NULL);
438 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200439 value = Py_None;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200440 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300441 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300442 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300443 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000445
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200446 /* We prepare a list which will receive (name, weakref) tuples of
447 modules when they are removed from sys.modules. The name is used
448 for diagnosis messages (in verbose mode), while the weakref helps
449 detect those modules which have been held alive. */
450 weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300451 if (weaklist == NULL) {
452 PyErr_WriteUnraisable(NULL);
453 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200454
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200455#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200456 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300458 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200459 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300460 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300461 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300462 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200463 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300464 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200465 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300466 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300467 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300468 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600470#define CLEAR_MODULE(name, mod) \
471 if (PyModule_Check(mod)) { \
472 if (Py_VerboseFlag && PyUnicode_Check(name)) \
473 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
474 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300475 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300476 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300477 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600478 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000479
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200480 /* Remove all modules from sys.modules, hoping that garbage collection
481 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600482 if (PyDict_CheckExact(modules)) {
483 pos = 0;
484 while (PyDict_Next(modules, &pos, &key, &value)) {
485 CLEAR_MODULE(key, value);
486 }
487 }
488 else {
489 PyObject *iterator = PyObject_GetIter(modules);
490 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300491 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600492 }
493 else {
494 while ((key = PyIter_Next(iterator))) {
495 value = PyObject_GetItem(modules, key);
496 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300497 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600498 continue;
499 }
500 CLEAR_MODULE(key, value);
501 Py_DECREF(value);
502 Py_DECREF(key);
503 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300504 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300505 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300506 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600507 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 }
509 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000510
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200511 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600512 if (PyDict_CheckExact(modules)) {
513 PyDict_Clear(modules);
514 }
515 else {
516 _Py_IDENTIFIER(clear);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300517 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
518 PyErr_WriteUnraisable(NULL);
519 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600520 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200521 /* Restore the original builtins dict, to ensure that any
522 user data gets cleared. */
523 dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300524 if (dict == NULL) {
525 PyErr_WriteUnraisable(NULL);
526 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200527 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300528 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200529 PyErr_Clear();
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300530 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200531 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200532 /* Clear module dict copies stored in the interpreter state */
533 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200534 /* Collect references */
535 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200536 /* Dump GC stats before it's too late, since it uses the warnings
537 machinery. */
Victor Stinner9db03242019-04-26 02:32:01 +0200538 _PyGC_DumpShutdownStats(&_PyRuntime);
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200539
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200540 /* Now, if there are any modules left alive, clear their globals to
541 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200542 up here, since they are kept alive in the interpreter state.
543
544 The special treatment of "builtins" here is because even
545 when it's not referenced as a module, its dictionary is
546 referenced by almost every module's __builtins__. Since
547 deleting a module clears its dictionary (even if there are
548 references left to it), we need to delete the "builtins"
549 module last. Likewise, we don't delete sys until the very
550 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200551 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200552 Py_ssize_t i;
553 /* Since dict is ordered in CPython 3.6+, modules are saved in
554 importing order. First clear modules imported later. */
555 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200556 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200557 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200558 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
559 if (mod == Py_None)
560 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200561 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200562 dict = PyModule_GetDict(mod);
563 if (dict == interp->builtins || dict == interp->sysdict)
564 continue;
565 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200566 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200567 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200568 _PyModule_Clear(mod);
569 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200570 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200571 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000573
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200574 /* Next, delete sys and builtins (in that order) */
575 if (Py_VerboseFlag)
576 PySys_FormatStderr("# cleanup[3] wiping sys\n");
577 _PyModule_ClearDict(interp->sysdict);
578 if (Py_VerboseFlag)
579 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
580 _PyModule_ClearDict(interp->builtins);
581
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200582 /* Clear and delete the modules directory. Actual modules will
583 still be there only if imported during the execution of some
584 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700585 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200587
588 /* Once more */
589 _PyGC_CollectNoFail();
590
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300591#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200592#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000593}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000594
595
Barry Warsaw28a691b2010-04-17 00:19:56 +0000596/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000597
598long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000599PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000600{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200601 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200602 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600603 PyObject *external, *pyc_magic;
604
605 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
606 if (external == NULL)
607 return -1;
608 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
609 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400610 if (pyc_magic == NULL)
611 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200612 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700613 Py_DECREF(pyc_magic);
614 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000615}
616
617
Brett Cannon3adc7b72012-07-09 14:22:12 -0400618extern const char * _PySys_ImplCacheTag;
619
Barry Warsaw28a691b2010-04-17 00:19:56 +0000620const char *
621PyImport_GetMagicTag(void)
622{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400623 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000624}
625
Brett Cannon98979b82012-07-02 15:13:11 -0400626
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627/* Magic for extension modules (built-in as well as dynamically
628 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200629 once, we keep a static dictionary 'extensions' keyed by the tuple
630 (module name, module name) (for built-in modules) or by
631 (filename, module name) (for dynamically loaded modules), containing these
632 modules. A copy of the module's dictionary is stored by calling
633 _PyImport_FixupExtensionObject() immediately after the module initialization
634 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100635 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000636
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000637 Modules which do support multiple initialization set their m_size
638 field to a non-negative number (indicating the size of the
639 module-specific state). They are still recorded in the extensions
640 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000641*/
642
643int
Victor Stinner95872862011-03-07 18:20:56 +0100644_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600645 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000646{
Eric Snowd393c1b2017-09-14 12:18:12 -0600647 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500649 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (extensions == NULL) {
651 extensions = PyDict_New();
652 if (extensions == NULL)
653 return -1;
654 }
655 if (mod == NULL || !PyModule_Check(mod)) {
656 PyErr_BadInternalCall();
657 return -1;
658 }
659 def = PyModule_GetDef(mod);
660 if (!def) {
661 PyErr_BadInternalCall();
662 return -1;
663 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600664 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 return -1;
666 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600667 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return -1;
669 }
670 if (def->m_size == -1) {
671 if (def->m_base.m_copy) {
672 /* Somebody already imported the module,
673 likely under a different name.
674 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200675 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 }
677 dict = PyModule_GetDict(mod);
678 if (dict == NULL)
679 return -1;
680 def->m_base.m_copy = PyDict_Copy(dict);
681 if (def->m_base.m_copy == NULL)
682 return -1;
683 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500684 key = PyTuple_Pack(2, filename, name);
685 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200686 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500687 res = PyDict_SetItem(extensions, key, (PyObject *)def);
688 Py_DECREF(key);
689 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200690 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000692}
693
Victor Stinner49d3f252010-10-17 01:24:53 +0000694int
Eric Snowd393c1b2017-09-14 12:18:12 -0600695_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000696{
697 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100698 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100699 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100700 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000701 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600702 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100703 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000704 return res;
705}
706
Guido van Rossum25ce5661997-08-02 03:10:38 +0000707PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100708_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000709{
Eric Snowd393c1b2017-09-14 12:18:12 -0600710 PyObject *modules = PyImport_GetModuleDict();
711 return _PyImport_FindExtensionObjectEx(name, filename, modules);
712}
713
714PyObject *
715_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
716 PyObject *modules)
717{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500718 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyModuleDef* def;
720 if (extensions == NULL)
721 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500722 key = PyTuple_Pack(2, filename, name);
723 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200724 return NULL;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200725 def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500726 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (def == NULL)
728 return NULL;
729 if (def->m_size == -1) {
730 /* Module does not support repeated initialization */
731 if (def->m_base.m_copy == NULL)
732 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600733 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (mod == NULL)
735 return NULL;
736 mdict = PyModule_GetDict(mod);
737 if (mdict == NULL)
738 return NULL;
739 if (PyDict_Update(mdict, def->m_base.m_copy))
740 return NULL;
741 }
742 else {
743 if (def->m_base.m_init == NULL)
744 return NULL;
745 mod = def->m_base.m_init();
746 if (mod == NULL)
747 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600748 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200749 Py_DECREF(mod);
750 return NULL;
751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 Py_DECREF(mod);
753 }
754 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600755 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return NULL;
757 }
758 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100759 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 name, filename);
761 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000762
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763}
764
Victor Stinner49d3f252010-10-17 01:24:53 +0000765PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600766_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000767{
Victor Stinner95872862011-03-07 18:20:56 +0100768 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100769 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100770 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000771 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600772 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100773 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000774 return res;
775}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000776
777/* Get the module object corresponding to a module name.
778 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000779 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000780 Because the former action is most common, THIS DOES NOT RETURN A
781 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000782
Guido van Rossum79f25d91997-04-29 20:08:16 +0000783PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000784PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600787 return _PyImport_AddModuleObject(name, modules);
788}
789
790PyObject *
791_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
792{
Eric Snow86b7afd2017-09-04 17:54:09 -0600793 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600794 if (PyDict_CheckExact(modules)) {
795 m = PyDict_GetItemWithError(modules, name);
796 }
797 else {
798 m = PyObject_GetItem(modules, name);
799 // For backward-comaptibility we copy the behavior
800 // of PyDict_GetItemWithError().
801 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
802 PyErr_Clear();
803 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200804 }
805 if (PyErr_Occurred()) {
806 return NULL;
807 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600808 if (m != NULL && PyModule_Check(m)) {
809 return m;
810 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000811 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (m == NULL)
813 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600814 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 Py_DECREF(m);
816 return NULL;
817 }
818 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000821}
822
Victor Stinner27ee0892011-03-04 12:57:09 +0000823PyObject *
824PyImport_AddModule(const char *name)
825{
826 PyObject *nameobj, *module;
827 nameobj = PyUnicode_FromString(name);
828 if (nameobj == NULL)
829 return NULL;
830 module = PyImport_AddModuleObject(nameobj);
831 Py_DECREF(nameobj);
832 return module;
833}
834
835
Tim Peters1cd70172004-08-02 03:52:12 +0000836/* Remove name from sys.modules, if it's there. */
837static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000838remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000839{
Zackery Spytz94a64e92019-05-08 10:31:23 -0600840 PyObject *type, *value, *traceback;
841 PyErr_Fetch(&type, &value, &traceback);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyObject *modules = PyImport_GetModuleDict();
Zackery Spytz94a64e92019-05-08 10:31:23 -0600843 if (!PyMapping_HasKey(modules, name)) {
844 goto out;
845 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600846 if (PyMapping_DelItem(modules, name) < 0) {
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200847 Py_FatalError("import: deleting existing key in "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600849 }
Zackery Spytz94a64e92019-05-08 10:31:23 -0600850out:
851 PyErr_Restore(type, value, traceback);
Tim Peters1cd70172004-08-02 03:52:12 +0000852}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000853
Christian Heimes3b06e532008-01-07 20:12:44 +0000854
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000855/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000856 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
857 * removed from sys.modules, to avoid leaving damaged module objects
858 * in sys.modules. The caller may wish to restore the original
859 * module object (if any) in this case; PyImport_ReloadModule is an
860 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000861 *
862 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
863 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000864 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000865PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300866PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return PyImport_ExecCodeModuleWithPathnames(
869 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000870}
871
872PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300873PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return PyImport_ExecCodeModuleWithPathnames(
876 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000877}
878
879PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300880PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
881 const char *pathname,
882 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000883{
Victor Stinner27ee0892011-03-04 12:57:09 +0000884 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600885 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000886
887 nameobj = PyUnicode_FromString(name);
888 if (nameobj == NULL)
889 return NULL;
890
Victor Stinner27ee0892011-03-04 12:57:09 +0000891 if (cpathname != NULL) {
892 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
893 if (cpathobj == NULL)
894 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400895 }
896 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000897 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400898
899 if (pathname != NULL) {
900 pathobj = PyUnicode_DecodeFSDefault(pathname);
901 if (pathobj == NULL)
902 goto error;
903 }
904 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200905 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400906 _Py_IDENTIFIER(_get_sourcefile);
907
908 if (interp == NULL) {
909 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
910 "no interpreter!");
911 }
912
Eric Snow32439d62015-05-02 19:15:18 -0600913 external= PyObject_GetAttrString(interp->importlib,
914 "_bootstrap_external");
915 if (external != NULL) {
916 pathobj = _PyObject_CallMethodIdObjArgs(external,
917 &PyId__get_sourcefile, cpathobj,
918 NULL);
919 Py_DECREF(external);
920 }
Brett Cannona6473f92012-07-13 13:57:03 -0400921 if (pathobj == NULL)
922 PyErr_Clear();
923 }
924 else
925 pathobj = NULL;
926
Victor Stinner27ee0892011-03-04 12:57:09 +0000927 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
928error:
929 Py_DECREF(nameobj);
930 Py_XDECREF(pathobj);
931 Py_XDECREF(cpathobj);
932 return m;
933}
934
Brett Cannon18fc4e72014-04-04 10:01:46 -0400935static PyObject *
936module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000937{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200938 _Py_IDENTIFIER(__builtins__);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400939 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000940
Victor Stinner27ee0892011-03-04 12:57:09 +0000941 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (m == NULL)
943 return NULL;
944 /* If the module is being reloaded, we get the old module back
945 and re-use its dict to exec the new code. */
946 d = PyModule_GetDict(m);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200947 if (_PyDict_GetItemIdWithError(d, &PyId___builtins__) == NULL) {
948 if (PyErr_Occurred() ||
949 _PyDict_SetItemId(d, &PyId___builtins__,
950 PyEval_GetBuiltins()) != 0)
951 {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400952 remove_module(name);
953 return NULL;
954 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400956
Eric Snow08197a42014-05-12 17:54:55 -0600957 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400958}
959
960static PyObject *
961exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
962{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400963 PyObject *v, *m;
964
965 v = PyEval_EvalCode(code_object, module_dict, module_dict);
966 if (v == NULL) {
967 remove_module(name);
968 return NULL;
969 }
970 Py_DECREF(v);
971
Eric Snow3f9eee62017-09-15 16:35:20 -0600972 m = PyImport_GetModule(name);
Stefan Krah027b09c2019-03-25 21:50:58 +0100973 if (m == NULL && !PyErr_Occurred()) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400974 PyErr_Format(PyExc_ImportError,
975 "Loaded module %R not found in sys.modules",
976 name);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400977 }
978
Brett Cannon18fc4e72014-04-04 10:01:46 -0400979 return m;
980}
981
982PyObject*
983PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
984 PyObject *cpathname)
985{
Eric Snow32439d62015-05-02 19:15:18 -0600986 PyObject *d, *external, *res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200987 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow08197a42014-05-12 17:54:55 -0600988 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400989
990 d = module_dict_for_exec(name);
991 if (d == NULL) {
992 return NULL;
993 }
994
Eric Snow08197a42014-05-12 17:54:55 -0600995 if (pathname == NULL) {
996 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
Eric Snow32439d62015-05-02 19:15:18 -0600998 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
999 if (external == NULL)
1000 return NULL;
1001 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -06001002 &PyId__fix_up_module,
1003 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -06001004 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -06001005 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -06001006 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -06001007 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 }
Eric Snow08197a42014-05-12 17:54:55 -06001009 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001010}
1011
1012
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001013static void
1014update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PyObject *constants, *tmp;
1017 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (PyUnicode_Compare(co->co_filename, oldname))
1020 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001021
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001022 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001023 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 constants = co->co_consts;
1026 n = PyTuple_GET_SIZE(constants);
1027 for (i = 0; i < n; i++) {
1028 tmp = PyTuple_GET_ITEM(constants, i);
1029 if (PyCode_Check(tmp))
1030 update_code_filenames((PyCodeObject *)tmp,
1031 oldname, newname);
1032 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001033}
1034
Victor Stinner2f42ae52011-03-20 00:41:24 +01001035static void
1036update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001037{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001038 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001039
Victor Stinner2f42ae52011-03-20 00:41:24 +01001040 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1041 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 oldname = co->co_filename;
1044 Py_INCREF(oldname);
1045 update_code_filenames(co, oldname, newname);
1046 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001047}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048
Brett Cannon4caa61d2014-01-09 19:03:32 -05001049/*[clinic input]
1050_imp._fix_co_filename
1051
1052 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1053 Code object to change.
1054
1055 path: unicode
1056 File path to use.
1057 /
1058
1059Changes code.co_filename to specify the passed-in file path.
1060[clinic start generated code]*/
1061
Brett Cannon4caa61d2014-01-09 19:03:32 -05001062static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001063_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001064 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001065/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001066
Brett Cannon4caa61d2014-01-09 19:03:32 -05001067{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001068 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001069
1070 Py_RETURN_NONE;
1071}
1072
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001073
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001074/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001075static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001076
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001077
1078/* Helper to test for built-in module */
1079
1080static int
Victor Stinner95872862011-03-07 18:20:56 +01001081is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001082{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001083 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001085 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 if (PyImport_Inittab[i].initfunc == NULL)
1087 return -1;
1088 else
1089 return 1;
1090 }
1091 }
1092 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001093}
1094
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001095
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001096/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001097 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001098 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001099 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001100 this tells our caller that the path based finder could not find
1101 a finder for this path item. Cache the result in
1102 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001103 Returns a borrowed reference. */
1104
1105static PyObject *
1106get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject *importer;
1110 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* These conditions are the caller's responsibility: */
1113 assert(PyList_Check(path_hooks));
1114 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 nhooks = PyList_Size(path_hooks);
1117 if (nhooks < 0)
1118 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001119
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001120 importer = PyDict_GetItemWithError(path_importer_cache, p);
1121 if (importer != NULL || PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* set path_importer_cache[p] to None to avoid recursion */
1125 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1126 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 for (j = 0; j < nhooks; j++) {
1129 PyObject *hook = PyList_GetItem(path_hooks, j);
1130 if (hook == NULL)
1131 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001132 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (importer != NULL)
1134 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1137 return NULL;
1138 }
1139 PyErr_Clear();
1140 }
1141 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001142 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 }
1144 if (importer != NULL) {
1145 int err = PyDict_SetItem(path_importer_cache, p, importer);
1146 Py_DECREF(importer);
1147 if (err != 0)
1148 return NULL;
1149 }
1150 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001151}
1152
Benjamin Petersone5024512018-09-12 12:06:42 -07001153PyObject *
Christian Heimes9cd17752007-11-18 19:35:23 +00001154PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001156
Victor Stinner1e53bba2013-07-16 22:26:05 +02001157 path_importer_cache = PySys_GetObject("path_importer_cache");
1158 path_hooks = PySys_GetObject("path_hooks");
1159 if (path_importer_cache != NULL && path_hooks != NULL) {
1160 importer = get_path_importer(path_importer_cache,
1161 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 }
1163 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1164 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001165}
1166
Nick Coghland5cacbb2015-05-23 22:24:10 +10001167/*[clinic input]
1168_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001169
Nick Coghland5cacbb2015-05-23 22:24:10 +10001170 spec: object
1171 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001172
Nick Coghland5cacbb2015-05-23 22:24:10 +10001173Create an extension module.
1174[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001175
Nick Coghland5cacbb2015-05-23 22:24:10 +10001176static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001177_imp_create_builtin(PyObject *module, PyObject *spec)
1178/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001181 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001182 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001183 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001184
Nick Coghland5cacbb2015-05-23 22:24:10 +10001185 name = PyObject_GetAttrString(spec, "name");
1186 if (name == NULL) {
1187 return NULL;
1188 }
1189
Victor Stinner5eb4f592013-11-14 22:38:52 +01001190 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001191 if (mod || PyErr_Occurred()) {
1192 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001193 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001194 return mod;
1195 }
1196
1197 namestr = PyUnicode_AsUTF8(name);
1198 if (namestr == NULL) {
1199 Py_DECREF(name);
1200 return NULL;
1201 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001202
Eric Snowd393c1b2017-09-14 12:18:12 -06001203 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001205 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001206 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001208 /* Cannot re-init internal module ("sys" or "builtins") */
1209 mod = PyImport_AddModule(namestr);
1210 Py_DECREF(name);
1211 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001214 if (mod == NULL) {
1215 Py_DECREF(name);
1216 return NULL;
1217 }
1218 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1219 Py_DECREF(name);
1220 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1221 } else {
1222 /* Remember pointer to module init function. */
1223 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001224 if (def == NULL) {
1225 Py_DECREF(name);
1226 return NULL;
1227 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001228 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001229 if (modules == NULL) {
1230 modules = PyImport_GetModuleDict();
1231 }
1232 if (_PyImport_FixupExtensionObject(mod, name, name,
1233 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001234 Py_DECREF(name);
1235 return NULL;
1236 }
1237 Py_DECREF(name);
1238 return mod;
1239 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 }
1241 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001242 Py_DECREF(name);
1243 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001244}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001245
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001247/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001248
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001249static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001250find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001251{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001252 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001253
Victor Stinner53dc7352011-03-20 01:50:21 +01001254 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 for (p = PyImport_FrozenModules; ; p++) {
1258 if (p->name == NULL)
1259 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001260 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 break;
1262 }
1263 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001264}
1265
Guido van Rossum79f25d91997-04-29 20:08:16 +00001266static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001267get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001268{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001269 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (p == NULL) {
1273 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001274 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 name);
1276 return NULL;
1277 }
1278 if (p->code == NULL) {
1279 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001280 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 name);
1282 return NULL;
1283 }
1284 size = p->size;
1285 if (size < 0)
1286 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001287 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001288}
1289
Brett Cannon8d110132009-03-15 02:20:16 +00001290static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001291is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001292{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001293 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (p == NULL) {
1297 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001298 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 name);
1300 return NULL;
1301 }
Brett Cannon8d110132009-03-15 02:20:16 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (size < 0)
1306 Py_RETURN_TRUE;
1307 else
1308 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001309}
1310
1311
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001312/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001313 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001314 an exception set if the initialization failed.
1315 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001316
1317int
Victor Stinner53dc7352011-03-20 01:50:21 +01001318PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001319{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001320 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001321 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 int ispackage;
1323 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001324
Victor Stinner53dc7352011-03-20 01:50:21 +01001325 p = find_frozen(name);
1326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (p == NULL)
1328 return 0;
1329 if (p->code == NULL) {
1330 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001331 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 name);
1333 return -1;
1334 }
1335 size = p->size;
1336 ispackage = (size < 0);
1337 if (ispackage)
1338 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001339 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (co == NULL)
1341 return -1;
1342 if (!PyCode_Check(co)) {
1343 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001344 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 name);
1346 goto err_return;
1347 }
1348 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001349 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001350 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001352 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (m == NULL)
1354 goto err_return;
1355 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001356 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 goto err_return;
1359 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 err = PyDict_SetItemString(d, "__path__", l);
1361 Py_DECREF(l);
1362 if (err != 0)
1363 goto err_return;
1364 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001365 d = module_dict_for_exec(name);
1366 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001367 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001368 }
1369 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 if (m == NULL)
1371 goto err_return;
1372 Py_DECREF(co);
1373 Py_DECREF(m);
1374 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001375err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 Py_DECREF(co);
1377 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001378}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001379
Victor Stinner53dc7352011-03-20 01:50:21 +01001380int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001381PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001382{
1383 PyObject *nameobj;
1384 int ret;
1385 nameobj = PyUnicode_InternFromString(name);
1386 if (nameobj == NULL)
1387 return -1;
1388 ret = PyImport_ImportFrozenModuleObject(nameobj);
1389 Py_DECREF(nameobj);
1390 return ret;
1391}
1392
Guido van Rossum74e6a111994-08-29 12:54:38 +00001393
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001394/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001395 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001396
Guido van Rossum79f25d91997-04-29 20:08:16 +00001397PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001398PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 PyObject *pname;
1401 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 pname = PyUnicode_FromString(name);
1404 if (pname == NULL)
1405 return NULL;
1406 result = PyImport_Import(pname);
1407 Py_DECREF(pname);
1408 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001409}
1410
Christian Heimes072c0f12008-01-03 23:01:04 +00001411/* Import a module without blocking
1412 *
1413 * At first it tries to fetch the module from sys.modules. If the module was
1414 * never loaded before it loads it with PyImport_ImportModule() unless another
1415 * thread holds the import lock. In the latter case the function raises an
1416 * ImportError instead of blocking.
1417 *
1418 * Returns the module object with incremented ref count.
1419 */
1420PyObject *
1421PyImport_ImportModuleNoBlock(const char *name)
1422{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001423 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001424}
1425
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001426
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001427/* Remove importlib frames from the traceback,
1428 * except in Verbose mode. */
1429static void
1430remove_importlib_frames(void)
1431{
1432 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001433 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001434 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001435 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001436 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001437 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001438 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001439
1440 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001441 from the traceback. We always trim chunks
1442 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001443
1444 PyErr_Fetch(&exception, &value, &base_tb);
1445 if (!exception || Py_VerboseFlag)
1446 goto done;
1447 if (PyType_IsSubtype((PyTypeObject *) exception,
1448 (PyTypeObject *) PyExc_ImportError))
1449 always_trim = 1;
1450
1451 prev_link = &base_tb;
1452 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001453 while (tb != NULL) {
1454 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1455 PyObject *next = (PyObject *) traceback->tb_next;
1456 PyFrameObject *frame = traceback->tb_frame;
1457 PyCodeObject *code = frame->f_code;
1458 int now_in_importlib;
1459
1460 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001461 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1462 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001463 if (now_in_importlib && !in_importlib) {
1464 /* This is the link to this chunk of importlib tracebacks */
1465 outer_link = prev_link;
1466 }
1467 in_importlib = now_in_importlib;
1468
1469 if (in_importlib &&
1470 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001471 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001472 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001473 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001474 prev_link = outer_link;
1475 }
1476 else {
1477 prev_link = (PyObject **) &traceback->tb_next;
1478 }
1479 tb = next;
1480 }
1481done:
1482 PyErr_Restore(exception, value, base_tb);
1483}
1484
1485
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001486static PyObject *
1487resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001488{
Eric Snowb523f842013-11-22 09:05:39 -07001489 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001490 _Py_IDENTIFIER(__package__);
1491 _Py_IDENTIFIER(__path__);
1492 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001493 _Py_IDENTIFIER(parent);
1494 PyObject *abs_name;
1495 PyObject *package = NULL;
1496 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001497 Py_ssize_t last_dot;
1498 PyObject *base;
1499 int level_up;
1500
1501 if (globals == NULL) {
1502 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1503 goto error;
1504 }
1505 if (!PyDict_Check(globals)) {
1506 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1507 goto error;
1508 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001509 package = _PyDict_GetItemIdWithError(globals, &PyId___package__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001510 if (package == Py_None) {
1511 package = NULL;
1512 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001513 else if (package == NULL && PyErr_Occurred()) {
1514 goto error;
1515 }
1516 spec = _PyDict_GetItemIdWithError(globals, &PyId___spec__);
1517 if (spec == NULL && PyErr_Occurred()) {
1518 goto error;
1519 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001520
1521 if (package != NULL) {
1522 Py_INCREF(package);
1523 if (!PyUnicode_Check(package)) {
1524 PyErr_SetString(PyExc_TypeError, "package must be a string");
1525 goto error;
1526 }
1527 else if (spec != NULL && spec != Py_None) {
1528 int equal;
1529 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1530 if (parent == NULL) {
1531 goto error;
1532 }
1533
1534 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1535 Py_DECREF(parent);
1536 if (equal < 0) {
1537 goto error;
1538 }
1539 else if (equal == 0) {
1540 if (PyErr_WarnEx(PyExc_ImportWarning,
1541 "__package__ != __spec__.parent", 1) < 0) {
1542 goto error;
1543 }
1544 }
1545 }
1546 }
1547 else if (spec != NULL && spec != Py_None) {
1548 package = _PyObject_GetAttrId(spec, &PyId_parent);
1549 if (package == NULL) {
1550 goto error;
1551 }
1552 else if (!PyUnicode_Check(package)) {
1553 PyErr_SetString(PyExc_TypeError,
1554 "__spec__.parent must be a string");
1555 goto error;
1556 }
1557 }
1558 else {
1559 if (PyErr_WarnEx(PyExc_ImportWarning,
1560 "can't resolve package from __spec__ or __package__, "
1561 "falling back on __name__ and __path__", 1) < 0) {
1562 goto error;
1563 }
1564
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001565 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001566 if (package == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001567 if (!PyErr_Occurred()) {
1568 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1569 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001570 goto error;
1571 }
1572
1573 Py_INCREF(package);
1574 if (!PyUnicode_Check(package)) {
1575 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1576 goto error;
1577 }
1578
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001579 if (_PyDict_GetItemIdWithError(globals, &PyId___path__) == NULL) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001580 Py_ssize_t dot;
1581
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001582 if (PyErr_Occurred() || PyUnicode_READY(package) < 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001583 goto error;
1584 }
1585
1586 dot = PyUnicode_FindChar(package, '.',
1587 0, PyUnicode_GET_LENGTH(package), -1);
1588 if (dot == -2) {
1589 goto error;
1590 }
1591
1592 if (dot >= 0) {
1593 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1594 if (substr == NULL) {
1595 goto error;
1596 }
1597 Py_SETREF(package, substr);
1598 }
1599 }
1600 }
1601
1602 last_dot = PyUnicode_GET_LENGTH(package);
1603 if (last_dot == 0) {
1604 PyErr_SetString(PyExc_ImportError,
1605 "attempted relative import with no known parent package");
1606 goto error;
1607 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001608
1609 for (level_up = 1; level_up < level; level_up += 1) {
1610 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1611 if (last_dot == -2) {
1612 goto error;
1613 }
1614 else if (last_dot == -1) {
1615 PyErr_SetString(PyExc_ValueError,
1616 "attempted relative import beyond top-level "
1617 "package");
1618 goto error;
1619 }
1620 }
1621
1622 base = PyUnicode_Substring(package, 0, last_dot);
1623 Py_DECREF(package);
1624 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1625 return base;
1626 }
1627
1628 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1629 Py_DECREF(base);
1630 return abs_name;
1631
1632 error:
1633 Py_XDECREF(package);
1634 return NULL;
1635}
1636
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001637static PyObject *
1638import_find_and_load(PyObject *abs_name)
1639{
1640 _Py_IDENTIFIER(_find_and_load);
1641 PyObject *mod = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001642 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001643 int import_time = interp->core_config.import_time;
1644 static int import_level;
1645 static _PyTime_t accumulated;
1646
1647 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1648
1649 /* XOptions is initialized after first some imports.
1650 * So we can't have negative cache before completed initialization.
1651 * Anyway, importlib._find_and_load is much slower than
1652 * _PyDict_GetItemIdWithError().
1653 */
1654 if (import_time) {
1655 static int header = 1;
1656 if (header) {
1657 fputs("import time: self [us] | cumulative | imported package\n",
1658 stderr);
1659 header = 0;
1660 }
1661
1662 import_level++;
1663 t1 = _PyTime_GetPerfCounter();
1664 accumulated = 0;
1665 }
1666
1667 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1668 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1669
1670 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1671 &PyId__find_and_load, abs_name,
1672 interp->import_func, NULL);
1673
1674 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1675 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1676 mod != NULL);
1677
1678 if (import_time) {
1679 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1680
1681 import_level--;
1682 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1683 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1684 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1685 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1686
1687 accumulated = accumulated_copy + cum;
1688 }
1689
1690 return mod;
1691}
1692
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001693PyObject *
1694PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1695 PyObject *locals, PyObject *fromlist,
1696 int level)
1697{
Brett Cannonfd074152012-04-14 14:10:13 -04001698 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001699 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001700 PyObject *final_mod = NULL;
1701 PyObject *mod = NULL;
1702 PyObject *package = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001703 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001704 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001705
Brett Cannonfd074152012-04-14 14:10:13 -04001706 if (name == NULL) {
1707 PyErr_SetString(PyExc_ValueError, "Empty module name");
1708 goto error;
1709 }
1710
1711 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1712 for added performance. */
1713
1714 if (!PyUnicode_Check(name)) {
1715 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1716 goto error;
1717 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001718 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001719 goto error;
1720 }
1721 if (level < 0) {
1722 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1723 goto error;
1724 }
Brett Cannon849113a2016-01-22 15:25:50 -08001725
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001726 if (level > 0) {
1727 abs_name = resolve_name(name, globals, level);
1728 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001729 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001730 }
1731 else { /* level == 0 */
1732 if (PyUnicode_GET_LENGTH(name) == 0) {
1733 PyErr_SetString(PyExc_ValueError, "Empty module name");
1734 goto error;
1735 }
Brett Cannonfd074152012-04-14 14:10:13 -04001736 abs_name = name;
1737 Py_INCREF(abs_name);
1738 }
1739
Eric Snow3f9eee62017-09-15 16:35:20 -06001740 mod = PyImport_GetModule(abs_name);
Stefan Krah027b09c2019-03-25 21:50:58 +01001741 if (mod == NULL && PyErr_Occurred()) {
1742 goto error;
1743 }
1744
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001745 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001746 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001747 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001748 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001749
Antoine Pitrou03989852012-08-28 00:24:52 +02001750 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001751 __spec__._initializing is true.
1752 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001753 stuffing the new module in sys.modules.
1754 */
Eric Snowb523f842013-11-22 09:05:39 -07001755 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001756 if (_PyModuleSpec_IsInitializing(spec)) {
1757 PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1758 &PyId__lock_unlock_module, abs_name,
1759 NULL);
1760 if (value == NULL) {
1761 Py_DECREF(spec);
1762 goto error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001763 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001764 Py_DECREF(value);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001765 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001766 Py_XDECREF(spec);
Brett Cannonfd074152012-04-14 14:10:13 -04001767 }
1768 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001769 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001770 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001771 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001772 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001773 }
1774 }
1775
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001776 has_from = 0;
1777 if (fromlist != NULL && fromlist != Py_None) {
1778 has_from = PyObject_IsTrue(fromlist);
1779 if (has_from < 0)
1780 goto error;
1781 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001782 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001783 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1784 if (level == 0 || len > 0) {
1785 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001786
Victor Stinner744c34e2016-05-20 11:36:13 +02001787 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1788 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001789 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001790 }
1791
Victor Stinner744c34e2016-05-20 11:36:13 +02001792 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001793 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001794 final_mod = mod;
1795 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001796 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001797 }
1798
Brett Cannonfd074152012-04-14 14:10:13 -04001799 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001800 PyObject *front = PyUnicode_Substring(name, 0, dot);
1801 if (front == NULL) {
1802 goto error;
1803 }
1804
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001805 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001806 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001807 }
1808 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001809 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001810 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001811 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001812 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001813 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001814 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001815 }
Brett Cannonfd074152012-04-14 14:10:13 -04001816
Eric Snow3f9eee62017-09-15 16:35:20 -06001817 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001818 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001819 if (final_mod == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001820 if (!PyErr_Occurred()) {
1821 PyErr_Format(PyExc_KeyError,
1822 "%R not in sys.modules as expected",
1823 to_return);
1824 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001825 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001826 }
Brett Cannonfd074152012-04-14 14:10:13 -04001827 }
1828 }
1829 else {
1830 final_mod = mod;
1831 Py_INCREF(mod);
1832 }
1833 }
1834 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001835 _Py_IDENTIFIER(__path__);
1836 PyObject *path;
1837 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1838 goto error;
1839 }
1840 if (path) {
1841 Py_DECREF(path);
1842 final_mod = _PyObject_CallMethodIdObjArgs(
1843 interp->importlib, &PyId__handle_fromlist,
1844 mod, fromlist, interp->import_func, NULL);
1845 }
1846 else {
1847 final_mod = mod;
1848 Py_INCREF(mod);
1849 }
Brett Cannonfd074152012-04-14 14:10:13 -04001850 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001851
Brett Cannonfd074152012-04-14 14:10:13 -04001852 error:
1853 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001854 Py_XDECREF(mod);
1855 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001856 if (final_mod == NULL)
1857 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001858 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001859}
1860
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001861PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001862PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001863 PyObject *fromlist, int level)
1864{
1865 PyObject *nameobj, *mod;
1866 nameobj = PyUnicode_FromString(name);
1867 if (nameobj == NULL)
1868 return NULL;
1869 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1870 fromlist, level);
1871 Py_DECREF(nameobj);
1872 return mod;
1873}
1874
1875
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001876/* Re-import a module of any kind and return its module object, WITH
1877 INCREMENTED REFERENCE COUNT */
1878
Guido van Rossum79f25d91997-04-29 20:08:16 +00001879PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001880PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001881{
Eric Snow3f9eee62017-09-15 16:35:20 -06001882 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001883 _Py_IDENTIFIER(reload);
1884 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001885 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001886 if (imp == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01001887 if (PyErr_Occurred()) {
1888 return NULL;
1889 }
1890
Brett Cannon62228db2012-04-29 14:38:11 -04001891 imp = PyImport_ImportModule("imp");
1892 if (imp == NULL) {
1893 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001896
Victor Stinner55ba38a2016-12-09 16:09:30 +01001897 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001898 Py_DECREF(imp);
1899 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001900}
1901
1902
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001903/* Higher-level import emulator which emulates the "import" statement
1904 more accurately -- it invokes the __import__() function from the
1905 builtins of the current globals. This means that the import is
1906 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001907 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001908 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001909 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001910 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001911
1912PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001913PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 static PyObject *silly_list = NULL;
1916 static PyObject *builtins_str = NULL;
1917 static PyObject *import_str = NULL;
1918 PyObject *globals = NULL;
1919 PyObject *import = NULL;
1920 PyObject *builtins = NULL;
1921 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 /* Initialize constant string objects */
1924 if (silly_list == NULL) {
1925 import_str = PyUnicode_InternFromString("__import__");
1926 if (import_str == NULL)
1927 return NULL;
1928 builtins_str = PyUnicode_InternFromString("__builtins__");
1929 if (builtins_str == NULL)
1930 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001931 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 if (silly_list == NULL)
1933 return NULL;
1934 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* Get the builtins from current globals */
1937 globals = PyEval_GetGlobals();
1938 if (globals != NULL) {
1939 Py_INCREF(globals);
1940 builtins = PyObject_GetItem(globals, builtins_str);
1941 if (builtins == NULL)
1942 goto err;
1943 }
1944 else {
1945 /* No globals -- use standard builtins, and fake globals */
1946 builtins = PyImport_ImportModuleLevel("builtins",
1947 NULL, NULL, NULL, 0);
1948 if (builtins == NULL)
1949 return NULL;
1950 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1951 if (globals == NULL)
1952 goto err;
1953 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 /* Get the __import__ function from the builtins */
1956 if (PyDict_Check(builtins)) {
1957 import = PyObject_GetItem(builtins, import_str);
1958 if (import == NULL)
1959 PyErr_SetObject(PyExc_KeyError, import_str);
1960 }
1961 else
1962 import = PyObject_GetAttr(builtins, import_str);
1963 if (import == NULL)
1964 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001967 Always use absolute import here.
1968 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1970 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001971 if (r == NULL)
1972 goto err;
1973 Py_DECREF(r);
1974
Eric Snow3f9eee62017-09-15 16:35:20 -06001975 r = PyImport_GetModule(module_name);
1976 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001977 PyErr_SetObject(PyExc_KeyError, module_name);
1978 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001979
1980 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 Py_XDECREF(globals);
1982 Py_XDECREF(builtins);
1983 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001986}
1987
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988/*[clinic input]
1989_imp.extension_suffixes
1990
1991Returns the list of file suffixes used to identify extension modules.
1992[clinic start generated code]*/
1993
Brett Cannon4caa61d2014-01-09 19:03:32 -05001994static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001995_imp_extension_suffixes_impl(PyObject *module)
1996/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 list = PyList_New(0);
2001 if (list == NULL)
2002 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04002003#ifdef HAVE_DYNAMIC_LOADING
Stéphane Wirtel0d765e32019-03-20 00:37:20 +01002004 const char *suffix;
2005 unsigned int index = 0;
2006
Brett Cannon2657df42012-05-04 15:20:40 -04002007 while ((suffix = _PyImport_DynLoadFiletab[index])) {
2008 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (item == NULL) {
2010 Py_DECREF(list);
2011 return NULL;
2012 }
2013 if (PyList_Append(list, item) < 0) {
2014 Py_DECREF(list);
2015 Py_DECREF(item);
2016 return NULL;
2017 }
2018 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04002019 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
Brett Cannon2657df42012-05-04 15:20:40 -04002021#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002023}
2024
Brett Cannon4caa61d2014-01-09 19:03:32 -05002025/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05002026_imp.init_frozen
2027
2028 name: unicode
2029 /
2030
2031Initializes a frozen module.
2032[clinic start generated code]*/
2033
Brett Cannon4caa61d2014-01-09 19:03:32 -05002034static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002035_imp_init_frozen_impl(PyObject *module, PyObject *name)
2036/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 int ret;
2039 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002040
Victor Stinner53dc7352011-03-20 01:50:21 +01002041 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (ret < 0)
2043 return NULL;
2044 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002045 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002047 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 Py_XINCREF(m);
2049 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002050}
2051
Brett Cannon4caa61d2014-01-09 19:03:32 -05002052/*[clinic input]
2053_imp.get_frozen_object
2054
2055 name: unicode
2056 /
2057
2058Create a code object for a frozen module.
2059[clinic start generated code]*/
2060
Brett Cannon4caa61d2014-01-09 19:03:32 -05002061static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002062_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2063/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002066}
2067
Brett Cannon4caa61d2014-01-09 19:03:32 -05002068/*[clinic input]
2069_imp.is_frozen_package
2070
2071 name: unicode
2072 /
2073
2074Returns True if the module name is of a frozen package.
2075[clinic start generated code]*/
2076
Brett Cannon4caa61d2014-01-09 19:03:32 -05002077static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002078_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2079/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002082}
2083
Brett Cannon4caa61d2014-01-09 19:03:32 -05002084/*[clinic input]
2085_imp.is_builtin
2086
2087 name: unicode
2088 /
2089
2090Returns True if the module name corresponds to a built-in module.
2091[clinic start generated code]*/
2092
Guido van Rossum79f25d91997-04-29 20:08:16 +00002093static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002094_imp_is_builtin_impl(PyObject *module, PyObject *name)
2095/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002096{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002097 return PyLong_FromLong(is_builtin(name));
2098}
2099
2100/*[clinic input]
2101_imp.is_frozen
2102
2103 name: unicode
2104 /
2105
2106Returns True if the module name corresponds to a frozen module.
2107[clinic start generated code]*/
2108
Brett Cannon4caa61d2014-01-09 19:03:32 -05002109static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002110_imp_is_frozen_impl(PyObject *module, PyObject *name)
2111/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002112{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002113 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 p = find_frozen(name);
2116 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002117}
2118
Larry Hastings1df0b352015-08-24 19:53:56 -07002119/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2120static int
2121exec_builtin_or_dynamic(PyObject *mod) {
2122 PyModuleDef *def;
2123 void *state;
2124
2125 if (!PyModule_Check(mod)) {
2126 return 0;
2127 }
2128
2129 def = PyModule_GetDef(mod);
2130 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002131 return 0;
2132 }
Brett Cannon52794db2016-09-07 17:00:43 -07002133
Larry Hastings1df0b352015-08-24 19:53:56 -07002134 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002135 if (state) {
2136 /* Already initialized; skip reload */
2137 return 0;
2138 }
Brett Cannon52794db2016-09-07 17:00:43 -07002139
Larry Hastings1df0b352015-08-24 19:53:56 -07002140 return PyModule_ExecDef(mod, def);
2141}
2142
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002143#ifdef HAVE_DYNAMIC_LOADING
2144
Brett Cannon4caa61d2014-01-09 19:03:32 -05002145/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002146_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002147
Nick Coghland5cacbb2015-05-23 22:24:10 +10002148 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002149 file: object = NULL
2150 /
2151
Nick Coghland5cacbb2015-05-23 22:24:10 +10002152Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002153[clinic start generated code]*/
2154
Brett Cannon4caa61d2014-01-09 19:03:32 -05002155static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002156_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2157/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002158{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002159 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002160 FILE *fp;
2161
Nick Coghland5cacbb2015-05-23 22:24:10 +10002162 name = PyObject_GetAttrString(spec, "name");
2163 if (name == NULL) {
2164 return NULL;
2165 }
2166
2167 path = PyObject_GetAttrString(spec, "origin");
2168 if (path == NULL) {
2169 Py_DECREF(name);
2170 return NULL;
2171 }
2172
2173 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002174 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002175 Py_DECREF(name);
2176 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002177 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002178 return mod;
2179 }
2180
Brett Cannon4caa61d2014-01-09 19:03:32 -05002181 if (file != NULL) {
2182 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002183 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002184 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002185 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002189 else
2190 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002191
2192 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2193
2194 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002195 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 if (fp)
2197 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002198 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002199}
2200
Nick Coghland5cacbb2015-05-23 22:24:10 +10002201/*[clinic input]
2202_imp.exec_dynamic -> int
2203
2204 mod: object
2205 /
2206
2207Initialize an extension module.
2208[clinic start generated code]*/
2209
2210static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002211_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2212/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002213{
Larry Hastings1df0b352015-08-24 19:53:56 -07002214 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002215}
2216
2217
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002218#endif /* HAVE_DYNAMIC_LOADING */
2219
Larry Hastings7726ac92014-01-31 22:03:12 -08002220/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002221_imp.exec_builtin -> int
2222
2223 mod: object
2224 /
2225
2226Initialize a built-in module.
2227[clinic start generated code]*/
2228
2229static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002230_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2231/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002232{
2233 return exec_builtin_or_dynamic(mod);
2234}
2235
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002236/*[clinic input]
2237_imp.source_hash
2238
2239 key: long
2240 source: Py_buffer
2241[clinic start generated code]*/
2242
2243static PyObject *
2244_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2245/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2246{
Benjamin Peterson83620772017-12-09 12:18:56 -08002247 union {
2248 uint64_t x;
2249 char data[sizeof(uint64_t)];
2250 } hash;
2251 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002252#if !PY_LITTLE_ENDIAN
2253 // Force to little-endian. There really ought to be a succinct standard way
2254 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002255 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2256 char tmp = hash.data[i];
2257 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2258 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002259 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002260#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002261 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002262}
2263
Barry Warsaw28a691b2010-04-17 00:19:56 +00002264
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002265PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002266"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002267
Guido van Rossum79f25d91997-04-29 20:08:16 +00002268static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002269 _IMP_EXTENSION_SUFFIXES_METHODDEF
2270 _IMP_LOCK_HELD_METHODDEF
2271 _IMP_ACQUIRE_LOCK_METHODDEF
2272 _IMP_RELEASE_LOCK_METHODDEF
2273 _IMP_GET_FROZEN_OBJECT_METHODDEF
2274 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002275 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002276 _IMP_INIT_FROZEN_METHODDEF
2277 _IMP_IS_BUILTIN_METHODDEF
2278 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002279 _IMP_CREATE_DYNAMIC_METHODDEF
2280 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002281 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002282 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002283 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002284 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002285};
2286
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002287
Martin v. Löwis1a214512008-06-11 05:26:20 +00002288static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002290 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 doc_imp,
2292 0,
2293 imp_methods,
2294 NULL,
2295 NULL,
2296 NULL,
2297 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002298};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002299
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002300PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002301PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 m = PyModule_Create(&impmodule);
2306 if (m == NULL)
2307 goto failure;
2308 d = PyModule_GetDict(m);
2309 if (d == NULL)
2310 goto failure;
Victor Stinnercaba55b2018-08-03 15:33:52 +02002311 _PyCoreConfig *config = &_PyInterpreterState_Get()->core_config;
Victor Stinnercb9fbd32019-05-01 23:51:56 -04002312 PyObject *pyc_mode = PyUnicode_FromWideChar(config->check_hash_pycs_mode, -1);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002313 if (pyc_mode == NULL) {
2314 goto failure;
2315 }
2316 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2317 Py_DECREF(pyc_mode);
2318 goto failure;
2319 }
2320 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002323 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 Py_XDECREF(m);
2325 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002326}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002327
2328
Guido van Rossumb18618d2000-05-03 23:44:39 +00002329/* API for embedding applications that want to add their own entries
2330 to the table of built-in modules. This should normally be called
2331 *before* Py_Initialize(). When the table resize fails, -1 is
2332 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002333
2334 After a similar function by Just van Rossum. */
2335
2336int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002337PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002340 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002341 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* Count the number of entries in both tables */
2344 for (n = 0; newtab[n].name != NULL; n++)
2345 ;
2346 if (n == 0)
2347 return 0; /* Nothing to do */
2348 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2349 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002350
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002351 /* Force default raw memory allocator to get a known allocator to be able
2352 to release the memory in _PyImport_Fini2() */
2353 PyMemAllocatorEx old_alloc;
2354 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002357 p = NULL;
2358 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002359 size_t size = sizeof(struct _inittab) * (i + n + 1);
2360 p = PyMem_RawRealloc(inittab_copy, size);
2361 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002362 if (p == NULL) {
2363 res = -1;
2364 goto done;
2365 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002366
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002367 /* Copy the tables into the new memory at the first call
2368 to PyImport_ExtendInittab(). */
2369 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002371 }
2372 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2373 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002374
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002375done:
2376 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2377 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002378}
2379
2380/* Shorthand to add a single entry given a name and a function */
2381
2382int
Brett Cannona826f322009-04-02 03:41:46 +00002383PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002388
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002389 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002393}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002394
2395#ifdef __cplusplus
2396}
2397#endif