blob: d5dad1a6a30ad360e60a96c2eae8e3eef8a7d8e0 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08008#include "internal/hash.h"
9#include "internal/import.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060010#include "internal/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{
96 PyObject *path_hooks, *zimpimport;
97 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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 zimpimport = PyImport_ImportModule("zipimport");
109 if (zimpimport == NULL) {
110 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);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200116 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
117 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 Py_DECREF(zimpimport);
119 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{
Eric Snow93c92f72017-09-13 23:46:04 -0700309 PyInterpreterState *interp = PyThreadState_GET()->interp;
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);
368 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
369 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;
402 PyInterpreterState *interp = PyThreadState_GET()->interp;
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");
420 PyDict_SetItemString(interp->builtins, "_", Py_None);
421
422 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200424 PySys_WriteStderr("# clear sys.%s\n", *p);
425 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200427 for (p = sys_files; *p != NULL; p+=2) {
428 if (Py_VerboseFlag)
429 PySys_WriteStderr("# restore sys.%s\n", *p);
430 value = PyDict_GetItemString(interp->sysdict, *(p+1));
431 if (value == NULL)
432 value = Py_None;
433 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200436 /* We prepare a list which will receive (name, weakref) tuples of
437 modules when they are removed from sys.modules. The name is used
438 for diagnosis messages (in verbose mode), while the weakref helps
439 detect those modules which have been held alive. */
440 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200441 if (weaklist == NULL)
442 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200443
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200444#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200445 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200446 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
447 if (name && wr) { \
448 PyObject *tup = PyTuple_Pack(2, name, wr); \
449 PyList_Append(weaklist, tup); \
450 Py_XDECREF(tup); \
451 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200452 Py_XDECREF(wr); \
453 if (PyErr_Occurred()) \
454 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600456#define CLEAR_MODULE(name, mod) \
457 if (PyModule_Check(mod)) { \
458 if (Py_VerboseFlag && PyUnicode_Check(name)) \
459 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
460 STORE_MODULE_WEAKREF(name, mod); \
461 PyObject_SetItem(modules, name, Py_None); \
462 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000463
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200464 /* Remove all modules from sys.modules, hoping that garbage collection
465 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600466 if (PyDict_CheckExact(modules)) {
467 pos = 0;
468 while (PyDict_Next(modules, &pos, &key, &value)) {
469 CLEAR_MODULE(key, value);
470 }
471 }
472 else {
473 PyObject *iterator = PyObject_GetIter(modules);
474 if (iterator == NULL) {
475 PyErr_Clear();
476 }
477 else {
478 while ((key = PyIter_Next(iterator))) {
479 value = PyObject_GetItem(modules, key);
480 if (value == NULL) {
481 PyErr_Clear();
482 continue;
483 }
484 CLEAR_MODULE(key, value);
485 Py_DECREF(value);
486 Py_DECREF(key);
487 }
488 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 }
490 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000491
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200492 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600493 if (PyDict_CheckExact(modules)) {
494 PyDict_Clear(modules);
495 }
496 else {
497 _Py_IDENTIFIER(clear);
498 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL)
499 PyErr_Clear();
500 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200501 /* Restore the original builtins dict, to ensure that any
502 user data gets cleared. */
503 dict = PyDict_Copy(interp->builtins);
504 if (dict == NULL)
505 PyErr_Clear();
506 PyDict_Clear(interp->builtins);
507 if (PyDict_Update(interp->builtins, interp->builtins_copy))
508 PyErr_Clear();
509 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200510 /* Clear module dict copies stored in the interpreter state */
511 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200512 /* Collect references */
513 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200514 /* Dump GC stats before it's too late, since it uses the warnings
515 machinery. */
516 _PyGC_DumpShutdownStats();
517
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200518 /* Now, if there are any modules left alive, clear their globals to
519 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200520 up here, since they are kept alive in the interpreter state.
521
522 The special treatment of "builtins" here is because even
523 when it's not referenced as a module, its dictionary is
524 referenced by almost every module's __builtins__. Since
525 deleting a module clears its dictionary (even if there are
526 references left to it), we need to delete the "builtins"
527 module last. Likewise, we don't delete sys until the very
528 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200529 if (weaklist != NULL) {
530 Py_ssize_t i, n;
531 n = PyList_GET_SIZE(weaklist);
532 for (i = 0; i < n; i++) {
533 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200534 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200535 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
536 if (mod == Py_None)
537 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200538 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200539 dict = PyModule_GetDict(mod);
540 if (dict == interp->builtins || dict == interp->sysdict)
541 continue;
542 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200543 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200544 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200545 _PyModule_Clear(mod);
546 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200547 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200548 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000550
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200551 /* Next, delete sys and builtins (in that order) */
552 if (Py_VerboseFlag)
553 PySys_FormatStderr("# cleanup[3] wiping sys\n");
554 _PyModule_ClearDict(interp->sysdict);
555 if (Py_VerboseFlag)
556 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
557 _PyModule_ClearDict(interp->builtins);
558
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200559 /* Clear and delete the modules directory. Actual modules will
560 still be there only if imported during the execution of some
561 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700562 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200564
565 /* Once more */
566 _PyGC_CollectNoFail();
567
568#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000569}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000570
571
Barry Warsaw28a691b2010-04-17 00:19:56 +0000572/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573
574long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000575PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000576{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200577 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400578 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600579 PyObject *external, *pyc_magic;
580
581 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
582 if (external == NULL)
583 return -1;
584 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
585 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400586 if (pyc_magic == NULL)
587 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200588 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700589 Py_DECREF(pyc_magic);
590 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000591}
592
593
Brett Cannon3adc7b72012-07-09 14:22:12 -0400594extern const char * _PySys_ImplCacheTag;
595
Barry Warsaw28a691b2010-04-17 00:19:56 +0000596const char *
597PyImport_GetMagicTag(void)
598{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400599 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000600}
601
Brett Cannon98979b82012-07-02 15:13:11 -0400602
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603/* Magic for extension modules (built-in as well as dynamically
604 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200605 once, we keep a static dictionary 'extensions' keyed by the tuple
606 (module name, module name) (for built-in modules) or by
607 (filename, module name) (for dynamically loaded modules), containing these
608 modules. A copy of the module's dictionary is stored by calling
609 _PyImport_FixupExtensionObject() immediately after the module initialization
610 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100611 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000612
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000613 Modules which do support multiple initialization set their m_size
614 field to a non-negative number (indicating the size of the
615 module-specific state). They are still recorded in the extensions
616 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000617*/
618
619int
Victor Stinner95872862011-03-07 18:20:56 +0100620_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600621 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000622{
Eric Snowd393c1b2017-09-14 12:18:12 -0600623 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500625 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (extensions == NULL) {
627 extensions = PyDict_New();
628 if (extensions == NULL)
629 return -1;
630 }
631 if (mod == NULL || !PyModule_Check(mod)) {
632 PyErr_BadInternalCall();
633 return -1;
634 }
635 def = PyModule_GetDef(mod);
636 if (!def) {
637 PyErr_BadInternalCall();
638 return -1;
639 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600640 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return -1;
642 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600643 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return -1;
645 }
646 if (def->m_size == -1) {
647 if (def->m_base.m_copy) {
648 /* Somebody already imported the module,
649 likely under a different name.
650 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200651 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 }
653 dict = PyModule_GetDict(mod);
654 if (dict == NULL)
655 return -1;
656 def->m_base.m_copy = PyDict_Copy(dict);
657 if (def->m_base.m_copy == NULL)
658 return -1;
659 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500660 key = PyTuple_Pack(2, filename, name);
661 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200662 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500663 res = PyDict_SetItem(extensions, key, (PyObject *)def);
664 Py_DECREF(key);
665 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200666 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000668}
669
Victor Stinner49d3f252010-10-17 01:24:53 +0000670int
Eric Snowd393c1b2017-09-14 12:18:12 -0600671_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000672{
673 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100674 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100675 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100676 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000677 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600678 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100679 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000680 return res;
681}
682
Guido van Rossum25ce5661997-08-02 03:10:38 +0000683PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100684_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000685{
Eric Snowd393c1b2017-09-14 12:18:12 -0600686 PyObject *modules = PyImport_GetModuleDict();
687 return _PyImport_FindExtensionObjectEx(name, filename, modules);
688}
689
690PyObject *
691_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
692 PyObject *modules)
693{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500694 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 PyModuleDef* def;
696 if (extensions == NULL)
697 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500698 key = PyTuple_Pack(2, filename, name);
699 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200700 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500701 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
702 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (def == NULL)
704 return NULL;
705 if (def->m_size == -1) {
706 /* Module does not support repeated initialization */
707 if (def->m_base.m_copy == NULL)
708 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600709 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (mod == NULL)
711 return NULL;
712 mdict = PyModule_GetDict(mod);
713 if (mdict == NULL)
714 return NULL;
715 if (PyDict_Update(mdict, def->m_base.m_copy))
716 return NULL;
717 }
718 else {
719 if (def->m_base.m_init == NULL)
720 return NULL;
721 mod = def->m_base.m_init();
722 if (mod == NULL)
723 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600724 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200725 Py_DECREF(mod);
726 return NULL;
727 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 Py_DECREF(mod);
729 }
730 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600731 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 Py_DECREF(mod);
733 return NULL;
734 }
735 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100736 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 name, filename);
738 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000739
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740}
741
Victor Stinner49d3f252010-10-17 01:24:53 +0000742PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600743_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000744{
Victor Stinner95872862011-03-07 18:20:56 +0100745 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100746 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100747 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000748 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600749 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100750 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000751 return res;
752}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000753
754/* Get the module object corresponding to a module name.
755 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000756 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000757 Because the former action is most common, THIS DOES NOT RETURN A
758 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759
Guido van Rossum79f25d91997-04-29 20:08:16 +0000760PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000761PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600764 return _PyImport_AddModuleObject(name, modules);
765}
766
767PyObject *
768_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
769{
Eric Snow86b7afd2017-09-04 17:54:09 -0600770 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600771 if (PyDict_CheckExact(modules)) {
772 m = PyDict_GetItemWithError(modules, name);
773 }
774 else {
775 m = PyObject_GetItem(modules, name);
776 // For backward-comaptibility we copy the behavior
777 // of PyDict_GetItemWithError().
778 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
779 PyErr_Clear();
780 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200781 }
782 if (PyErr_Occurred()) {
783 return NULL;
784 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600785 if (m != NULL && PyModule_Check(m)) {
786 return m;
787 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000788 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (m == NULL)
790 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600791 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 Py_DECREF(m);
793 return NULL;
794 }
795 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000798}
799
Victor Stinner27ee0892011-03-04 12:57:09 +0000800PyObject *
801PyImport_AddModule(const char *name)
802{
803 PyObject *nameobj, *module;
804 nameobj = PyUnicode_FromString(name);
805 if (nameobj == NULL)
806 return NULL;
807 module = PyImport_AddModuleObject(nameobj);
808 Py_DECREF(nameobj);
809 return module;
810}
811
812
Tim Peters1cd70172004-08-02 03:52:12 +0000813/* Remove name from sys.modules, if it's there. */
814static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000815remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject *modules = PyImport_GetModuleDict();
Eric Snow3f9eee62017-09-15 16:35:20 -0600818 if (PyMapping_DelItem(modules, name) < 0) {
819 if (!PyMapping_HasKey(modules, name)) {
820 return;
821 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 Py_FatalError("import: deleting existing key in"
823 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600824 }
Tim Peters1cd70172004-08-02 03:52:12 +0000825}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000826
Christian Heimes3b06e532008-01-07 20:12:44 +0000827
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000828/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000829 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
830 * removed from sys.modules, to avoid leaving damaged module objects
831 * in sys.modules. The caller may wish to restore the original
832 * module object (if any) in this case; PyImport_ReloadModule is an
833 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000834 *
835 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
836 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000837 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000838PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300839PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 return PyImport_ExecCodeModuleWithPathnames(
842 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000843}
844
845PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300846PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 return PyImport_ExecCodeModuleWithPathnames(
849 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000850}
851
852PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300853PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
854 const char *pathname,
855 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000856{
Victor Stinner27ee0892011-03-04 12:57:09 +0000857 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600858 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000859
860 nameobj = PyUnicode_FromString(name);
861 if (nameobj == NULL)
862 return NULL;
863
Victor Stinner27ee0892011-03-04 12:57:09 +0000864 if (cpathname != NULL) {
865 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
866 if (cpathobj == NULL)
867 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400868 }
869 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000870 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400871
872 if (pathname != NULL) {
873 pathobj = PyUnicode_DecodeFSDefault(pathname);
874 if (pathobj == NULL)
875 goto error;
876 }
877 else if (cpathobj != NULL) {
878 PyInterpreterState *interp = PyThreadState_GET()->interp;
879 _Py_IDENTIFIER(_get_sourcefile);
880
881 if (interp == NULL) {
882 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
883 "no interpreter!");
884 }
885
Eric Snow32439d62015-05-02 19:15:18 -0600886 external= PyObject_GetAttrString(interp->importlib,
887 "_bootstrap_external");
888 if (external != NULL) {
889 pathobj = _PyObject_CallMethodIdObjArgs(external,
890 &PyId__get_sourcefile, cpathobj,
891 NULL);
892 Py_DECREF(external);
893 }
Brett Cannona6473f92012-07-13 13:57:03 -0400894 if (pathobj == NULL)
895 PyErr_Clear();
896 }
897 else
898 pathobj = NULL;
899
Victor Stinner27ee0892011-03-04 12:57:09 +0000900 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
901error:
902 Py_DECREF(nameobj);
903 Py_XDECREF(pathobj);
904 Py_XDECREF(cpathobj);
905 return m;
906}
907
Brett Cannon18fc4e72014-04-04 10:01:46 -0400908static PyObject *
909module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000910{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400911 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912
Victor Stinner27ee0892011-03-04 12:57:09 +0000913 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (m == NULL)
915 return NULL;
916 /* If the module is being reloaded, we get the old module back
917 and re-use its dict to exec the new code. */
918 d = PyModule_GetDict(m);
919 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
920 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400921 PyEval_GetBuiltins()) != 0) {
922 remove_module(name);
923 return NULL;
924 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400926
Eric Snow08197a42014-05-12 17:54:55 -0600927 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400928}
929
930static PyObject *
931exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
932{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400933 PyObject *v, *m;
934
935 v = PyEval_EvalCode(code_object, module_dict, module_dict);
936 if (v == NULL) {
937 remove_module(name);
938 return NULL;
939 }
940 Py_DECREF(v);
941
Eric Snow3f9eee62017-09-15 16:35:20 -0600942 m = PyImport_GetModule(name);
943 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400944 PyErr_Format(PyExc_ImportError,
945 "Loaded module %R not found in sys.modules",
946 name);
947 return NULL;
948 }
949
Brett Cannon18fc4e72014-04-04 10:01:46 -0400950 return m;
951}
952
953PyObject*
954PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
955 PyObject *cpathname)
956{
Eric Snow32439d62015-05-02 19:15:18 -0600957 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600958 PyInterpreterState *interp = PyThreadState_GET()->interp;
959 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400960
961 d = module_dict_for_exec(name);
962 if (d == NULL) {
963 return NULL;
964 }
965
Eric Snow08197a42014-05-12 17:54:55 -0600966 if (pathname == NULL) {
967 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 }
Eric Snow32439d62015-05-02 19:15:18 -0600969 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
970 if (external == NULL)
971 return NULL;
972 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600973 &PyId__fix_up_module,
974 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600975 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600976 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600977 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600978 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 }
Eric Snow08197a42014-05-12 17:54:55 -0600980 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000981}
982
983
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000984static void
985update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyObject *constants, *tmp;
988 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (PyUnicode_Compare(co->co_filename, oldname))
991 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000992
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200993 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300994 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 constants = co->co_consts;
997 n = PyTuple_GET_SIZE(constants);
998 for (i = 0; i < n; i++) {
999 tmp = PyTuple_GET_ITEM(constants, i);
1000 if (PyCode_Check(tmp))
1001 update_code_filenames((PyCodeObject *)tmp,
1002 oldname, newname);
1003 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001004}
1005
Victor Stinner2f42ae52011-03-20 00:41:24 +01001006static void
1007update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001008{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001009 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001010
Victor Stinner2f42ae52011-03-20 00:41:24 +01001011 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1012 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 oldname = co->co_filename;
1015 Py_INCREF(oldname);
1016 update_code_filenames(co, oldname, newname);
1017 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001018}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001019
Brett Cannon4caa61d2014-01-09 19:03:32 -05001020/*[clinic input]
1021_imp._fix_co_filename
1022
1023 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1024 Code object to change.
1025
1026 path: unicode
1027 File path to use.
1028 /
1029
1030Changes code.co_filename to specify the passed-in file path.
1031[clinic start generated code]*/
1032
Brett Cannon4caa61d2014-01-09 19:03:32 -05001033static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001034_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001035 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001036/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001037
Brett Cannon4caa61d2014-01-09 19:03:32 -05001038{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001039 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001040
1041 Py_RETURN_NONE;
1042}
1043
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001044
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001045/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001046static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001047
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001048
1049/* Helper to test for built-in module */
1050
1051static int
Victor Stinner95872862011-03-07 18:20:56 +01001052is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001053{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001054 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001056 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (PyImport_Inittab[i].initfunc == NULL)
1058 return -1;
1059 else
1060 return 1;
1061 }
1062 }
1063 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001064}
1065
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001066
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001067/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001068 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001069 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001070 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001071 this tells our caller that the path based finder could not find
1072 a finder for this path item. Cache the result in
1073 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001074 Returns a borrowed reference. */
1075
1076static PyObject *
1077get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyObject *importer;
1081 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 /* These conditions are the caller's responsibility: */
1084 assert(PyList_Check(path_hooks));
1085 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 nhooks = PyList_Size(path_hooks);
1088 if (nhooks < 0)
1089 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 importer = PyDict_GetItem(path_importer_cache, p);
1092 if (importer != NULL)
1093 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 /* set path_importer_cache[p] to None to avoid recursion */
1096 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1097 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 for (j = 0; j < nhooks; j++) {
1100 PyObject *hook = PyList_GetItem(path_hooks, j);
1101 if (hook == NULL)
1102 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001103 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 if (importer != NULL)
1105 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1108 return NULL;
1109 }
1110 PyErr_Clear();
1111 }
1112 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001113 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 }
1115 if (importer != NULL) {
1116 int err = PyDict_SetItem(path_importer_cache, p, importer);
1117 Py_DECREF(importer);
1118 if (err != 0)
1119 return NULL;
1120 }
1121 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001122}
1123
Christian Heimes9cd17752007-11-18 19:35:23 +00001124PyAPI_FUNC(PyObject *)
1125PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001127
Victor Stinner1e53bba2013-07-16 22:26:05 +02001128 path_importer_cache = PySys_GetObject("path_importer_cache");
1129 path_hooks = PySys_GetObject("path_hooks");
1130 if (path_importer_cache != NULL && path_hooks != NULL) {
1131 importer = get_path_importer(path_importer_cache,
1132 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
1134 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1135 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001136}
1137
Nick Coghland5cacbb2015-05-23 22:24:10 +10001138/*[clinic input]
1139_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001140
Nick Coghland5cacbb2015-05-23 22:24:10 +10001141 spec: object
1142 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001143
Nick Coghland5cacbb2015-05-23 22:24:10 +10001144Create an extension module.
1145[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001146
Nick Coghland5cacbb2015-05-23 22:24:10 +10001147static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001148_imp_create_builtin(PyObject *module, PyObject *spec)
1149/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001152 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001153 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001154 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001155
Nick Coghland5cacbb2015-05-23 22:24:10 +10001156 name = PyObject_GetAttrString(spec, "name");
1157 if (name == NULL) {
1158 return NULL;
1159 }
1160
Victor Stinner5eb4f592013-11-14 22:38:52 +01001161 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001162 if (mod || PyErr_Occurred()) {
1163 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001164 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001165 return mod;
1166 }
1167
1168 namestr = PyUnicode_AsUTF8(name);
1169 if (namestr == NULL) {
1170 Py_DECREF(name);
1171 return NULL;
1172 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001173
Eric Snowd393c1b2017-09-14 12:18:12 -06001174 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001176 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001177 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001179 /* Cannot re-init internal module ("sys" or "builtins") */
1180 mod = PyImport_AddModule(namestr);
1181 Py_DECREF(name);
1182 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001185 if (mod == NULL) {
1186 Py_DECREF(name);
1187 return NULL;
1188 }
1189 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1190 Py_DECREF(name);
1191 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1192 } else {
1193 /* Remember pointer to module init function. */
1194 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001195 if (def == NULL) {
1196 Py_DECREF(name);
1197 return NULL;
1198 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001199 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001200 if (modules == NULL) {
1201 modules = PyImport_GetModuleDict();
1202 }
1203 if (_PyImport_FixupExtensionObject(mod, name, name,
1204 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001205 Py_DECREF(name);
1206 return NULL;
1207 }
1208 Py_DECREF(name);
1209 return mod;
1210 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 }
1212 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001213 Py_DECREF(name);
1214 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001215}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001216
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001217
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001218/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001219
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001220static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001221find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001222{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001223 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001224
Victor Stinner53dc7352011-03-20 01:50:21 +01001225 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 for (p = PyImport_FrozenModules; ; p++) {
1229 if (p->name == NULL)
1230 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001231 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 break;
1233 }
1234 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001235}
1236
Guido van Rossum79f25d91997-04-29 20:08:16 +00001237static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001238get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001239{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001240 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (p == NULL) {
1244 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001245 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 name);
1247 return NULL;
1248 }
1249 if (p->code == NULL) {
1250 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001251 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 name);
1253 return NULL;
1254 }
1255 size = p->size;
1256 if (size < 0)
1257 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001258 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001259}
1260
Brett Cannon8d110132009-03-15 02:20:16 +00001261static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001262is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001263{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001264 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (p == NULL) {
1268 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001269 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 name);
1271 return NULL;
1272 }
Brett Cannon8d110132009-03-15 02:20:16 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (size < 0)
1277 Py_RETURN_TRUE;
1278 else
1279 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001280}
1281
1282
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001283/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001284 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001285 an exception set if the initialization failed.
1286 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001287
1288int
Victor Stinner53dc7352011-03-20 01:50:21 +01001289PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001290{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001291 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001292 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 int ispackage;
1294 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001295
Victor Stinner53dc7352011-03-20 01:50:21 +01001296 p = find_frozen(name);
1297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (p == NULL)
1299 return 0;
1300 if (p->code == NULL) {
1301 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001302 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 name);
1304 return -1;
1305 }
1306 size = p->size;
1307 ispackage = (size < 0);
1308 if (ispackage)
1309 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001310 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (co == NULL)
1312 return -1;
1313 if (!PyCode_Check(co)) {
1314 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001315 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 name);
1317 goto err_return;
1318 }
1319 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001320 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001321 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001323 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (m == NULL)
1325 goto err_return;
1326 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001327 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 goto err_return;
1330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 err = PyDict_SetItemString(d, "__path__", l);
1332 Py_DECREF(l);
1333 if (err != 0)
1334 goto err_return;
1335 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001336 d = module_dict_for_exec(name);
1337 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001338 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001339 }
1340 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 if (m == NULL)
1342 goto err_return;
1343 Py_DECREF(co);
1344 Py_DECREF(m);
1345 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001346err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 Py_DECREF(co);
1348 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001349}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001350
Victor Stinner53dc7352011-03-20 01:50:21 +01001351int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001352PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001353{
1354 PyObject *nameobj;
1355 int ret;
1356 nameobj = PyUnicode_InternFromString(name);
1357 if (nameobj == NULL)
1358 return -1;
1359 ret = PyImport_ImportFrozenModuleObject(nameobj);
1360 Py_DECREF(nameobj);
1361 return ret;
1362}
1363
Guido van Rossum74e6a111994-08-29 12:54:38 +00001364
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001365/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001366 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001367
Guido van Rossum79f25d91997-04-29 20:08:16 +00001368PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001369PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 PyObject *pname;
1372 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 pname = PyUnicode_FromString(name);
1375 if (pname == NULL)
1376 return NULL;
1377 result = PyImport_Import(pname);
1378 Py_DECREF(pname);
1379 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001380}
1381
Christian Heimes072c0f12008-01-03 23:01:04 +00001382/* Import a module without blocking
1383 *
1384 * At first it tries to fetch the module from sys.modules. If the module was
1385 * never loaded before it loads it with PyImport_ImportModule() unless another
1386 * thread holds the import lock. In the latter case the function raises an
1387 * ImportError instead of blocking.
1388 *
1389 * Returns the module object with incremented ref count.
1390 */
1391PyObject *
1392PyImport_ImportModuleNoBlock(const char *name)
1393{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001394 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001395}
1396
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001397
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001398/* Remove importlib frames from the traceback,
1399 * except in Verbose mode. */
1400static void
1401remove_importlib_frames(void)
1402{
1403 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001404 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001405 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001406 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001407 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001408 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001409 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001410
1411 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001412 from the traceback. We always trim chunks
1413 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001414
1415 PyErr_Fetch(&exception, &value, &base_tb);
1416 if (!exception || Py_VerboseFlag)
1417 goto done;
1418 if (PyType_IsSubtype((PyTypeObject *) exception,
1419 (PyTypeObject *) PyExc_ImportError))
1420 always_trim = 1;
1421
1422 prev_link = &base_tb;
1423 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001424 while (tb != NULL) {
1425 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1426 PyObject *next = (PyObject *) traceback->tb_next;
1427 PyFrameObject *frame = traceback->tb_frame;
1428 PyCodeObject *code = frame->f_code;
1429 int now_in_importlib;
1430
1431 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001432 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1433 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001434 if (now_in_importlib && !in_importlib) {
1435 /* This is the link to this chunk of importlib tracebacks */
1436 outer_link = prev_link;
1437 }
1438 in_importlib = now_in_importlib;
1439
1440 if (in_importlib &&
1441 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001442 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001443 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001444 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001445 prev_link = outer_link;
1446 }
1447 else {
1448 prev_link = (PyObject **) &traceback->tb_next;
1449 }
1450 tb = next;
1451 }
1452done:
1453 PyErr_Restore(exception, value, base_tb);
1454}
1455
1456
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001457static PyObject *
1458resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001459{
Eric Snowb523f842013-11-22 09:05:39 -07001460 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001461 _Py_IDENTIFIER(__package__);
1462 _Py_IDENTIFIER(__path__);
1463 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001464 _Py_IDENTIFIER(parent);
1465 PyObject *abs_name;
1466 PyObject *package = NULL;
1467 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001468 Py_ssize_t last_dot;
1469 PyObject *base;
1470 int level_up;
1471
1472 if (globals == NULL) {
1473 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1474 goto error;
1475 }
1476 if (!PyDict_Check(globals)) {
1477 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1478 goto error;
1479 }
1480 package = _PyDict_GetItemId(globals, &PyId___package__);
1481 if (package == Py_None) {
1482 package = NULL;
1483 }
1484 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1485
1486 if (package != NULL) {
1487 Py_INCREF(package);
1488 if (!PyUnicode_Check(package)) {
1489 PyErr_SetString(PyExc_TypeError, "package must be a string");
1490 goto error;
1491 }
1492 else if (spec != NULL && spec != Py_None) {
1493 int equal;
1494 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1495 if (parent == NULL) {
1496 goto error;
1497 }
1498
1499 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1500 Py_DECREF(parent);
1501 if (equal < 0) {
1502 goto error;
1503 }
1504 else if (equal == 0) {
1505 if (PyErr_WarnEx(PyExc_ImportWarning,
1506 "__package__ != __spec__.parent", 1) < 0) {
1507 goto error;
1508 }
1509 }
1510 }
1511 }
1512 else if (spec != NULL && spec != Py_None) {
1513 package = _PyObject_GetAttrId(spec, &PyId_parent);
1514 if (package == NULL) {
1515 goto error;
1516 }
1517 else if (!PyUnicode_Check(package)) {
1518 PyErr_SetString(PyExc_TypeError,
1519 "__spec__.parent must be a string");
1520 goto error;
1521 }
1522 }
1523 else {
1524 if (PyErr_WarnEx(PyExc_ImportWarning,
1525 "can't resolve package from __spec__ or __package__, "
1526 "falling back on __name__ and __path__", 1) < 0) {
1527 goto error;
1528 }
1529
1530 package = _PyDict_GetItemId(globals, &PyId___name__);
1531 if (package == NULL) {
1532 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1533 goto error;
1534 }
1535
1536 Py_INCREF(package);
1537 if (!PyUnicode_Check(package)) {
1538 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1539 goto error;
1540 }
1541
1542 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1543 Py_ssize_t dot;
1544
1545 if (PyUnicode_READY(package) < 0) {
1546 goto error;
1547 }
1548
1549 dot = PyUnicode_FindChar(package, '.',
1550 0, PyUnicode_GET_LENGTH(package), -1);
1551 if (dot == -2) {
1552 goto error;
1553 }
1554
1555 if (dot >= 0) {
1556 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1557 if (substr == NULL) {
1558 goto error;
1559 }
1560 Py_SETREF(package, substr);
1561 }
1562 }
1563 }
1564
1565 last_dot = PyUnicode_GET_LENGTH(package);
1566 if (last_dot == 0) {
1567 PyErr_SetString(PyExc_ImportError,
1568 "attempted relative import with no known parent package");
1569 goto error;
1570 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001571
1572 for (level_up = 1; level_up < level; level_up += 1) {
1573 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1574 if (last_dot == -2) {
1575 goto error;
1576 }
1577 else if (last_dot == -1) {
1578 PyErr_SetString(PyExc_ValueError,
1579 "attempted relative import beyond top-level "
1580 "package");
1581 goto error;
1582 }
1583 }
1584
1585 base = PyUnicode_Substring(package, 0, last_dot);
1586 Py_DECREF(package);
1587 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1588 return base;
1589 }
1590
1591 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1592 Py_DECREF(base);
1593 return abs_name;
1594
1595 error:
1596 Py_XDECREF(package);
1597 return NULL;
1598}
1599
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001600static PyObject *
1601import_find_and_load(PyObject *abs_name)
1602{
1603 _Py_IDENTIFIER(_find_and_load);
1604 PyObject *mod = NULL;
1605 PyInterpreterState *interp = PyThreadState_GET()->interp;
1606 int import_time = interp->core_config.import_time;
1607 static int import_level;
1608 static _PyTime_t accumulated;
1609
1610 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1611
1612 /* XOptions is initialized after first some imports.
1613 * So we can't have negative cache before completed initialization.
1614 * Anyway, importlib._find_and_load is much slower than
1615 * _PyDict_GetItemIdWithError().
1616 */
1617 if (import_time) {
1618 static int header = 1;
1619 if (header) {
1620 fputs("import time: self [us] | cumulative | imported package\n",
1621 stderr);
1622 header = 0;
1623 }
1624
1625 import_level++;
1626 t1 = _PyTime_GetPerfCounter();
1627 accumulated = 0;
1628 }
1629
1630 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1631 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1632
1633 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1634 &PyId__find_and_load, abs_name,
1635 interp->import_func, NULL);
1636
1637 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1638 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1639 mod != NULL);
1640
1641 if (import_time) {
1642 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1643
1644 import_level--;
1645 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1646 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1647 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1648 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1649
1650 accumulated = accumulated_copy + cum;
1651 }
1652
1653 return mod;
1654}
1655
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001656PyObject *
1657PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1658 PyObject *locals, PyObject *fromlist,
1659 int level)
1660{
Brett Cannonfd074152012-04-14 14:10:13 -04001661 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001662 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001663 PyObject *final_mod = NULL;
1664 PyObject *mod = NULL;
1665 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001666 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001667 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001668
Brett Cannonfd074152012-04-14 14:10:13 -04001669 if (name == NULL) {
1670 PyErr_SetString(PyExc_ValueError, "Empty module name");
1671 goto error;
1672 }
1673
1674 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1675 for added performance. */
1676
1677 if (!PyUnicode_Check(name)) {
1678 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1679 goto error;
1680 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001681 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001682 goto error;
1683 }
1684 if (level < 0) {
1685 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1686 goto error;
1687 }
Brett Cannon849113a2016-01-22 15:25:50 -08001688
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001689 if (level > 0) {
1690 abs_name = resolve_name(name, globals, level);
1691 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001692 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001693 }
1694 else { /* level == 0 */
1695 if (PyUnicode_GET_LENGTH(name) == 0) {
1696 PyErr_SetString(PyExc_ValueError, "Empty module name");
1697 goto error;
1698 }
Brett Cannonfd074152012-04-14 14:10:13 -04001699 abs_name = name;
1700 Py_INCREF(abs_name);
1701 }
1702
Eric Snow3f9eee62017-09-15 16:35:20 -06001703 mod = PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001704 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001705 _Py_IDENTIFIER(__spec__);
1706 _Py_IDENTIFIER(_initializing);
1707 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001708 PyObject *value = NULL;
1709 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001710 int initializing = 0;
1711
Antoine Pitrou03989852012-08-28 00:24:52 +02001712 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001713 __spec__._initializing is true.
1714 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001715 stuffing the new module in sys.modules.
1716 */
Eric Snowb523f842013-11-22 09:05:39 -07001717 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1718 if (spec != NULL) {
1719 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1720 Py_DECREF(spec);
1721 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001722 if (value == NULL)
1723 PyErr_Clear();
1724 else {
1725 initializing = PyObject_IsTrue(value);
1726 Py_DECREF(value);
1727 if (initializing == -1)
1728 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001729 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001730 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1731 &PyId__lock_unlock_module, abs_name,
1732 NULL);
1733 if (value == NULL)
1734 goto error;
1735 Py_DECREF(value);
1736 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001737 }
Brett Cannonfd074152012-04-14 14:10:13 -04001738 }
1739 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001740 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001741 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001742 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001743 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001744 }
1745 }
1746
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001747 has_from = 0;
1748 if (fromlist != NULL && fromlist != Py_None) {
1749 has_from = PyObject_IsTrue(fromlist);
1750 if (has_from < 0)
1751 goto error;
1752 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001753 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001754 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1755 if (level == 0 || len > 0) {
1756 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001757
Victor Stinner744c34e2016-05-20 11:36:13 +02001758 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1759 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001760 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001761 }
1762
Victor Stinner744c34e2016-05-20 11:36:13 +02001763 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001764 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001765 final_mod = mod;
1766 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001767 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001768 }
1769
Brett Cannonfd074152012-04-14 14:10:13 -04001770 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001771 PyObject *front = PyUnicode_Substring(name, 0, dot);
1772 if (front == NULL) {
1773 goto error;
1774 }
1775
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001776 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001777 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001778 }
1779 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001780 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001781 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001782 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001783 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001784 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001785 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001786 }
Brett Cannonfd074152012-04-14 14:10:13 -04001787
Eric Snow3f9eee62017-09-15 16:35:20 -06001788 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001789 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001790 if (final_mod == NULL) {
1791 PyErr_Format(PyExc_KeyError,
1792 "%R not in sys.modules as expected",
1793 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001794 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001795 }
Brett Cannonfd074152012-04-14 14:10:13 -04001796 }
1797 }
1798 else {
1799 final_mod = mod;
1800 Py_INCREF(mod);
1801 }
1802 }
1803 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001804 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001805 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001806 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001807 NULL);
1808 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001809
Brett Cannonfd074152012-04-14 14:10:13 -04001810 error:
1811 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001812 Py_XDECREF(mod);
1813 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001814 if (final_mod == NULL)
1815 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001816 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001817}
1818
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001819PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001820PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001821 PyObject *fromlist, int level)
1822{
1823 PyObject *nameobj, *mod;
1824 nameobj = PyUnicode_FromString(name);
1825 if (nameobj == NULL)
1826 return NULL;
1827 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1828 fromlist, level);
1829 Py_DECREF(nameobj);
1830 return mod;
1831}
1832
1833
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001834/* Re-import a module of any kind and return its module object, WITH
1835 INCREMENTED REFERENCE COUNT */
1836
Guido van Rossum79f25d91997-04-29 20:08:16 +00001837PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001838PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001839{
Eric Snow3f9eee62017-09-15 16:35:20 -06001840 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001841 _Py_IDENTIFIER(reload);
1842 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001843 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001844 if (imp == NULL) {
1845 imp = PyImport_ImportModule("imp");
1846 if (imp == NULL) {
1847 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001850
Victor Stinner55ba38a2016-12-09 16:09:30 +01001851 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001852 Py_DECREF(imp);
1853 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001854}
1855
1856
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001857/* Higher-level import emulator which emulates the "import" statement
1858 more accurately -- it invokes the __import__() function from the
1859 builtins of the current globals. This means that the import is
1860 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001861 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001862 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001863 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001864 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001865
1866PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001867PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 static PyObject *silly_list = NULL;
1870 static PyObject *builtins_str = NULL;
1871 static PyObject *import_str = NULL;
1872 PyObject *globals = NULL;
1873 PyObject *import = NULL;
1874 PyObject *builtins = NULL;
1875 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 /* Initialize constant string objects */
1878 if (silly_list == NULL) {
1879 import_str = PyUnicode_InternFromString("__import__");
1880 if (import_str == NULL)
1881 return NULL;
1882 builtins_str = PyUnicode_InternFromString("__builtins__");
1883 if (builtins_str == NULL)
1884 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001885 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (silly_list == NULL)
1887 return NULL;
1888 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 /* Get the builtins from current globals */
1891 globals = PyEval_GetGlobals();
1892 if (globals != NULL) {
1893 Py_INCREF(globals);
1894 builtins = PyObject_GetItem(globals, builtins_str);
1895 if (builtins == NULL)
1896 goto err;
1897 }
1898 else {
1899 /* No globals -- use standard builtins, and fake globals */
1900 builtins = PyImport_ImportModuleLevel("builtins",
1901 NULL, NULL, NULL, 0);
1902 if (builtins == NULL)
1903 return NULL;
1904 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1905 if (globals == NULL)
1906 goto err;
1907 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 /* Get the __import__ function from the builtins */
1910 if (PyDict_Check(builtins)) {
1911 import = PyObject_GetItem(builtins, import_str);
1912 if (import == NULL)
1913 PyErr_SetObject(PyExc_KeyError, import_str);
1914 }
1915 else
1916 import = PyObject_GetAttr(builtins, import_str);
1917 if (import == NULL)
1918 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001921 Always use absolute import here.
1922 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1924 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001925 if (r == NULL)
1926 goto err;
1927 Py_DECREF(r);
1928
Eric Snow3f9eee62017-09-15 16:35:20 -06001929 r = PyImport_GetModule(module_name);
1930 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001931 PyErr_SetObject(PyExc_KeyError, module_name);
1932 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001933
1934 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 Py_XDECREF(globals);
1936 Py_XDECREF(builtins);
1937 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001940}
1941
Brett Cannon4caa61d2014-01-09 19:03:32 -05001942/*[clinic input]
1943_imp.extension_suffixes
1944
1945Returns the list of file suffixes used to identify extension modules.
1946[clinic start generated code]*/
1947
Brett Cannon4caa61d2014-01-09 19:03:32 -05001948static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001949_imp_extension_suffixes_impl(PyObject *module)
1950/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001953 const char *suffix;
1954 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 list = PyList_New(0);
1957 if (list == NULL)
1958 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001959#ifdef HAVE_DYNAMIC_LOADING
1960 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1961 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (item == NULL) {
1963 Py_DECREF(list);
1964 return NULL;
1965 }
1966 if (PyList_Append(list, item) < 0) {
1967 Py_DECREF(list);
1968 Py_DECREF(item);
1969 return NULL;
1970 }
1971 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001972 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 }
Brett Cannon2657df42012-05-04 15:20:40 -04001974#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001976}
1977
Brett Cannon4caa61d2014-01-09 19:03:32 -05001978/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001979_imp.init_frozen
1980
1981 name: unicode
1982 /
1983
1984Initializes a frozen module.
1985[clinic start generated code]*/
1986
Brett Cannon4caa61d2014-01-09 19:03:32 -05001987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001988_imp_init_frozen_impl(PyObject *module, PyObject *name)
1989/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 int ret;
1992 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001993
Victor Stinner53dc7352011-03-20 01:50:21 +01001994 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (ret < 0)
1996 return NULL;
1997 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001998 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002000 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 Py_XINCREF(m);
2002 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002003}
2004
Brett Cannon4caa61d2014-01-09 19:03:32 -05002005/*[clinic input]
2006_imp.get_frozen_object
2007
2008 name: unicode
2009 /
2010
2011Create a code object for a frozen module.
2012[clinic start generated code]*/
2013
Brett Cannon4caa61d2014-01-09 19:03:32 -05002014static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002015_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2016/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002019}
2020
Brett Cannon4caa61d2014-01-09 19:03:32 -05002021/*[clinic input]
2022_imp.is_frozen_package
2023
2024 name: unicode
2025 /
2026
2027Returns True if the module name is of a frozen package.
2028[clinic start generated code]*/
2029
Brett Cannon4caa61d2014-01-09 19:03:32 -05002030static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002031_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2032/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002035}
2036
Brett Cannon4caa61d2014-01-09 19:03:32 -05002037/*[clinic input]
2038_imp.is_builtin
2039
2040 name: unicode
2041 /
2042
2043Returns True if the module name corresponds to a built-in module.
2044[clinic start generated code]*/
2045
Guido van Rossum79f25d91997-04-29 20:08:16 +00002046static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002047_imp_is_builtin_impl(PyObject *module, PyObject *name)
2048/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002049{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002050 return PyLong_FromLong(is_builtin(name));
2051}
2052
2053/*[clinic input]
2054_imp.is_frozen
2055
2056 name: unicode
2057 /
2058
2059Returns True if the module name corresponds to a frozen module.
2060[clinic start generated code]*/
2061
Brett Cannon4caa61d2014-01-09 19:03:32 -05002062static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002063_imp_is_frozen_impl(PyObject *module, PyObject *name)
2064/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002065{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002066 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 p = find_frozen(name);
2069 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002070}
2071
Larry Hastings1df0b352015-08-24 19:53:56 -07002072/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2073static int
2074exec_builtin_or_dynamic(PyObject *mod) {
2075 PyModuleDef *def;
2076 void *state;
2077
2078 if (!PyModule_Check(mod)) {
2079 return 0;
2080 }
2081
2082 def = PyModule_GetDef(mod);
2083 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002084 return 0;
2085 }
Brett Cannon52794db2016-09-07 17:00:43 -07002086
Larry Hastings1df0b352015-08-24 19:53:56 -07002087 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002088 if (state) {
2089 /* Already initialized; skip reload */
2090 return 0;
2091 }
Brett Cannon52794db2016-09-07 17:00:43 -07002092
Larry Hastings1df0b352015-08-24 19:53:56 -07002093 return PyModule_ExecDef(mod, def);
2094}
2095
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002096#ifdef HAVE_DYNAMIC_LOADING
2097
Brett Cannon4caa61d2014-01-09 19:03:32 -05002098/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002099_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002100
Nick Coghland5cacbb2015-05-23 22:24:10 +10002101 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002102 file: object = NULL
2103 /
2104
Nick Coghland5cacbb2015-05-23 22:24:10 +10002105Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002106[clinic start generated code]*/
2107
Brett Cannon4caa61d2014-01-09 19:03:32 -05002108static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002109_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2110/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002111{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002112 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002113 FILE *fp;
2114
Nick Coghland5cacbb2015-05-23 22:24:10 +10002115 name = PyObject_GetAttrString(spec, "name");
2116 if (name == NULL) {
2117 return NULL;
2118 }
2119
2120 path = PyObject_GetAttrString(spec, "origin");
2121 if (path == NULL) {
2122 Py_DECREF(name);
2123 return NULL;
2124 }
2125
2126 mod = _PyImport_FindExtensionObject(name, path);
2127 if (mod != NULL) {
2128 Py_DECREF(name);
2129 Py_DECREF(path);
2130 Py_INCREF(mod);
2131 return mod;
2132 }
2133
Brett Cannon4caa61d2014-01-09 19:03:32 -05002134 if (file != NULL) {
2135 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002136 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002137 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002138 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002142 else
2143 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002144
2145 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2146
2147 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002148 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (fp)
2150 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002151 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002152}
2153
Nick Coghland5cacbb2015-05-23 22:24:10 +10002154/*[clinic input]
2155_imp.exec_dynamic -> int
2156
2157 mod: object
2158 /
2159
2160Initialize an extension module.
2161[clinic start generated code]*/
2162
2163static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002164_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2165/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002166{
Larry Hastings1df0b352015-08-24 19:53:56 -07002167 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002168}
2169
2170
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002171#endif /* HAVE_DYNAMIC_LOADING */
2172
Larry Hastings7726ac92014-01-31 22:03:12 -08002173/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002174_imp.exec_builtin -> int
2175
2176 mod: object
2177 /
2178
2179Initialize a built-in module.
2180[clinic start generated code]*/
2181
2182static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002183_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2184/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002185{
2186 return exec_builtin_or_dynamic(mod);
2187}
2188
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002189/*[clinic input]
2190_imp.source_hash
2191
2192 key: long
2193 source: Py_buffer
2194[clinic start generated code]*/
2195
2196static PyObject *
2197_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2198/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2199{
Benjamin Peterson83620772017-12-09 12:18:56 -08002200 union {
2201 uint64_t x;
2202 char data[sizeof(uint64_t)];
2203 } hash;
2204 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002205#if !PY_LITTLE_ENDIAN
2206 // Force to little-endian. There really ought to be a succinct standard way
2207 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002208 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2209 char tmp = hash.data[i];
2210 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2211 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002212 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002213#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002214 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002215}
2216
Barry Warsaw28a691b2010-04-17 00:19:56 +00002217
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002218PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002219"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002220
Guido van Rossum79f25d91997-04-29 20:08:16 +00002221static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002222 _IMP_EXTENSION_SUFFIXES_METHODDEF
2223 _IMP_LOCK_HELD_METHODDEF
2224 _IMP_ACQUIRE_LOCK_METHODDEF
2225 _IMP_RELEASE_LOCK_METHODDEF
2226 _IMP_GET_FROZEN_OBJECT_METHODDEF
2227 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002228 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002229 _IMP_INIT_FROZEN_METHODDEF
2230 _IMP_IS_BUILTIN_METHODDEF
2231 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002232 _IMP_CREATE_DYNAMIC_METHODDEF
2233 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002234 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002235 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002236 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002237 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002238};
2239
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002240
Martin v. Löwis1a214512008-06-11 05:26:20 +00002241static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002243 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 doc_imp,
2245 0,
2246 imp_methods,
2247 NULL,
2248 NULL,
2249 NULL,
2250 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002251};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002252
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002253const char *_Py_CheckHashBasedPycsMode = "default";
2254
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002255PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002256PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 m = PyModule_Create(&impmodule);
2261 if (m == NULL)
2262 goto failure;
2263 d = PyModule_GetDict(m);
2264 if (d == NULL)
2265 goto failure;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002266 PyObject *pyc_mode = PyUnicode_FromString(_Py_CheckHashBasedPycsMode);
2267 if (pyc_mode == NULL) {
2268 goto failure;
2269 }
2270 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2271 Py_DECREF(pyc_mode);
2272 goto failure;
2273 }
2274 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002277 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 Py_XDECREF(m);
2279 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002280}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002281
2282
Guido van Rossumb18618d2000-05-03 23:44:39 +00002283/* API for embedding applications that want to add their own entries
2284 to the table of built-in modules. This should normally be called
2285 *before* Py_Initialize(). When the table resize fails, -1 is
2286 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002287
2288 After a similar function by Just van Rossum. */
2289
2290int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002291PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 struct _inittab *p;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002294 Py_ssize_t i, n;
2295 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Count the number of entries in both tables */
2298 for (n = 0; newtab[n].name != NULL; n++)
2299 ;
2300 if (n == 0)
2301 return 0; /* Nothing to do */
2302 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2303 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002304
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002305 /* Force default raw memory allocator to get a known allocator to be able
2306 to release the memory in _PyImport_Fini2() */
2307 PyMemAllocatorEx old_alloc;
2308 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Allocate new memory for the combined table */
Victor Stinnerd2337962017-12-12 23:29:28 +01002311 if ((i + n + 1) <= PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(struct _inittab)) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002312 size_t size = sizeof(struct _inittab) * (i + n + 1);
2313 p = PyMem_RawRealloc(inittab_copy, size);
2314 }
2315 else {
2316 p = NULL;
2317 }
2318 if (p == NULL) {
2319 res = -1;
2320 goto done;
2321 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002322
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002323 /* Copy the tables into the new memory at the first call
2324 to PyImport_ExtendInittab(). */
2325 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002327 }
2328 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2329 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002330
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002331done:
2332 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2333 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002334}
2335
2336/* Shorthand to add a single entry given a name and a function */
2337
2338int
Brett Cannona826f322009-04-02 03:41:46 +00002339PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002344
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002345 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002349}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002350
2351#ifdef __cplusplus
2352}
2353#endif