blob: 344f199216d09fb14e3028e75519a8e146b85ba1 [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);
434 value = PyDict_GetItemString(interp->sysdict, *(p+1));
435 if (value == NULL)
436 value = Py_None;
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300437 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300438 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300439 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000441
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200442 /* We prepare a list which will receive (name, weakref) tuples of
443 modules when they are removed from sys.modules. The name is used
444 for diagnosis messages (in verbose mode), while the weakref helps
445 detect those modules which have been held alive. */
446 weaklist = PyList_New(0);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300447 if (weaklist == NULL) {
448 PyErr_WriteUnraisable(NULL);
449 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200451#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200452 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200453 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300454 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200455 PyObject *tup = PyTuple_Pack(2, name, wr); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300456 if (!tup || PyList_Append(weaklist, tup) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300457 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300458 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200459 Py_XDECREF(tup); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300460 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200461 } \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300462 else { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300463 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300464 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600466#define CLEAR_MODULE(name, mod) \
467 if (PyModule_Check(mod)) { \
468 if (Py_VerboseFlag && PyUnicode_Check(name)) \
469 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
470 STORE_MODULE_WEAKREF(name, mod); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300471 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300472 PyErr_WriteUnraisable(NULL); \
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300473 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600474 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000475
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200476 /* Remove all modules from sys.modules, hoping that garbage collection
477 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600478 if (PyDict_CheckExact(modules)) {
479 pos = 0;
480 while (PyDict_Next(modules, &pos, &key, &value)) {
481 CLEAR_MODULE(key, value);
482 }
483 }
484 else {
485 PyObject *iterator = PyObject_GetIter(modules);
486 if (iterator == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300487 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600488 }
489 else {
490 while ((key = PyIter_Next(iterator))) {
491 value = PyObject_GetItem(modules, key);
492 if (value == NULL) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300493 PyErr_WriteUnraisable(NULL);
Eric Snow3f9eee62017-09-15 16:35:20 -0600494 continue;
495 }
496 CLEAR_MODULE(key, value);
497 Py_DECREF(value);
498 Py_DECREF(key);
499 }
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300500 if (PyErr_Occurred()) {
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300501 PyErr_WriteUnraisable(NULL);
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300502 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600503 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 }
505 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000506
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200507 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600508 if (PyDict_CheckExact(modules)) {
509 PyDict_Clear(modules);
510 }
511 else {
512 _Py_IDENTIFIER(clear);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300513 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL) {
514 PyErr_WriteUnraisable(NULL);
515 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600516 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200517 /* Restore the original builtins dict, to ensure that any
518 user data gets cleared. */
519 dict = PyDict_Copy(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300520 if (dict == NULL) {
521 PyErr_WriteUnraisable(NULL);
522 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200523 PyDict_Clear(interp->builtins);
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300524 if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200525 PyErr_Clear();
Serhiy Storchakac1a68322018-04-29 22:16:30 +0300526 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200527 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200528 /* Clear module dict copies stored in the interpreter state */
529 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200530 /* Collect references */
531 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200532 /* Dump GC stats before it's too late, since it uses the warnings
533 machinery. */
534 _PyGC_DumpShutdownStats();
535
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200536 /* Now, if there are any modules left alive, clear their globals to
537 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200538 up here, since they are kept alive in the interpreter state.
539
540 The special treatment of "builtins" here is because even
541 when it's not referenced as a module, its dictionary is
542 referenced by almost every module's __builtins__. Since
543 deleting a module clears its dictionary (even if there are
544 references left to it), we need to delete the "builtins"
545 module last. Likewise, we don't delete sys until the very
546 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200547 if (weaklist != NULL) {
Serhiy Storchakac93c58b2018-10-29 19:30:16 +0200548 Py_ssize_t i;
549 /* Since dict is ordered in CPython 3.6+, modules are saved in
550 importing order. First clear modules imported later. */
551 for (i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200552 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200553 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200554 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
555 if (mod == Py_None)
556 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200557 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200558 dict = PyModule_GetDict(mod);
559 if (dict == interp->builtins || dict == interp->sysdict)
560 continue;
561 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200562 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200563 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200564 _PyModule_Clear(mod);
565 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200566 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200567 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000569
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200570 /* Next, delete sys and builtins (in that order) */
571 if (Py_VerboseFlag)
572 PySys_FormatStderr("# cleanup[3] wiping sys\n");
573 _PyModule_ClearDict(interp->sysdict);
574 if (Py_VerboseFlag)
575 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
576 _PyModule_ClearDict(interp->builtins);
577
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200578 /* Clear and delete the modules directory. Actual modules will
579 still be there only if imported during the execution of some
580 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700581 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200583
584 /* Once more */
585 _PyGC_CollectNoFail();
586
Serhiy Storchakae9d94942018-04-25 20:58:40 +0300587#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200588#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000589}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000590
591
Barry Warsaw28a691b2010-04-17 00:19:56 +0000592/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000593
594long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000595PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000596{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200597 long res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200598 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow32439d62015-05-02 19:15:18 -0600599 PyObject *external, *pyc_magic;
600
601 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
602 if (external == NULL)
603 return -1;
604 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
605 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400606 if (pyc_magic == NULL)
607 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200608 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700609 Py_DECREF(pyc_magic);
610 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000611}
612
613
Brett Cannon3adc7b72012-07-09 14:22:12 -0400614extern const char * _PySys_ImplCacheTag;
615
Barry Warsaw28a691b2010-04-17 00:19:56 +0000616const char *
617PyImport_GetMagicTag(void)
618{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400619 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000620}
621
Brett Cannon98979b82012-07-02 15:13:11 -0400622
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623/* Magic for extension modules (built-in as well as dynamically
624 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200625 once, we keep a static dictionary 'extensions' keyed by the tuple
626 (module name, module name) (for built-in modules) or by
627 (filename, module name) (for dynamically loaded modules), containing these
628 modules. A copy of the module's dictionary is stored by calling
629 _PyImport_FixupExtensionObject() immediately after the module initialization
630 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100631 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000632
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000633 Modules which do support multiple initialization set their m_size
634 field to a non-negative number (indicating the size of the
635 module-specific state). They are still recorded in the extensions
636 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000637*/
638
639int
Victor Stinner95872862011-03-07 18:20:56 +0100640_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600641 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000642{
Eric Snowd393c1b2017-09-14 12:18:12 -0600643 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500645 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (extensions == NULL) {
647 extensions = PyDict_New();
648 if (extensions == NULL)
649 return -1;
650 }
651 if (mod == NULL || !PyModule_Check(mod)) {
652 PyErr_BadInternalCall();
653 return -1;
654 }
655 def = PyModule_GetDef(mod);
656 if (!def) {
657 PyErr_BadInternalCall();
658 return -1;
659 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600660 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 return -1;
662 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600663 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 return -1;
665 }
666 if (def->m_size == -1) {
667 if (def->m_base.m_copy) {
668 /* Somebody already imported the module,
669 likely under a different name.
670 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200671 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 }
673 dict = PyModule_GetDict(mod);
674 if (dict == NULL)
675 return -1;
676 def->m_base.m_copy = PyDict_Copy(dict);
677 if (def->m_base.m_copy == NULL)
678 return -1;
679 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500680 key = PyTuple_Pack(2, filename, name);
681 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200682 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500683 res = PyDict_SetItem(extensions, key, (PyObject *)def);
684 Py_DECREF(key);
685 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200686 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000688}
689
Victor Stinner49d3f252010-10-17 01:24:53 +0000690int
Eric Snowd393c1b2017-09-14 12:18:12 -0600691_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000692{
693 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100694 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100695 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100696 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000697 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600698 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100699 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000700 return res;
701}
702
Guido van Rossum25ce5661997-08-02 03:10:38 +0000703PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100704_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000705{
Eric Snowd393c1b2017-09-14 12:18:12 -0600706 PyObject *modules = PyImport_GetModuleDict();
707 return _PyImport_FindExtensionObjectEx(name, filename, modules);
708}
709
710PyObject *
711_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
712 PyObject *modules)
713{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500714 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyModuleDef* def;
716 if (extensions == NULL)
717 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500718 key = PyTuple_Pack(2, filename, name);
719 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200720 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500721 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
722 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 if (def == NULL)
724 return NULL;
725 if (def->m_size == -1) {
726 /* Module does not support repeated initialization */
727 if (def->m_base.m_copy == NULL)
728 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600729 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 if (mod == NULL)
731 return NULL;
732 mdict = PyModule_GetDict(mod);
733 if (mdict == NULL)
734 return NULL;
735 if (PyDict_Update(mdict, def->m_base.m_copy))
736 return NULL;
737 }
738 else {
739 if (def->m_base.m_init == NULL)
740 return NULL;
741 mod = def->m_base.m_init();
742 if (mod == NULL)
743 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600744 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200745 Py_DECREF(mod);
746 return NULL;
747 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 Py_DECREF(mod);
749 }
750 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600751 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 return NULL;
753 }
754 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100755 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 name, filename);
757 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000758
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759}
760
Victor Stinner49d3f252010-10-17 01:24:53 +0000761PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600762_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000763{
Victor Stinner95872862011-03-07 18:20:56 +0100764 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100765 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100766 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000767 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600768 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100769 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000770 return res;
771}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000772
773/* Get the module object corresponding to a module name.
774 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000775 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000776 Because the former action is most common, THIS DOES NOT RETURN A
777 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000778
Guido van Rossum79f25d91997-04-29 20:08:16 +0000779PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000780PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600783 return _PyImport_AddModuleObject(name, modules);
784}
785
786PyObject *
787_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
788{
Eric Snow86b7afd2017-09-04 17:54:09 -0600789 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600790 if (PyDict_CheckExact(modules)) {
791 m = PyDict_GetItemWithError(modules, name);
792 }
793 else {
794 m = PyObject_GetItem(modules, name);
795 // For backward-comaptibility we copy the behavior
796 // of PyDict_GetItemWithError().
797 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
798 PyErr_Clear();
799 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200800 }
801 if (PyErr_Occurred()) {
802 return NULL;
803 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600804 if (m != NULL && PyModule_Check(m)) {
805 return m;
806 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000807 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (m == NULL)
809 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600810 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 Py_DECREF(m);
812 return NULL;
813 }
814 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817}
818
Victor Stinner27ee0892011-03-04 12:57:09 +0000819PyObject *
820PyImport_AddModule(const char *name)
821{
822 PyObject *nameobj, *module;
823 nameobj = PyUnicode_FromString(name);
824 if (nameobj == NULL)
825 return NULL;
826 module = PyImport_AddModuleObject(nameobj);
827 Py_DECREF(nameobj);
828 return module;
829}
830
831
Tim Peters1cd70172004-08-02 03:52:12 +0000832/* Remove name from sys.modules, if it's there. */
833static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000834remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyObject *modules = PyImport_GetModuleDict();
Eric Snow3f9eee62017-09-15 16:35:20 -0600837 if (PyMapping_DelItem(modules, name) < 0) {
838 if (!PyMapping_HasKey(modules, name)) {
839 return;
840 }
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200841 Py_FatalError("import: deleting existing key in "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600843 }
Tim Peters1cd70172004-08-02 03:52:12 +0000844}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000845
Christian Heimes3b06e532008-01-07 20:12:44 +0000846
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000847/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000848 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
849 * removed from sys.modules, to avoid leaving damaged module objects
850 * in sys.modules. The caller may wish to restore the original
851 * module object (if any) in this case; PyImport_ReloadModule is an
852 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000853 *
854 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
855 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000856 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000857PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300858PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return PyImport_ExecCodeModuleWithPathnames(
861 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000862}
863
864PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300865PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 return PyImport_ExecCodeModuleWithPathnames(
868 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000869}
870
871PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300872PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
873 const char *pathname,
874 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000875{
Victor Stinner27ee0892011-03-04 12:57:09 +0000876 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600877 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000878
879 nameobj = PyUnicode_FromString(name);
880 if (nameobj == NULL)
881 return NULL;
882
Victor Stinner27ee0892011-03-04 12:57:09 +0000883 if (cpathname != NULL) {
884 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
885 if (cpathobj == NULL)
886 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400887 }
888 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000889 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400890
891 if (pathname != NULL) {
892 pathobj = PyUnicode_DecodeFSDefault(pathname);
893 if (pathobj == NULL)
894 goto error;
895 }
896 else if (cpathobj != NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200897 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Brett Cannona6473f92012-07-13 13:57:03 -0400898 _Py_IDENTIFIER(_get_sourcefile);
899
900 if (interp == NULL) {
901 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
902 "no interpreter!");
903 }
904
Eric Snow32439d62015-05-02 19:15:18 -0600905 external= PyObject_GetAttrString(interp->importlib,
906 "_bootstrap_external");
907 if (external != NULL) {
908 pathobj = _PyObject_CallMethodIdObjArgs(external,
909 &PyId__get_sourcefile, cpathobj,
910 NULL);
911 Py_DECREF(external);
912 }
Brett Cannona6473f92012-07-13 13:57:03 -0400913 if (pathobj == NULL)
914 PyErr_Clear();
915 }
916 else
917 pathobj = NULL;
918
Victor Stinner27ee0892011-03-04 12:57:09 +0000919 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
920error:
921 Py_DECREF(nameobj);
922 Py_XDECREF(pathobj);
923 Py_XDECREF(cpathobj);
924 return m;
925}
926
Brett Cannon18fc4e72014-04-04 10:01:46 -0400927static PyObject *
928module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000929{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400930 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931
Victor Stinner27ee0892011-03-04 12:57:09 +0000932 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (m == NULL)
934 return NULL;
935 /* If the module is being reloaded, we get the old module back
936 and re-use its dict to exec the new code. */
937 d = PyModule_GetDict(m);
938 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
939 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400940 PyEval_GetBuiltins()) != 0) {
941 remove_module(name);
942 return NULL;
943 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400945
Eric Snow08197a42014-05-12 17:54:55 -0600946 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400947}
948
949static PyObject *
950exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
951{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400952 PyObject *v, *m;
953
954 v = PyEval_EvalCode(code_object, module_dict, module_dict);
955 if (v == NULL) {
956 remove_module(name);
957 return NULL;
958 }
959 Py_DECREF(v);
960
Eric Snow3f9eee62017-09-15 16:35:20 -0600961 m = PyImport_GetModule(name);
962 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400963 PyErr_Format(PyExc_ImportError,
964 "Loaded module %R not found in sys.modules",
965 name);
966 return NULL;
967 }
968
Brett Cannon18fc4e72014-04-04 10:01:46 -0400969 return m;
970}
971
972PyObject*
973PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
974 PyObject *cpathname)
975{
Eric Snow32439d62015-05-02 19:15:18 -0600976 PyObject *d, *external, *res;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200977 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Eric Snow08197a42014-05-12 17:54:55 -0600978 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400979
980 d = module_dict_for_exec(name);
981 if (d == NULL) {
982 return NULL;
983 }
984
Eric Snow08197a42014-05-12 17:54:55 -0600985 if (pathname == NULL) {
986 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 }
Eric Snow32439d62015-05-02 19:15:18 -0600988 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
989 if (external == NULL)
990 return NULL;
991 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600992 &PyId__fix_up_module,
993 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600994 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600995 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600996 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600997 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 }
Eric Snow08197a42014-05-12 17:54:55 -0600999 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001000}
1001
1002
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001003static void
1004update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 PyObject *constants, *tmp;
1007 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (PyUnicode_Compare(co->co_filename, oldname))
1010 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001011
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001012 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001013 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 constants = co->co_consts;
1016 n = PyTuple_GET_SIZE(constants);
1017 for (i = 0; i < n; i++) {
1018 tmp = PyTuple_GET_ITEM(constants, i);
1019 if (PyCode_Check(tmp))
1020 update_code_filenames((PyCodeObject *)tmp,
1021 oldname, newname);
1022 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001023}
1024
Victor Stinner2f42ae52011-03-20 00:41:24 +01001025static void
1026update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001027{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001028 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001029
Victor Stinner2f42ae52011-03-20 00:41:24 +01001030 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1031 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 oldname = co->co_filename;
1034 Py_INCREF(oldname);
1035 update_code_filenames(co, oldname, newname);
1036 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001037}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001038
Brett Cannon4caa61d2014-01-09 19:03:32 -05001039/*[clinic input]
1040_imp._fix_co_filename
1041
1042 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1043 Code object to change.
1044
1045 path: unicode
1046 File path to use.
1047 /
1048
1049Changes code.co_filename to specify the passed-in file path.
1050[clinic start generated code]*/
1051
Brett Cannon4caa61d2014-01-09 19:03:32 -05001052static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001053_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001054 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001055/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001056
Brett Cannon4caa61d2014-01-09 19:03:32 -05001057{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001058 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001059
1060 Py_RETURN_NONE;
1061}
1062
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001063
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001064/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001065static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001066
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001067
1068/* Helper to test for built-in module */
1069
1070static int
Victor Stinner95872862011-03-07 18:20:56 +01001071is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001072{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001073 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001075 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (PyImport_Inittab[i].initfunc == NULL)
1077 return -1;
1078 else
1079 return 1;
1080 }
1081 }
1082 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001083}
1084
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001085
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001086/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001087 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001088 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001089 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001090 this tells our caller that the path based finder could not find
1091 a finder for this path item. Cache the result in
1092 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001093 Returns a borrowed reference. */
1094
1095static PyObject *
1096get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *importer;
1100 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* These conditions are the caller's responsibility: */
1103 assert(PyList_Check(path_hooks));
1104 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 nhooks = PyList_Size(path_hooks);
1107 if (nhooks < 0)
1108 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 importer = PyDict_GetItem(path_importer_cache, p);
1111 if (importer != NULL)
1112 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 /* set path_importer_cache[p] to None to avoid recursion */
1115 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1116 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 for (j = 0; j < nhooks; j++) {
1119 PyObject *hook = PyList_GetItem(path_hooks, j);
1120 if (hook == NULL)
1121 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001122 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (importer != NULL)
1124 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1127 return NULL;
1128 }
1129 PyErr_Clear();
1130 }
1131 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001132 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
1134 if (importer != NULL) {
1135 int err = PyDict_SetItem(path_importer_cache, p, importer);
1136 Py_DECREF(importer);
1137 if (err != 0)
1138 return NULL;
1139 }
1140 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001141}
1142
Benjamin Petersone5024512018-09-12 12:06:42 -07001143PyObject *
Christian Heimes9cd17752007-11-18 19:35:23 +00001144PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001146
Victor Stinner1e53bba2013-07-16 22:26:05 +02001147 path_importer_cache = PySys_GetObject("path_importer_cache");
1148 path_hooks = PySys_GetObject("path_hooks");
1149 if (path_importer_cache != NULL && path_hooks != NULL) {
1150 importer = get_path_importer(path_importer_cache,
1151 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 }
1153 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1154 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001155}
1156
Nick Coghland5cacbb2015-05-23 22:24:10 +10001157/*[clinic input]
1158_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001159
Nick Coghland5cacbb2015-05-23 22:24:10 +10001160 spec: object
1161 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001162
Nick Coghland5cacbb2015-05-23 22:24:10 +10001163Create an extension module.
1164[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001165
Nick Coghland5cacbb2015-05-23 22:24:10 +10001166static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001167_imp_create_builtin(PyObject *module, PyObject *spec)
1168/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001171 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001172 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001173 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001174
Nick Coghland5cacbb2015-05-23 22:24:10 +10001175 name = PyObject_GetAttrString(spec, "name");
1176 if (name == NULL) {
1177 return NULL;
1178 }
1179
Victor Stinner5eb4f592013-11-14 22:38:52 +01001180 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001181 if (mod || PyErr_Occurred()) {
1182 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001183 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001184 return mod;
1185 }
1186
1187 namestr = PyUnicode_AsUTF8(name);
1188 if (namestr == NULL) {
1189 Py_DECREF(name);
1190 return NULL;
1191 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001192
Eric Snowd393c1b2017-09-14 12:18:12 -06001193 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001195 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001196 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001198 /* Cannot re-init internal module ("sys" or "builtins") */
1199 mod = PyImport_AddModule(namestr);
1200 Py_DECREF(name);
1201 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001204 if (mod == NULL) {
1205 Py_DECREF(name);
1206 return NULL;
1207 }
1208 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1209 Py_DECREF(name);
1210 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1211 } else {
1212 /* Remember pointer to module init function. */
1213 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001214 if (def == NULL) {
1215 Py_DECREF(name);
1216 return NULL;
1217 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001218 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001219 if (modules == NULL) {
1220 modules = PyImport_GetModuleDict();
1221 }
1222 if (_PyImport_FixupExtensionObject(mod, name, name,
1223 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001224 Py_DECREF(name);
1225 return NULL;
1226 }
1227 Py_DECREF(name);
1228 return mod;
1229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 }
1231 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001232 Py_DECREF(name);
1233 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001234}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001235
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001236
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001237/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001238
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001239static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001240find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001241{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001242 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001243
Victor Stinner53dc7352011-03-20 01:50:21 +01001244 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 for (p = PyImport_FrozenModules; ; p++) {
1248 if (p->name == NULL)
1249 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001250 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 break;
1252 }
1253 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001254}
1255
Guido van Rossum79f25d91997-04-29 20:08:16 +00001256static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001257get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001258{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001259 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (p == NULL) {
1263 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001264 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 name);
1266 return NULL;
1267 }
1268 if (p->code == NULL) {
1269 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001270 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 name);
1272 return NULL;
1273 }
1274 size = p->size;
1275 if (size < 0)
1276 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001277 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001278}
1279
Brett Cannon8d110132009-03-15 02:20:16 +00001280static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001281is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001282{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001283 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (p == NULL) {
1287 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001288 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 name);
1290 return NULL;
1291 }
Brett Cannon8d110132009-03-15 02:20:16 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (size < 0)
1296 Py_RETURN_TRUE;
1297 else
1298 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001299}
1300
1301
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001302/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001303 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001304 an exception set if the initialization failed.
1305 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001306
1307int
Victor Stinner53dc7352011-03-20 01:50:21 +01001308PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001309{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001310 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001311 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 int ispackage;
1313 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001314
Victor Stinner53dc7352011-03-20 01:50:21 +01001315 p = find_frozen(name);
1316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (p == NULL)
1318 return 0;
1319 if (p->code == NULL) {
1320 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001321 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 name);
1323 return -1;
1324 }
1325 size = p->size;
1326 ispackage = (size < 0);
1327 if (ispackage)
1328 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001329 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (co == NULL)
1331 return -1;
1332 if (!PyCode_Check(co)) {
1333 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001334 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 name);
1336 goto err_return;
1337 }
1338 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001339 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001340 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001342 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (m == NULL)
1344 goto err_return;
1345 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001346 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 goto err_return;
1349 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 err = PyDict_SetItemString(d, "__path__", l);
1351 Py_DECREF(l);
1352 if (err != 0)
1353 goto err_return;
1354 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001355 d = module_dict_for_exec(name);
1356 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001357 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001358 }
1359 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (m == NULL)
1361 goto err_return;
1362 Py_DECREF(co);
1363 Py_DECREF(m);
1364 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001365err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 Py_DECREF(co);
1367 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001368}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001369
Victor Stinner53dc7352011-03-20 01:50:21 +01001370int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001371PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001372{
1373 PyObject *nameobj;
1374 int ret;
1375 nameobj = PyUnicode_InternFromString(name);
1376 if (nameobj == NULL)
1377 return -1;
1378 ret = PyImport_ImportFrozenModuleObject(nameobj);
1379 Py_DECREF(nameobj);
1380 return ret;
1381}
1382
Guido van Rossum74e6a111994-08-29 12:54:38 +00001383
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001384/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001385 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001386
Guido van Rossum79f25d91997-04-29 20:08:16 +00001387PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001388PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 PyObject *pname;
1391 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 pname = PyUnicode_FromString(name);
1394 if (pname == NULL)
1395 return NULL;
1396 result = PyImport_Import(pname);
1397 Py_DECREF(pname);
1398 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001399}
1400
Christian Heimes072c0f12008-01-03 23:01:04 +00001401/* Import a module without blocking
1402 *
1403 * At first it tries to fetch the module from sys.modules. If the module was
1404 * never loaded before it loads it with PyImport_ImportModule() unless another
1405 * thread holds the import lock. In the latter case the function raises an
1406 * ImportError instead of blocking.
1407 *
1408 * Returns the module object with incremented ref count.
1409 */
1410PyObject *
1411PyImport_ImportModuleNoBlock(const char *name)
1412{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001413 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001414}
1415
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001416
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001417/* Remove importlib frames from the traceback,
1418 * except in Verbose mode. */
1419static void
1420remove_importlib_frames(void)
1421{
1422 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001423 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001424 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001425 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001426 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001427 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001428 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001429
1430 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001431 from the traceback. We always trim chunks
1432 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001433
1434 PyErr_Fetch(&exception, &value, &base_tb);
1435 if (!exception || Py_VerboseFlag)
1436 goto done;
1437 if (PyType_IsSubtype((PyTypeObject *) exception,
1438 (PyTypeObject *) PyExc_ImportError))
1439 always_trim = 1;
1440
1441 prev_link = &base_tb;
1442 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001443 while (tb != NULL) {
1444 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1445 PyObject *next = (PyObject *) traceback->tb_next;
1446 PyFrameObject *frame = traceback->tb_frame;
1447 PyCodeObject *code = frame->f_code;
1448 int now_in_importlib;
1449
1450 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001451 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1452 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001453 if (now_in_importlib && !in_importlib) {
1454 /* This is the link to this chunk of importlib tracebacks */
1455 outer_link = prev_link;
1456 }
1457 in_importlib = now_in_importlib;
1458
1459 if (in_importlib &&
1460 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001461 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001462 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001463 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001464 prev_link = outer_link;
1465 }
1466 else {
1467 prev_link = (PyObject **) &traceback->tb_next;
1468 }
1469 tb = next;
1470 }
1471done:
1472 PyErr_Restore(exception, value, base_tb);
1473}
1474
1475
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001476static PyObject *
1477resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001478{
Eric Snowb523f842013-11-22 09:05:39 -07001479 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001480 _Py_IDENTIFIER(__package__);
1481 _Py_IDENTIFIER(__path__);
1482 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001483 _Py_IDENTIFIER(parent);
1484 PyObject *abs_name;
1485 PyObject *package = NULL;
1486 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001487 Py_ssize_t last_dot;
1488 PyObject *base;
1489 int level_up;
1490
1491 if (globals == NULL) {
1492 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1493 goto error;
1494 }
1495 if (!PyDict_Check(globals)) {
1496 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1497 goto error;
1498 }
1499 package = _PyDict_GetItemId(globals, &PyId___package__);
1500 if (package == Py_None) {
1501 package = NULL;
1502 }
1503 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1504
1505 if (package != NULL) {
1506 Py_INCREF(package);
1507 if (!PyUnicode_Check(package)) {
1508 PyErr_SetString(PyExc_TypeError, "package must be a string");
1509 goto error;
1510 }
1511 else if (spec != NULL && spec != Py_None) {
1512 int equal;
1513 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1514 if (parent == NULL) {
1515 goto error;
1516 }
1517
1518 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1519 Py_DECREF(parent);
1520 if (equal < 0) {
1521 goto error;
1522 }
1523 else if (equal == 0) {
1524 if (PyErr_WarnEx(PyExc_ImportWarning,
1525 "__package__ != __spec__.parent", 1) < 0) {
1526 goto error;
1527 }
1528 }
1529 }
1530 }
1531 else if (spec != NULL && spec != Py_None) {
1532 package = _PyObject_GetAttrId(spec, &PyId_parent);
1533 if (package == NULL) {
1534 goto error;
1535 }
1536 else if (!PyUnicode_Check(package)) {
1537 PyErr_SetString(PyExc_TypeError,
1538 "__spec__.parent must be a string");
1539 goto error;
1540 }
1541 }
1542 else {
1543 if (PyErr_WarnEx(PyExc_ImportWarning,
1544 "can't resolve package from __spec__ or __package__, "
1545 "falling back on __name__ and __path__", 1) < 0) {
1546 goto error;
1547 }
1548
1549 package = _PyDict_GetItemId(globals, &PyId___name__);
1550 if (package == NULL) {
1551 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1552 goto error;
1553 }
1554
1555 Py_INCREF(package);
1556 if (!PyUnicode_Check(package)) {
1557 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1558 goto error;
1559 }
1560
1561 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1562 Py_ssize_t dot;
1563
1564 if (PyUnicode_READY(package) < 0) {
1565 goto error;
1566 }
1567
1568 dot = PyUnicode_FindChar(package, '.',
1569 0, PyUnicode_GET_LENGTH(package), -1);
1570 if (dot == -2) {
1571 goto error;
1572 }
1573
1574 if (dot >= 0) {
1575 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1576 if (substr == NULL) {
1577 goto error;
1578 }
1579 Py_SETREF(package, substr);
1580 }
1581 }
1582 }
1583
1584 last_dot = PyUnicode_GET_LENGTH(package);
1585 if (last_dot == 0) {
1586 PyErr_SetString(PyExc_ImportError,
1587 "attempted relative import with no known parent package");
1588 goto error;
1589 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001590
1591 for (level_up = 1; level_up < level; level_up += 1) {
1592 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1593 if (last_dot == -2) {
1594 goto error;
1595 }
1596 else if (last_dot == -1) {
1597 PyErr_SetString(PyExc_ValueError,
1598 "attempted relative import beyond top-level "
1599 "package");
1600 goto error;
1601 }
1602 }
1603
1604 base = PyUnicode_Substring(package, 0, last_dot);
1605 Py_DECREF(package);
1606 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1607 return base;
1608 }
1609
1610 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1611 Py_DECREF(base);
1612 return abs_name;
1613
1614 error:
1615 Py_XDECREF(package);
1616 return NULL;
1617}
1618
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001619static PyObject *
1620import_find_and_load(PyObject *abs_name)
1621{
1622 _Py_IDENTIFIER(_find_and_load);
1623 PyObject *mod = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001624 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001625 int import_time = interp->core_config.import_time;
1626 static int import_level;
1627 static _PyTime_t accumulated;
1628
1629 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1630
1631 /* XOptions is initialized after first some imports.
1632 * So we can't have negative cache before completed initialization.
1633 * Anyway, importlib._find_and_load is much slower than
1634 * _PyDict_GetItemIdWithError().
1635 */
1636 if (import_time) {
1637 static int header = 1;
1638 if (header) {
1639 fputs("import time: self [us] | cumulative | imported package\n",
1640 stderr);
1641 header = 0;
1642 }
1643
1644 import_level++;
1645 t1 = _PyTime_GetPerfCounter();
1646 accumulated = 0;
1647 }
1648
1649 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1650 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1651
1652 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1653 &PyId__find_and_load, abs_name,
1654 interp->import_func, NULL);
1655
1656 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1657 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1658 mod != NULL);
1659
1660 if (import_time) {
1661 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1662
1663 import_level--;
1664 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1665 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1666 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1667 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1668
1669 accumulated = accumulated_copy + cum;
1670 }
1671
1672 return mod;
1673}
1674
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001675PyObject *
1676PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1677 PyObject *locals, PyObject *fromlist,
1678 int level)
1679{
Brett Cannonfd074152012-04-14 14:10:13 -04001680 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001681 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001682 PyObject *final_mod = NULL;
1683 PyObject *mod = NULL;
1684 PyObject *package = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001685 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001686 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001687
Brett Cannonfd074152012-04-14 14:10:13 -04001688 if (name == NULL) {
1689 PyErr_SetString(PyExc_ValueError, "Empty module name");
1690 goto error;
1691 }
1692
1693 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1694 for added performance. */
1695
1696 if (!PyUnicode_Check(name)) {
1697 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1698 goto error;
1699 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001700 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001701 goto error;
1702 }
1703 if (level < 0) {
1704 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1705 goto error;
1706 }
Brett Cannon849113a2016-01-22 15:25:50 -08001707
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001708 if (level > 0) {
1709 abs_name = resolve_name(name, globals, level);
1710 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001711 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001712 }
1713 else { /* level == 0 */
1714 if (PyUnicode_GET_LENGTH(name) == 0) {
1715 PyErr_SetString(PyExc_ValueError, "Empty module name");
1716 goto error;
1717 }
Brett Cannonfd074152012-04-14 14:10:13 -04001718 abs_name = name;
1719 Py_INCREF(abs_name);
1720 }
1721
Eric Snow3f9eee62017-09-15 16:35:20 -06001722 mod = PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001723 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001724 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001725 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001726 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001727
Antoine Pitrou03989852012-08-28 00:24:52 +02001728 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001729 __spec__._initializing is true.
1730 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001731 stuffing the new module in sys.modules.
1732 */
Eric Snowb523f842013-11-22 09:05:39 -07001733 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001734 if (_PyModuleSpec_IsInitializing(spec)) {
1735 PyObject *value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1736 &PyId__lock_unlock_module, abs_name,
1737 NULL);
1738 if (value == NULL) {
1739 Py_DECREF(spec);
1740 goto error;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001741 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001742 Py_DECREF(value);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001743 }
Serhiy Storchaka3e429dc2018-10-30 13:19:51 +02001744 Py_XDECREF(spec);
Brett Cannonfd074152012-04-14 14:10:13 -04001745 }
1746 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001747 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001748 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001749 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001750 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001751 }
1752 }
1753
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001754 has_from = 0;
1755 if (fromlist != NULL && fromlist != Py_None) {
1756 has_from = PyObject_IsTrue(fromlist);
1757 if (has_from < 0)
1758 goto error;
1759 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001760 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001761 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1762 if (level == 0 || len > 0) {
1763 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001764
Victor Stinner744c34e2016-05-20 11:36:13 +02001765 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1766 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001767 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001768 }
1769
Victor Stinner744c34e2016-05-20 11:36:13 +02001770 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001771 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001772 final_mod = mod;
1773 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001774 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001775 }
1776
Brett Cannonfd074152012-04-14 14:10:13 -04001777 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001778 PyObject *front = PyUnicode_Substring(name, 0, dot);
1779 if (front == NULL) {
1780 goto error;
1781 }
1782
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001783 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001784 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001785 }
1786 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001787 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001788 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001789 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001790 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001791 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001792 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001793 }
Brett Cannonfd074152012-04-14 14:10:13 -04001794
Eric Snow3f9eee62017-09-15 16:35:20 -06001795 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001796 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001797 if (final_mod == NULL) {
1798 PyErr_Format(PyExc_KeyError,
1799 "%R not in sys.modules as expected",
1800 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001801 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001802 }
Brett Cannonfd074152012-04-14 14:10:13 -04001803 }
1804 }
1805 else {
1806 final_mod = mod;
1807 Py_INCREF(mod);
1808 }
1809 }
1810 else {
Serhiy Storchaka4e244252018-03-11 10:52:37 +02001811 _Py_IDENTIFIER(__path__);
1812 PyObject *path;
1813 if (_PyObject_LookupAttrId(mod, &PyId___path__, &path) < 0) {
1814 goto error;
1815 }
1816 if (path) {
1817 Py_DECREF(path);
1818 final_mod = _PyObject_CallMethodIdObjArgs(
1819 interp->importlib, &PyId__handle_fromlist,
1820 mod, fromlist, interp->import_func, NULL);
1821 }
1822 else {
1823 final_mod = mod;
1824 Py_INCREF(mod);
1825 }
Brett Cannonfd074152012-04-14 14:10:13 -04001826 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001827
Brett Cannonfd074152012-04-14 14:10:13 -04001828 error:
1829 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001830 Py_XDECREF(mod);
1831 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001832 if (final_mod == NULL)
1833 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001834 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001835}
1836
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001837PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001838PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001839 PyObject *fromlist, int level)
1840{
1841 PyObject *nameobj, *mod;
1842 nameobj = PyUnicode_FromString(name);
1843 if (nameobj == NULL)
1844 return NULL;
1845 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1846 fromlist, level);
1847 Py_DECREF(nameobj);
1848 return mod;
1849}
1850
1851
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001852/* Re-import a module of any kind and return its module object, WITH
1853 INCREMENTED REFERENCE COUNT */
1854
Guido van Rossum79f25d91997-04-29 20:08:16 +00001855PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001856PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001857{
Eric Snow3f9eee62017-09-15 16:35:20 -06001858 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001859 _Py_IDENTIFIER(reload);
1860 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001861 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001862 if (imp == NULL) {
1863 imp = PyImport_ImportModule("imp");
1864 if (imp == NULL) {
1865 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001868
Victor Stinner55ba38a2016-12-09 16:09:30 +01001869 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001870 Py_DECREF(imp);
1871 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001872}
1873
1874
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001875/* Higher-level import emulator which emulates the "import" statement
1876 more accurately -- it invokes the __import__() function from the
1877 builtins of the current globals. This means that the import is
1878 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001879 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001880 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001881 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001882 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001883
1884PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001885PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 static PyObject *silly_list = NULL;
1888 static PyObject *builtins_str = NULL;
1889 static PyObject *import_str = NULL;
1890 PyObject *globals = NULL;
1891 PyObject *import = NULL;
1892 PyObject *builtins = NULL;
1893 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 /* Initialize constant string objects */
1896 if (silly_list == NULL) {
1897 import_str = PyUnicode_InternFromString("__import__");
1898 if (import_str == NULL)
1899 return NULL;
1900 builtins_str = PyUnicode_InternFromString("__builtins__");
1901 if (builtins_str == NULL)
1902 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001903 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (silly_list == NULL)
1905 return NULL;
1906 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 /* Get the builtins from current globals */
1909 globals = PyEval_GetGlobals();
1910 if (globals != NULL) {
1911 Py_INCREF(globals);
1912 builtins = PyObject_GetItem(globals, builtins_str);
1913 if (builtins == NULL)
1914 goto err;
1915 }
1916 else {
1917 /* No globals -- use standard builtins, and fake globals */
1918 builtins = PyImport_ImportModuleLevel("builtins",
1919 NULL, NULL, NULL, 0);
1920 if (builtins == NULL)
1921 return NULL;
1922 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1923 if (globals == NULL)
1924 goto err;
1925 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 /* Get the __import__ function from the builtins */
1928 if (PyDict_Check(builtins)) {
1929 import = PyObject_GetItem(builtins, import_str);
1930 if (import == NULL)
1931 PyErr_SetObject(PyExc_KeyError, import_str);
1932 }
1933 else
1934 import = PyObject_GetAttr(builtins, import_str);
1935 if (import == NULL)
1936 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001939 Always use absolute import here.
1940 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1942 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001943 if (r == NULL)
1944 goto err;
1945 Py_DECREF(r);
1946
Eric Snow3f9eee62017-09-15 16:35:20 -06001947 r = PyImport_GetModule(module_name);
1948 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001949 PyErr_SetObject(PyExc_KeyError, module_name);
1950 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001951
1952 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 Py_XDECREF(globals);
1954 Py_XDECREF(builtins);
1955 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001958}
1959
Brett Cannon4caa61d2014-01-09 19:03:32 -05001960/*[clinic input]
1961_imp.extension_suffixes
1962
1963Returns the list of file suffixes used to identify extension modules.
1964[clinic start generated code]*/
1965
Brett Cannon4caa61d2014-01-09 19:03:32 -05001966static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001967_imp_extension_suffixes_impl(PyObject *module)
1968/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001971 const char *suffix;
1972 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 list = PyList_New(0);
1975 if (list == NULL)
1976 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001977#ifdef HAVE_DYNAMIC_LOADING
1978 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1979 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (item == NULL) {
1981 Py_DECREF(list);
1982 return NULL;
1983 }
1984 if (PyList_Append(list, item) < 0) {
1985 Py_DECREF(list);
1986 Py_DECREF(item);
1987 return NULL;
1988 }
1989 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001990 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Brett Cannon2657df42012-05-04 15:20:40 -04001992#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001994}
1995
Brett Cannon4caa61d2014-01-09 19:03:32 -05001996/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001997_imp.init_frozen
1998
1999 name: unicode
2000 /
2001
2002Initializes a frozen module.
2003[clinic start generated code]*/
2004
Brett Cannon4caa61d2014-01-09 19:03:32 -05002005static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002006_imp_init_frozen_impl(PyObject *module, PyObject *name)
2007/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 int ret;
2010 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002011
Victor Stinner53dc7352011-03-20 01:50:21 +01002012 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (ret < 0)
2014 return NULL;
2015 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002016 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002018 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_XINCREF(m);
2020 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002021}
2022
Brett Cannon4caa61d2014-01-09 19:03:32 -05002023/*[clinic input]
2024_imp.get_frozen_object
2025
2026 name: unicode
2027 /
2028
2029Create a code object for a frozen module.
2030[clinic start generated code]*/
2031
Brett Cannon4caa61d2014-01-09 19:03:32 -05002032static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002033_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2034/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002037}
2038
Brett Cannon4caa61d2014-01-09 19:03:32 -05002039/*[clinic input]
2040_imp.is_frozen_package
2041
2042 name: unicode
2043 /
2044
2045Returns True if the module name is of a frozen package.
2046[clinic start generated code]*/
2047
Brett Cannon4caa61d2014-01-09 19:03:32 -05002048static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002049_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2050/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002053}
2054
Brett Cannon4caa61d2014-01-09 19:03:32 -05002055/*[clinic input]
2056_imp.is_builtin
2057
2058 name: unicode
2059 /
2060
2061Returns True if the module name corresponds to a built-in module.
2062[clinic start generated code]*/
2063
Guido van Rossum79f25d91997-04-29 20:08:16 +00002064static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002065_imp_is_builtin_impl(PyObject *module, PyObject *name)
2066/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002067{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002068 return PyLong_FromLong(is_builtin(name));
2069}
2070
2071/*[clinic input]
2072_imp.is_frozen
2073
2074 name: unicode
2075 /
2076
2077Returns True if the module name corresponds to a frozen module.
2078[clinic start generated code]*/
2079
Brett Cannon4caa61d2014-01-09 19:03:32 -05002080static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002081_imp_is_frozen_impl(PyObject *module, PyObject *name)
2082/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002083{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002084 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 p = find_frozen(name);
2087 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002088}
2089
Larry Hastings1df0b352015-08-24 19:53:56 -07002090/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2091static int
2092exec_builtin_or_dynamic(PyObject *mod) {
2093 PyModuleDef *def;
2094 void *state;
2095
2096 if (!PyModule_Check(mod)) {
2097 return 0;
2098 }
2099
2100 def = PyModule_GetDef(mod);
2101 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002102 return 0;
2103 }
Brett Cannon52794db2016-09-07 17:00:43 -07002104
Larry Hastings1df0b352015-08-24 19:53:56 -07002105 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002106 if (state) {
2107 /* Already initialized; skip reload */
2108 return 0;
2109 }
Brett Cannon52794db2016-09-07 17:00:43 -07002110
Larry Hastings1df0b352015-08-24 19:53:56 -07002111 return PyModule_ExecDef(mod, def);
2112}
2113
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002114#ifdef HAVE_DYNAMIC_LOADING
2115
Brett Cannon4caa61d2014-01-09 19:03:32 -05002116/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002117_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002118
Nick Coghland5cacbb2015-05-23 22:24:10 +10002119 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002120 file: object = NULL
2121 /
2122
Nick Coghland5cacbb2015-05-23 22:24:10 +10002123Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002124[clinic start generated code]*/
2125
Brett Cannon4caa61d2014-01-09 19:03:32 -05002126static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002127_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2128/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002129{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002130 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002131 FILE *fp;
2132
Nick Coghland5cacbb2015-05-23 22:24:10 +10002133 name = PyObject_GetAttrString(spec, "name");
2134 if (name == NULL) {
2135 return NULL;
2136 }
2137
2138 path = PyObject_GetAttrString(spec, "origin");
2139 if (path == NULL) {
2140 Py_DECREF(name);
2141 return NULL;
2142 }
2143
2144 mod = _PyImport_FindExtensionObject(name, path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002145 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002146 Py_DECREF(name);
2147 Py_DECREF(path);
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02002148 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002149 return mod;
2150 }
2151
Brett Cannon4caa61d2014-01-09 19:03:32 -05002152 if (file != NULL) {
2153 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002154 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002155 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002156 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002158 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002160 else
2161 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002162
2163 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2164
2165 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002166 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (fp)
2168 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002169 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002170}
2171
Nick Coghland5cacbb2015-05-23 22:24:10 +10002172/*[clinic input]
2173_imp.exec_dynamic -> int
2174
2175 mod: object
2176 /
2177
2178Initialize an extension module.
2179[clinic start generated code]*/
2180
2181static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002182_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2183/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002184{
Larry Hastings1df0b352015-08-24 19:53:56 -07002185 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002186}
2187
2188
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002189#endif /* HAVE_DYNAMIC_LOADING */
2190
Larry Hastings7726ac92014-01-31 22:03:12 -08002191/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002192_imp.exec_builtin -> int
2193
2194 mod: object
2195 /
2196
2197Initialize a built-in module.
2198[clinic start generated code]*/
2199
2200static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002201_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2202/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002203{
2204 return exec_builtin_or_dynamic(mod);
2205}
2206
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002207/*[clinic input]
2208_imp.source_hash
2209
2210 key: long
2211 source: Py_buffer
2212[clinic start generated code]*/
2213
2214static PyObject *
2215_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2216/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2217{
Benjamin Peterson83620772017-12-09 12:18:56 -08002218 union {
2219 uint64_t x;
2220 char data[sizeof(uint64_t)];
2221 } hash;
2222 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002223#if !PY_LITTLE_ENDIAN
2224 // Force to little-endian. There really ought to be a succinct standard way
2225 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002226 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2227 char tmp = hash.data[i];
2228 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2229 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002230 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002231#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002232 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002233}
2234
Barry Warsaw28a691b2010-04-17 00:19:56 +00002235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002236PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002237"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002238
Guido van Rossum79f25d91997-04-29 20:08:16 +00002239static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002240 _IMP_EXTENSION_SUFFIXES_METHODDEF
2241 _IMP_LOCK_HELD_METHODDEF
2242 _IMP_ACQUIRE_LOCK_METHODDEF
2243 _IMP_RELEASE_LOCK_METHODDEF
2244 _IMP_GET_FROZEN_OBJECT_METHODDEF
2245 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002246 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002247 _IMP_INIT_FROZEN_METHODDEF
2248 _IMP_IS_BUILTIN_METHODDEF
2249 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002250 _IMP_CREATE_DYNAMIC_METHODDEF
2251 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002252 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002253 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002254 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002255 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002256};
2257
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002258
Martin v. Löwis1a214512008-06-11 05:26:20 +00002259static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002261 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 doc_imp,
2263 0,
2264 imp_methods,
2265 NULL,
2266 NULL,
2267 NULL,
2268 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002269};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002270
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002271PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002272PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 m = PyModule_Create(&impmodule);
2277 if (m == NULL)
2278 goto failure;
2279 d = PyModule_GetDict(m);
2280 if (d == NULL)
2281 goto failure;
Victor Stinnercaba55b2018-08-03 15:33:52 +02002282 _PyCoreConfig *config = &_PyInterpreterState_Get()->core_config;
Victor Stinner80b762f2018-08-01 18:18:07 +02002283 PyObject *pyc_mode = PyUnicode_FromString(config->_check_hash_pycs_mode);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002284 if (pyc_mode == NULL) {
2285 goto failure;
2286 }
2287 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2288 Py_DECREF(pyc_mode);
2289 goto failure;
2290 }
2291 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002294 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 Py_XDECREF(m);
2296 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002297}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002298
2299
Guido van Rossumb18618d2000-05-03 23:44:39 +00002300/* API for embedding applications that want to add their own entries
2301 to the table of built-in modules. This should normally be called
2302 *before* Py_Initialize(). When the table resize fails, -1 is
2303 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002304
2305 After a similar function by Just van Rossum. */
2306
2307int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002308PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002311 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002312 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* Count the number of entries in both tables */
2315 for (n = 0; newtab[n].name != NULL; n++)
2316 ;
2317 if (n == 0)
2318 return 0; /* Nothing to do */
2319 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2320 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002321
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002322 /* Force default raw memory allocator to get a known allocator to be able
2323 to release the memory in _PyImport_Fini2() */
2324 PyMemAllocatorEx old_alloc;
2325 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002328 p = NULL;
2329 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002330 size_t size = sizeof(struct _inittab) * (i + n + 1);
2331 p = PyMem_RawRealloc(inittab_copy, size);
2332 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002333 if (p == NULL) {
2334 res = -1;
2335 goto done;
2336 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002337
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002338 /* Copy the tables into the new memory at the first call
2339 to PyImport_ExtendInittab(). */
2340 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002342 }
2343 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2344 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002345
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002346done:
2347 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2348 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002349}
2350
2351/* Shorthand to add a single entry given a name and a function */
2352
2353int
Brett Cannona826f322009-04-02 03:41:46 +00002354PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002359
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002360 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002364}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002365
2366#ifdef __cplusplus
2367}
2368#endif