blob: 5f5d135c7a2ed29c621796b9add5ffff82d1ac3c [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Module definition and import implementation */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00006#undef Yield /* undefine macro conflicting with winbase.h */
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08007#include "internal/hash.h"
8#include "internal/import.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06009#include "internal/pystate.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020013#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000014#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000015#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020016#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000022extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Barry Warsaw28a691b2010-04-17 00:19:56 +000025#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000026
Victor Stinner95872862011-03-07 18:20:56 +010027/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000028static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000029
Guido van Rossum771c6c81997-10-31 18:37:24 +000030/* This table is defined in config.c: */
31extern struct _inittab _PyImport_Inittab[];
32
33struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Victor Stinner92a3c6f2017-12-06 18:12:59 +010034static struct _inittab *inittab_copy = NULL;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000035
Brett Cannon4caa61d2014-01-09 19:03:32 -050036/*[clinic input]
37module _imp
38[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030039/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040040
41#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050042
Guido van Rossum1ae940a1995-01-02 19:04:15 +000043/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
Victor Stinnerf7e5b562017-11-15 15:48:08 -080045_PyInitError
Victor Stinner672b6ba2017-12-06 17:25:50 +010046_PyImport_Init(PyInterpreterState *interp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000047{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020048 interp->builtins_copy = PyDict_Copy(interp->builtins);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080049 if (interp->builtins_copy == NULL) {
50 return _Py_INIT_ERR("Can't backup builtins dict");
51 }
52 return _Py_INIT_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053}
54
Victor Stinnerf7e5b562017-11-15 15:48:08 -080055_PyInitError
Just van Rossum52e14d62002-12-30 22:08:05 +000056_PyImportHooks_Init(void)
57{
Brett Cannonfd074152012-04-14 14:10:13 -040058 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000060
Brett Cannonfd074152012-04-14 14:10:13 -040061 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 v = PyList_New(0);
63 if (v == NULL)
64 goto error;
65 err = PySys_SetObject("meta_path", v);
66 Py_DECREF(v);
67 if (err)
68 goto error;
69 v = PyDict_New();
70 if (v == NULL)
71 goto error;
72 err = PySys_SetObject("path_importer_cache", v);
73 Py_DECREF(v);
74 if (err)
75 goto error;
76 path_hooks = PyList_New(0);
77 if (path_hooks == NULL)
78 goto error;
79 err = PySys_SetObject("path_hooks", path_hooks);
80 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 }
Brett Cannonfd074152012-04-14 14:10:13 -040083 Py_DECREF(path_hooks);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084 return _Py_INIT_OK();
85
86 error:
87 PyErr_Print();
88 return _Py_INIT_ERR("initializing sys.meta_path, sys.path_hooks, "
89 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040090}
91
Victor Stinnerf7e5b562017-11-15 15:48:08 -080092_PyInitError
Brett Cannonfd074152012-04-14 14:10:13 -040093_PyImportZip_Init(void)
94{
95 PyObject *path_hooks, *zimpimport;
96 int err = 0;
97
98 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020099 if (path_hooks == NULL) {
100 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400101 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200102 }
Brett Cannonfd074152012-04-14 14:10:13 -0400103
104 if (Py_VerboseFlag)
105 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 zimpimport = PyImport_ImportModule("zipimport");
108 if (zimpimport == NULL) {
109 PyErr_Clear(); /* No zip import module -- okay */
110 if (Py_VerboseFlag)
111 PySys_WriteStderr("# can't import zipimport\n");
112 }
113 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200114 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200115 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
116 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 Py_DECREF(zimpimport);
118 if (zipimporter == NULL) {
119 PyErr_Clear(); /* No zipimporter object -- okay */
120 if (Py_VerboseFlag)
121 PySys_WriteStderr(
122 "# can't import zipimport.zipimporter\n");
123 }
124 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400125 /* sys.path_hooks.insert(0, zipimporter) */
126 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400128 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 if (Py_VerboseFlag)
132 PySys_WriteStderr(
133 "# installed zipimport hook\n");
134 }
135 }
Brett Cannonfd074152012-04-14 14:10:13 -0400136
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800137 return _Py_INIT_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400138
139 error:
140 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800141 return _Py_INIT_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000142}
143
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000144/* Locking primitives to prevent parallel imports of the same module
145 in different threads to return with a partially loaded module.
146 These calls are serialized by the global interpreter lock. */
147
Guido van Rossum49b56061998-10-01 20:42:43 +0000148#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000149
Guido van Rossum65d5b571998-12-21 19:32:43 +0000150static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200151static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000152static int import_lock_level = 0;
153
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000154void
155_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200157 unsigned long me = PyThread_get_thread_ident();
158 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 return; /* Too bad */
160 if (import_lock == NULL) {
161 import_lock = PyThread_allocate_lock();
162 if (import_lock == NULL)
163 return; /* Nothing much we can do. */
164 }
165 if (import_lock_thread == me) {
166 import_lock_level++;
167 return;
168 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200169 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
170 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 {
172 PyThreadState *tstate = PyEval_SaveThread();
173 PyThread_acquire_lock(import_lock, 1);
174 PyEval_RestoreThread(tstate);
175 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100176 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 import_lock_thread = me;
178 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000179}
180
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000181int
182_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000183{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200184 unsigned long me = PyThread_get_thread_ident();
185 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 return 0; /* Too bad */
187 if (import_lock_thread != me)
188 return -1;
189 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100190 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200192 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyThread_release_lock(import_lock);
194 }
195 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000196}
197
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200198/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000199 created child processes do not share locks with the parent.
200 We now acquire the import lock around fork() calls but on some platforms
201 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000202
203void
204_PyImport_ReInitLock(void)
205{
Christian Heimes418fd742015-04-19 21:08:42 +0200206 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200208 if (import_lock == NULL) {
209 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
210 }
211 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000212 if (import_lock_level > 1) {
213 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200214 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500215 /* The following could fail if the lock is already held, but forking as
216 a side-effect of an import is a) rare, b) nuts, and c) difficult to
217 do thanks to the lock only being held when doing individual module
218 locks per import. */
219 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000220 import_lock_thread = me;
221 import_lock_level--;
222 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200223 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000224 import_lock_level = 0;
225 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000226}
227
Brett Cannon4caa61d2014-01-09 19:03:32 -0500228/*[clinic input]
229_imp.lock_held
230
231Return True if the import lock is currently held, else False.
232
233On platforms without threads, return False.
234[clinic start generated code]*/
235
Brett Cannon4caa61d2014-01-09 19:03:32 -0500236static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300237_imp_lock_held_impl(PyObject *module)
238/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000239{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200240 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000241}
242
Brett Cannon4caa61d2014-01-09 19:03:32 -0500243/*[clinic input]
244_imp.acquire_lock
245
246Acquires the interpreter's import lock for the current thread.
247
248This lock should be used by import hooks to ensure thread-safety when importing
249modules. On platforms without threads, this function does nothing.
250[clinic start generated code]*/
251
Brett Cannon4caa61d2014-01-09 19:03:32 -0500252static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300253_imp_acquire_lock_impl(PyObject *module)
254/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200257 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000258}
259
Brett Cannon4caa61d2014-01-09 19:03:32 -0500260/*[clinic input]
261_imp.release_lock
262
263Release the interpreter's import lock.
264
265On platforms without threads, this function does nothing.
266[clinic start generated code]*/
267
Brett Cannon4caa61d2014-01-09 19:03:32 -0500268static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300269_imp_release_lock_impl(PyObject *module)
270/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (_PyImport_ReleaseLock() < 0) {
273 PyErr_SetString(PyExc_RuntimeError,
274 "not holding the import lock");
275 return NULL;
276 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200277 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000278}
279
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100280void
281_PyImport_Fini(void)
282{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200283 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100284 if (import_lock != NULL) {
285 PyThread_free_lock(import_lock);
286 import_lock = NULL;
287 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100288}
289
Victor Stinner92a3c6f2017-12-06 18:12:59 +0100290void
291_PyImport_Fini2(void)
292{
293 /* Use the same memory allocator than PyImport_ExtendInittab(). */
294 PyMemAllocatorEx old_alloc;
295 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
296
297 /* Free memory allocated by PyImport_ExtendInittab() */
298 PyMem_RawFree(inittab_copy);
299
300 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
301}
302
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303/* Helper for sys */
304
305PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000306PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307{
Eric Snow93c92f72017-09-13 23:46:04 -0700308 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snow3f9eee62017-09-15 16:35:20 -0600309 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700310 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600311 }
Eric Snow93c92f72017-09-13 23:46:04 -0700312 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313}
314
Eric Snowd393c1b2017-09-14 12:18:12 -0600315/* In some corner cases it is important to be sure that the import
316 machinery has been initialized (or not cleaned up yet). For
317 example, see issue #4236 and PyModule_Create2(). */
318
319int
320_PyImport_IsInitialized(PyInterpreterState *interp)
321{
322 if (interp->modules == NULL)
323 return 0;
324 return 1;
325}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000326
Eric Snow3f9eee62017-09-15 16:35:20 -0600327PyObject *
328_PyImport_GetModuleId(struct _Py_Identifier *nameid)
329{
330 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
331 if (name == NULL) {
332 return NULL;
333 }
334 return PyImport_GetModule(name);
335}
336
337int
338_PyImport_SetModule(PyObject *name, PyObject *m)
339{
340 PyObject *modules = PyImport_GetModuleDict();
341 return PyObject_SetItem(modules, name, m);
342}
343
344int
345_PyImport_SetModuleString(const char *name, PyObject *m)
346{
347 PyObject *modules = PyImport_GetModuleDict();
348 return PyMapping_SetItemString(modules, name, m);
349}
350
351PyObject *
352PyImport_GetModule(PyObject *name)
353{
354 PyObject *m;
355 PyObject *modules = PyImport_GetModuleDict();
356 if (modules == NULL) {
357 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
358 return NULL;
359 }
360 Py_INCREF(modules);
361 if (PyDict_CheckExact(modules)) {
362 m = PyDict_GetItemWithError(modules, name); /* borrowed */
363 Py_XINCREF(m);
364 }
365 else {
366 m = PyObject_GetItem(modules, name);
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700367 if (m == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600368 PyErr_Clear();
369 }
370 }
371 Py_DECREF(modules);
372 return m;
373}
374
375
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000376/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200377static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 "path", "argv", "ps1", "ps2",
379 "last_type", "last_value", "last_traceback",
380 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200381 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 /* misc stuff */
383 "flags", "float_info",
384 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000385};
386
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200387static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 "stdin", "__stdin__",
389 "stdout", "__stdout__",
390 "stderr", "__stderr__",
391 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000392};
393
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000394/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000397PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000398{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200399 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyObject *key, *value, *dict;
401 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snowd393c1b2017-09-14 12:18:12 -0600402 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200403 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200404 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 if (modules == NULL)
407 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 /* Delete some special variables first. These are common
410 places where user values hide and people complain when their
411 destructors fail. Since the modules containing them are
412 deleted *last* of all, they would come too late in the normal
413 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000414
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200415 /* XXX Perhaps these precautions are obsolete. Who knows? */
416
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200417 if (Py_VerboseFlag)
418 PySys_WriteStderr("# clear builtins._\n");
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700419 if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
420 PyErr_Clear();
421 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200422
423 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200425 PySys_WriteStderr("# clear sys.%s\n", *p);
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700426 if (PyDict_SetItemString(interp->sysdict, *p, Py_None) < 0) {
427 PyErr_Clear();
428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200430 for (p = sys_files; *p != NULL; p+=2) {
431 if (Py_VerboseFlag)
432 PySys_WriteStderr("# restore sys.%s\n", *p);
433 value = PyDict_GetItemString(interp->sysdict, *(p+1));
434 if (value == NULL)
435 value = Py_None;
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700436 if (PyDict_SetItemString(interp->sysdict, *p, value) < 0) {
437 PyErr_Clear();
438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000440
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200441 /* We prepare a list which will receive (name, weakref) tuples of
442 modules when they are removed from sys.modules. The name is used
443 for diagnosis messages (in verbose mode), while the weakref helps
444 detect those modules which have been held alive. */
445 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200446 if (weaklist == NULL)
447 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200448
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200449#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200451 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700452 if (wr) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200453 PyObject *tup = PyTuple_Pack(2, name, wr); \
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700454 if (!tup || PyList_Append(weaklist, tup) < 0) { \
455 PyErr_Clear(); \
456 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457 Py_XDECREF(tup); \
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700458 Py_DECREF(wr); \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200459 } \
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700460 else { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200461 PyErr_Clear(); \
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700462 } \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600464#define CLEAR_MODULE(name, mod) \
465 if (PyModule_Check(mod)) { \
466 if (Py_VerboseFlag && PyUnicode_Check(name)) \
467 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
468 STORE_MODULE_WEAKREF(name, mod); \
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700469 if (PyObject_SetItem(modules, name, Py_None) < 0) { \
470 PyErr_Clear(); \
471 } \
Eric Snow3f9eee62017-09-15 16:35:20 -0600472 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000473
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200474 /* Remove all modules from sys.modules, hoping that garbage collection
475 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600476 if (PyDict_CheckExact(modules)) {
477 pos = 0;
478 while (PyDict_Next(modules, &pos, &key, &value)) {
479 CLEAR_MODULE(key, value);
480 }
481 }
482 else {
483 PyObject *iterator = PyObject_GetIter(modules);
484 if (iterator == NULL) {
485 PyErr_Clear();
486 }
487 else {
488 while ((key = PyIter_Next(iterator))) {
489 value = PyObject_GetItem(modules, key);
490 if (value == NULL) {
491 PyErr_Clear();
492 continue;
493 }
494 CLEAR_MODULE(key, value);
495 Py_DECREF(value);
496 Py_DECREF(key);
497 }
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700498 if (PyErr_Occurred()) {
499 PyErr_Clear();
500 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600501 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
503 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000504
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200505 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600506 if (PyDict_CheckExact(modules)) {
507 PyDict_Clear(modules);
508 }
509 else {
510 _Py_IDENTIFIER(clear);
511 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL)
512 PyErr_Clear();
513 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200514 /* Restore the original builtins dict, to ensure that any
515 user data gets cleared. */
516 dict = PyDict_Copy(interp->builtins);
517 if (dict == NULL)
518 PyErr_Clear();
519 PyDict_Clear(interp->builtins);
520 if (PyDict_Update(interp->builtins, interp->builtins_copy))
521 PyErr_Clear();
522 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200523 /* Clear module dict copies stored in the interpreter state */
524 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200525 /* Collect references */
526 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200527 /* Dump GC stats before it's too late, since it uses the warnings
528 machinery. */
529 _PyGC_DumpShutdownStats();
530
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200531 /* Now, if there are any modules left alive, clear their globals to
532 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200533 up here, since they are kept alive in the interpreter state.
534
535 The special treatment of "builtins" here is because even
536 when it's not referenced as a module, its dictionary is
537 referenced by almost every module's __builtins__. Since
538 deleting a module clears its dictionary (even if there are
539 references left to it), we need to delete the "builtins"
540 module last. Likewise, we don't delete sys until the very
541 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200542 if (weaklist != NULL) {
543 Py_ssize_t i, n;
544 n = PyList_GET_SIZE(weaklist);
545 for (i = 0; i < n; i++) {
546 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200547 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200548 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
549 if (mod == Py_None)
550 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200551 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200552 dict = PyModule_GetDict(mod);
553 if (dict == interp->builtins || dict == interp->sysdict)
554 continue;
555 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200556 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200557 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200558 _PyModule_Clear(mod);
559 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200560 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200561 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000563
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200564 /* Next, delete sys and builtins (in that order) */
565 if (Py_VerboseFlag)
566 PySys_FormatStderr("# cleanup[3] wiping sys\n");
567 _PyModule_ClearDict(interp->sysdict);
568 if (Py_VerboseFlag)
569 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
570 _PyModule_ClearDict(interp->builtins);
571
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200572 /* Clear and delete the modules directory. Actual modules will
573 still be there only if imported during the execution of some
574 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700575 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200577
578 /* Once more */
579 _PyGC_CollectNoFail();
580
Miss Islington (bot)291c9d42018-04-25 11:32:52 -0700581#undef CLEAR_MODULE
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200582#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000583}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000584
585
Barry Warsaw28a691b2010-04-17 00:19:56 +0000586/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587
588long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000589PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000590{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200591 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400592 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600593 PyObject *external, *pyc_magic;
594
595 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
596 if (external == NULL)
597 return -1;
598 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
599 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400600 if (pyc_magic == NULL)
601 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200602 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700603 Py_DECREF(pyc_magic);
604 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000605}
606
607
Brett Cannon3adc7b72012-07-09 14:22:12 -0400608extern const char * _PySys_ImplCacheTag;
609
Barry Warsaw28a691b2010-04-17 00:19:56 +0000610const char *
611PyImport_GetMagicTag(void)
612{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400613 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000614}
615
Brett Cannon98979b82012-07-02 15:13:11 -0400616
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617/* Magic for extension modules (built-in as well as dynamically
618 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200619 once, we keep a static dictionary 'extensions' keyed by the tuple
620 (module name, module name) (for built-in modules) or by
621 (filename, module name) (for dynamically loaded modules), containing these
622 modules. A copy of the module's dictionary is stored by calling
623 _PyImport_FixupExtensionObject() immediately after the module initialization
624 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100625 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000626
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000627 Modules which do support multiple initialization set their m_size
628 field to a non-negative number (indicating the size of the
629 module-specific state). They are still recorded in the extensions
630 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000631*/
632
633int
Victor Stinner95872862011-03-07 18:20:56 +0100634_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600635 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000636{
Eric Snowd393c1b2017-09-14 12:18:12 -0600637 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500639 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (extensions == NULL) {
641 extensions = PyDict_New();
642 if (extensions == NULL)
643 return -1;
644 }
645 if (mod == NULL || !PyModule_Check(mod)) {
646 PyErr_BadInternalCall();
647 return -1;
648 }
649 def = PyModule_GetDef(mod);
650 if (!def) {
651 PyErr_BadInternalCall();
652 return -1;
653 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600654 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return -1;
656 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600657 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 return -1;
659 }
660 if (def->m_size == -1) {
661 if (def->m_base.m_copy) {
662 /* Somebody already imported the module,
663 likely under a different name.
664 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200665 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
667 dict = PyModule_GetDict(mod);
668 if (dict == NULL)
669 return -1;
670 def->m_base.m_copy = PyDict_Copy(dict);
671 if (def->m_base.m_copy == NULL)
672 return -1;
673 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500674 key = PyTuple_Pack(2, filename, name);
675 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200676 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500677 res = PyDict_SetItem(extensions, key, (PyObject *)def);
678 Py_DECREF(key);
679 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200680 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000682}
683
Victor Stinner49d3f252010-10-17 01:24:53 +0000684int
Eric Snowd393c1b2017-09-14 12:18:12 -0600685_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000686{
687 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100688 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100689 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100690 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000691 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600692 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100693 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000694 return res;
695}
696
Guido van Rossum25ce5661997-08-02 03:10:38 +0000697PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100698_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000699{
Eric Snowd393c1b2017-09-14 12:18:12 -0600700 PyObject *modules = PyImport_GetModuleDict();
701 return _PyImport_FindExtensionObjectEx(name, filename, modules);
702}
703
704PyObject *
705_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
706 PyObject *modules)
707{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500708 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyModuleDef* def;
710 if (extensions == NULL)
711 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500712 key = PyTuple_Pack(2, filename, name);
713 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200714 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500715 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
716 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (def == NULL)
718 return NULL;
719 if (def->m_size == -1) {
720 /* Module does not support repeated initialization */
721 if (def->m_base.m_copy == NULL)
722 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600723 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (mod == NULL)
725 return NULL;
726 mdict = PyModule_GetDict(mod);
727 if (mdict == NULL)
728 return NULL;
729 if (PyDict_Update(mdict, def->m_base.m_copy))
730 return NULL;
731 }
732 else {
733 if (def->m_base.m_init == NULL)
734 return NULL;
735 mod = def->m_base.m_init();
736 if (mod == NULL)
737 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600738 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200739 Py_DECREF(mod);
740 return NULL;
741 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 Py_DECREF(mod);
743 }
744 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600745 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 Py_DECREF(mod);
747 return NULL;
748 }
749 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100750 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 name, filename);
752 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000753
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000754}
755
Victor Stinner49d3f252010-10-17 01:24:53 +0000756PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600757_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000758{
Victor Stinner95872862011-03-07 18:20:56 +0100759 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100760 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100761 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000762 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600763 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100764 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000765 return res;
766}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767
768/* Get the module object corresponding to a module name.
769 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000770 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000771 Because the former action is most common, THIS DOES NOT RETURN A
772 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000773
Guido van Rossum79f25d91997-04-29 20:08:16 +0000774PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000775PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600778 return _PyImport_AddModuleObject(name, modules);
779}
780
781PyObject *
782_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
783{
Eric Snow86b7afd2017-09-04 17:54:09 -0600784 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600785 if (PyDict_CheckExact(modules)) {
786 m = PyDict_GetItemWithError(modules, name);
787 }
788 else {
789 m = PyObject_GetItem(modules, name);
790 // For backward-comaptibility we copy the behavior
791 // of PyDict_GetItemWithError().
792 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
793 PyErr_Clear();
794 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200795 }
796 if (PyErr_Occurred()) {
797 return NULL;
798 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600799 if (m != NULL && PyModule_Check(m)) {
800 return m;
801 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000802 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (m == NULL)
804 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600805 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 Py_DECREF(m);
807 return NULL;
808 }
809 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000812}
813
Victor Stinner27ee0892011-03-04 12:57:09 +0000814PyObject *
815PyImport_AddModule(const char *name)
816{
817 PyObject *nameobj, *module;
818 nameobj = PyUnicode_FromString(name);
819 if (nameobj == NULL)
820 return NULL;
821 module = PyImport_AddModuleObject(nameobj);
822 Py_DECREF(nameobj);
823 return module;
824}
825
826
Tim Peters1cd70172004-08-02 03:52:12 +0000827/* Remove name from sys.modules, if it's there. */
828static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000829remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyObject *modules = PyImport_GetModuleDict();
Eric Snow3f9eee62017-09-15 16:35:20 -0600832 if (PyMapping_DelItem(modules, name) < 0) {
833 if (!PyMapping_HasKey(modules, name)) {
834 return;
835 }
Miss Islington (bot)7beb8c52018-11-05 06:52:58 -0800836 Py_FatalError("import: deleting existing key in "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600838 }
Tim Peters1cd70172004-08-02 03:52:12 +0000839}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000840
Christian Heimes3b06e532008-01-07 20:12:44 +0000841
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000842/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000843 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
844 * removed from sys.modules, to avoid leaving damaged module objects
845 * in sys.modules. The caller may wish to restore the original
846 * module object (if any) in this case; PyImport_ReloadModule is an
847 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000848 *
849 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
850 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000851 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000852PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300853PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return PyImport_ExecCodeModuleWithPathnames(
856 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000857}
858
859PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300860PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 return PyImport_ExecCodeModuleWithPathnames(
863 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000864}
865
866PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300867PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
868 const char *pathname,
869 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000870{
Victor Stinner27ee0892011-03-04 12:57:09 +0000871 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600872 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000873
874 nameobj = PyUnicode_FromString(name);
875 if (nameobj == NULL)
876 return NULL;
877
Victor Stinner27ee0892011-03-04 12:57:09 +0000878 if (cpathname != NULL) {
879 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
880 if (cpathobj == NULL)
881 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400882 }
883 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000884 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400885
886 if (pathname != NULL) {
887 pathobj = PyUnicode_DecodeFSDefault(pathname);
888 if (pathobj == NULL)
889 goto error;
890 }
891 else if (cpathobj != NULL) {
892 PyInterpreterState *interp = PyThreadState_GET()->interp;
893 _Py_IDENTIFIER(_get_sourcefile);
894
895 if (interp == NULL) {
896 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
897 "no interpreter!");
898 }
899
Eric Snow32439d62015-05-02 19:15:18 -0600900 external= PyObject_GetAttrString(interp->importlib,
901 "_bootstrap_external");
902 if (external != NULL) {
903 pathobj = _PyObject_CallMethodIdObjArgs(external,
904 &PyId__get_sourcefile, cpathobj,
905 NULL);
906 Py_DECREF(external);
907 }
Brett Cannona6473f92012-07-13 13:57:03 -0400908 if (pathobj == NULL)
909 PyErr_Clear();
910 }
911 else
912 pathobj = NULL;
913
Victor Stinner27ee0892011-03-04 12:57:09 +0000914 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
915error:
916 Py_DECREF(nameobj);
917 Py_XDECREF(pathobj);
918 Py_XDECREF(cpathobj);
919 return m;
920}
921
Brett Cannon18fc4e72014-04-04 10:01:46 -0400922static PyObject *
923module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000924{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400925 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000926
Victor Stinner27ee0892011-03-04 12:57:09 +0000927 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (m == NULL)
929 return NULL;
930 /* If the module is being reloaded, we get the old module back
931 and re-use its dict to exec the new code. */
932 d = PyModule_GetDict(m);
933 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
934 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400935 PyEval_GetBuiltins()) != 0) {
936 remove_module(name);
937 return NULL;
938 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400940
Eric Snow08197a42014-05-12 17:54:55 -0600941 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400942}
943
944static PyObject *
945exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
946{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400947 PyObject *v, *m;
948
949 v = PyEval_EvalCode(code_object, module_dict, module_dict);
950 if (v == NULL) {
951 remove_module(name);
952 return NULL;
953 }
954 Py_DECREF(v);
955
Eric Snow3f9eee62017-09-15 16:35:20 -0600956 m = PyImport_GetModule(name);
957 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400958 PyErr_Format(PyExc_ImportError,
959 "Loaded module %R not found in sys.modules",
960 name);
961 return NULL;
962 }
963
Brett Cannon18fc4e72014-04-04 10:01:46 -0400964 return m;
965}
966
967PyObject*
968PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
969 PyObject *cpathname)
970{
Eric Snow32439d62015-05-02 19:15:18 -0600971 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600972 PyInterpreterState *interp = PyThreadState_GET()->interp;
973 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400974
975 d = module_dict_for_exec(name);
976 if (d == NULL) {
977 return NULL;
978 }
979
Eric Snow08197a42014-05-12 17:54:55 -0600980 if (pathname == NULL) {
981 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 }
Eric Snow32439d62015-05-02 19:15:18 -0600983 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
984 if (external == NULL)
985 return NULL;
986 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600987 &PyId__fix_up_module,
988 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600989 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600990 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600991 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600992 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 }
Eric Snow08197a42014-05-12 17:54:55 -0600994 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000995}
996
997
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000998static void
999update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 PyObject *constants, *tmp;
1002 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (PyUnicode_Compare(co->co_filename, oldname))
1005 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001006
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001007 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001008 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 constants = co->co_consts;
1011 n = PyTuple_GET_SIZE(constants);
1012 for (i = 0; i < n; i++) {
1013 tmp = PyTuple_GET_ITEM(constants, i);
1014 if (PyCode_Check(tmp))
1015 update_code_filenames((PyCodeObject *)tmp,
1016 oldname, newname);
1017 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001018}
1019
Victor Stinner2f42ae52011-03-20 00:41:24 +01001020static void
1021update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001022{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001023 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001024
Victor Stinner2f42ae52011-03-20 00:41:24 +01001025 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1026 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 oldname = co->co_filename;
1029 Py_INCREF(oldname);
1030 update_code_filenames(co, oldname, newname);
1031 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001032}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001033
Brett Cannon4caa61d2014-01-09 19:03:32 -05001034/*[clinic input]
1035_imp._fix_co_filename
1036
1037 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1038 Code object to change.
1039
1040 path: unicode
1041 File path to use.
1042 /
1043
1044Changes code.co_filename to specify the passed-in file path.
1045[clinic start generated code]*/
1046
Brett Cannon4caa61d2014-01-09 19:03:32 -05001047static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001048_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001049 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001050/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001051
Brett Cannon4caa61d2014-01-09 19:03:32 -05001052{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001053 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001054
1055 Py_RETURN_NONE;
1056}
1057
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001058
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001059/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001060static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001061
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001062
1063/* Helper to test for built-in module */
1064
1065static int
Victor Stinner95872862011-03-07 18:20:56 +01001066is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001067{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001068 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001070 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (PyImport_Inittab[i].initfunc == NULL)
1072 return -1;
1073 else
1074 return 1;
1075 }
1076 }
1077 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001078}
1079
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001080
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001081/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001082 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001083 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001084 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001085 this tells our caller that the path based finder could not find
1086 a finder for this path item. Cache the result in
1087 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001088 Returns a borrowed reference. */
1089
1090static PyObject *
1091get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *importer;
1095 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 /* These conditions are the caller's responsibility: */
1098 assert(PyList_Check(path_hooks));
1099 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 nhooks = PyList_Size(path_hooks);
1102 if (nhooks < 0)
1103 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 importer = PyDict_GetItem(path_importer_cache, p);
1106 if (importer != NULL)
1107 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 /* set path_importer_cache[p] to None to avoid recursion */
1110 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1111 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 for (j = 0; j < nhooks; j++) {
1114 PyObject *hook = PyList_GetItem(path_hooks, j);
1115 if (hook == NULL)
1116 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001117 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (importer != NULL)
1119 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1122 return NULL;
1123 }
1124 PyErr_Clear();
1125 }
1126 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001127 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
1129 if (importer != NULL) {
1130 int err = PyDict_SetItem(path_importer_cache, p, importer);
1131 Py_DECREF(importer);
1132 if (err != 0)
1133 return NULL;
1134 }
1135 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001136}
1137
Christian Heimes9cd17752007-11-18 19:35:23 +00001138PyAPI_FUNC(PyObject *)
1139PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001141
Victor Stinner1e53bba2013-07-16 22:26:05 +02001142 path_importer_cache = PySys_GetObject("path_importer_cache");
1143 path_hooks = PySys_GetObject("path_hooks");
1144 if (path_importer_cache != NULL && path_hooks != NULL) {
1145 importer = get_path_importer(path_importer_cache,
1146 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 }
1148 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1149 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001150}
1151
Nick Coghland5cacbb2015-05-23 22:24:10 +10001152/*[clinic input]
1153_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001154
Nick Coghland5cacbb2015-05-23 22:24:10 +10001155 spec: object
1156 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001157
Nick Coghland5cacbb2015-05-23 22:24:10 +10001158Create an extension module.
1159[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001160
Nick Coghland5cacbb2015-05-23 22:24:10 +10001161static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001162_imp_create_builtin(PyObject *module, PyObject *spec)
1163/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001166 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001167 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001168 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001169
Nick Coghland5cacbb2015-05-23 22:24:10 +10001170 name = PyObject_GetAttrString(spec, "name");
1171 if (name == NULL) {
1172 return NULL;
1173 }
1174
Victor Stinner5eb4f592013-11-14 22:38:52 +01001175 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001176 if (mod || PyErr_Occurred()) {
1177 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001178 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001179 return mod;
1180 }
1181
1182 namestr = PyUnicode_AsUTF8(name);
1183 if (namestr == NULL) {
1184 Py_DECREF(name);
1185 return NULL;
1186 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001187
Eric Snowd393c1b2017-09-14 12:18:12 -06001188 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001190 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001191 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001193 /* Cannot re-init internal module ("sys" or "builtins") */
1194 mod = PyImport_AddModule(namestr);
1195 Py_DECREF(name);
1196 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001199 if (mod == NULL) {
1200 Py_DECREF(name);
1201 return NULL;
1202 }
1203 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1204 Py_DECREF(name);
1205 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1206 } else {
1207 /* Remember pointer to module init function. */
1208 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001209 if (def == NULL) {
1210 Py_DECREF(name);
1211 return NULL;
1212 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001213 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001214 if (modules == NULL) {
1215 modules = PyImport_GetModuleDict();
1216 }
1217 if (_PyImport_FixupExtensionObject(mod, name, name,
1218 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001219 Py_DECREF(name);
1220 return NULL;
1221 }
1222 Py_DECREF(name);
1223 return mod;
1224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 }
1226 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001227 Py_DECREF(name);
1228 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001229}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001230
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001231
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001232/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001233
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001234static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001235find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001236{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001237 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001238
Victor Stinner53dc7352011-03-20 01:50:21 +01001239 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 for (p = PyImport_FrozenModules; ; p++) {
1243 if (p->name == NULL)
1244 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001245 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 break;
1247 }
1248 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001249}
1250
Guido van Rossum79f25d91997-04-29 20:08:16 +00001251static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001252get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001253{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001254 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (p == NULL) {
1258 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001259 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 name);
1261 return NULL;
1262 }
1263 if (p->code == NULL) {
1264 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001265 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 name);
1267 return NULL;
1268 }
1269 size = p->size;
1270 if (size < 0)
1271 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001272 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001273}
1274
Brett Cannon8d110132009-03-15 02:20:16 +00001275static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001276is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001277{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001278 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (p == NULL) {
1282 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001283 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 name);
1285 return NULL;
1286 }
Brett Cannon8d110132009-03-15 02:20:16 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (size < 0)
1291 Py_RETURN_TRUE;
1292 else
1293 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001294}
1295
1296
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001297/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001298 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001299 an exception set if the initialization failed.
1300 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001301
1302int
Victor Stinner53dc7352011-03-20 01:50:21 +01001303PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001304{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001305 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001306 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 int ispackage;
1308 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001309
Victor Stinner53dc7352011-03-20 01:50:21 +01001310 p = find_frozen(name);
1311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (p == NULL)
1313 return 0;
1314 if (p->code == NULL) {
1315 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001316 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 name);
1318 return -1;
1319 }
1320 size = p->size;
1321 ispackage = (size < 0);
1322 if (ispackage)
1323 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001324 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (co == NULL)
1326 return -1;
1327 if (!PyCode_Check(co)) {
1328 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001329 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 name);
1331 goto err_return;
1332 }
1333 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001334 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001335 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001337 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 if (m == NULL)
1339 goto err_return;
1340 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001341 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 goto err_return;
1344 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 err = PyDict_SetItemString(d, "__path__", l);
1346 Py_DECREF(l);
1347 if (err != 0)
1348 goto err_return;
1349 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001350 d = module_dict_for_exec(name);
1351 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001352 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001353 }
1354 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 if (m == NULL)
1356 goto err_return;
1357 Py_DECREF(co);
1358 Py_DECREF(m);
1359 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001360err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 Py_DECREF(co);
1362 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001363}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001364
Victor Stinner53dc7352011-03-20 01:50:21 +01001365int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001366PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001367{
1368 PyObject *nameobj;
1369 int ret;
1370 nameobj = PyUnicode_InternFromString(name);
1371 if (nameobj == NULL)
1372 return -1;
1373 ret = PyImport_ImportFrozenModuleObject(nameobj);
1374 Py_DECREF(nameobj);
1375 return ret;
1376}
1377
Guido van Rossum74e6a111994-08-29 12:54:38 +00001378
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001379/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001380 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001381
Guido van Rossum79f25d91997-04-29 20:08:16 +00001382PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001383PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 PyObject *pname;
1386 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 pname = PyUnicode_FromString(name);
1389 if (pname == NULL)
1390 return NULL;
1391 result = PyImport_Import(pname);
1392 Py_DECREF(pname);
1393 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001394}
1395
Christian Heimes072c0f12008-01-03 23:01:04 +00001396/* Import a module without blocking
1397 *
1398 * At first it tries to fetch the module from sys.modules. If the module was
1399 * never loaded before it loads it with PyImport_ImportModule() unless another
1400 * thread holds the import lock. In the latter case the function raises an
1401 * ImportError instead of blocking.
1402 *
1403 * Returns the module object with incremented ref count.
1404 */
1405PyObject *
1406PyImport_ImportModuleNoBlock(const char *name)
1407{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001408 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001409}
1410
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001411
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001412/* Remove importlib frames from the traceback,
1413 * except in Verbose mode. */
1414static void
1415remove_importlib_frames(void)
1416{
1417 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001418 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001419 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001420 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001421 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001422 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001423 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001424
1425 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001426 from the traceback. We always trim chunks
1427 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001428
1429 PyErr_Fetch(&exception, &value, &base_tb);
1430 if (!exception || Py_VerboseFlag)
1431 goto done;
1432 if (PyType_IsSubtype((PyTypeObject *) exception,
1433 (PyTypeObject *) PyExc_ImportError))
1434 always_trim = 1;
1435
1436 prev_link = &base_tb;
1437 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001438 while (tb != NULL) {
1439 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1440 PyObject *next = (PyObject *) traceback->tb_next;
1441 PyFrameObject *frame = traceback->tb_frame;
1442 PyCodeObject *code = frame->f_code;
1443 int now_in_importlib;
1444
1445 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001446 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1447 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001448 if (now_in_importlib && !in_importlib) {
1449 /* This is the link to this chunk of importlib tracebacks */
1450 outer_link = prev_link;
1451 }
1452 in_importlib = now_in_importlib;
1453
1454 if (in_importlib &&
1455 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001456 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001457 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001458 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001459 prev_link = outer_link;
1460 }
1461 else {
1462 prev_link = (PyObject **) &traceback->tb_next;
1463 }
1464 tb = next;
1465 }
1466done:
1467 PyErr_Restore(exception, value, base_tb);
1468}
1469
1470
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001471static PyObject *
1472resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001473{
Eric Snowb523f842013-11-22 09:05:39 -07001474 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001475 _Py_IDENTIFIER(__package__);
1476 _Py_IDENTIFIER(__path__);
1477 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001478 _Py_IDENTIFIER(parent);
1479 PyObject *abs_name;
1480 PyObject *package = NULL;
1481 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001482 Py_ssize_t last_dot;
1483 PyObject *base;
1484 int level_up;
1485
1486 if (globals == NULL) {
1487 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1488 goto error;
1489 }
1490 if (!PyDict_Check(globals)) {
1491 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1492 goto error;
1493 }
1494 package = _PyDict_GetItemId(globals, &PyId___package__);
1495 if (package == Py_None) {
1496 package = NULL;
1497 }
1498 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1499
1500 if (package != NULL) {
1501 Py_INCREF(package);
1502 if (!PyUnicode_Check(package)) {
1503 PyErr_SetString(PyExc_TypeError, "package must be a string");
1504 goto error;
1505 }
1506 else if (spec != NULL && spec != Py_None) {
1507 int equal;
1508 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1509 if (parent == NULL) {
1510 goto error;
1511 }
1512
1513 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1514 Py_DECREF(parent);
1515 if (equal < 0) {
1516 goto error;
1517 }
1518 else if (equal == 0) {
1519 if (PyErr_WarnEx(PyExc_ImportWarning,
1520 "__package__ != __spec__.parent", 1) < 0) {
1521 goto error;
1522 }
1523 }
1524 }
1525 }
1526 else if (spec != NULL && spec != Py_None) {
1527 package = _PyObject_GetAttrId(spec, &PyId_parent);
1528 if (package == NULL) {
1529 goto error;
1530 }
1531 else if (!PyUnicode_Check(package)) {
1532 PyErr_SetString(PyExc_TypeError,
1533 "__spec__.parent must be a string");
1534 goto error;
1535 }
1536 }
1537 else {
1538 if (PyErr_WarnEx(PyExc_ImportWarning,
1539 "can't resolve package from __spec__ or __package__, "
1540 "falling back on __name__ and __path__", 1) < 0) {
1541 goto error;
1542 }
1543
1544 package = _PyDict_GetItemId(globals, &PyId___name__);
1545 if (package == NULL) {
1546 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1547 goto error;
1548 }
1549
1550 Py_INCREF(package);
1551 if (!PyUnicode_Check(package)) {
1552 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1553 goto error;
1554 }
1555
1556 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1557 Py_ssize_t dot;
1558
1559 if (PyUnicode_READY(package) < 0) {
1560 goto error;
1561 }
1562
1563 dot = PyUnicode_FindChar(package, '.',
1564 0, PyUnicode_GET_LENGTH(package), -1);
1565 if (dot == -2) {
1566 goto error;
1567 }
1568
1569 if (dot >= 0) {
1570 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1571 if (substr == NULL) {
1572 goto error;
1573 }
1574 Py_SETREF(package, substr);
1575 }
1576 }
1577 }
1578
1579 last_dot = PyUnicode_GET_LENGTH(package);
1580 if (last_dot == 0) {
1581 PyErr_SetString(PyExc_ImportError,
1582 "attempted relative import with no known parent package");
1583 goto error;
1584 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001585
1586 for (level_up = 1; level_up < level; level_up += 1) {
1587 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1588 if (last_dot == -2) {
1589 goto error;
1590 }
1591 else if (last_dot == -1) {
1592 PyErr_SetString(PyExc_ValueError,
1593 "attempted relative import beyond top-level "
1594 "package");
1595 goto error;
1596 }
1597 }
1598
1599 base = PyUnicode_Substring(package, 0, last_dot);
1600 Py_DECREF(package);
1601 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1602 return base;
1603 }
1604
1605 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1606 Py_DECREF(base);
1607 return abs_name;
1608
1609 error:
1610 Py_XDECREF(package);
1611 return NULL;
1612}
1613
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001614static PyObject *
1615import_find_and_load(PyObject *abs_name)
1616{
1617 _Py_IDENTIFIER(_find_and_load);
1618 PyObject *mod = NULL;
1619 PyInterpreterState *interp = PyThreadState_GET()->interp;
1620 int import_time = interp->core_config.import_time;
1621 static int import_level;
1622 static _PyTime_t accumulated;
1623
1624 _PyTime_t t1 = 0, accumulated_copy = accumulated;
1625
1626 /* XOptions is initialized after first some imports.
1627 * So we can't have negative cache before completed initialization.
1628 * Anyway, importlib._find_and_load is much slower than
1629 * _PyDict_GetItemIdWithError().
1630 */
1631 if (import_time) {
1632 static int header = 1;
1633 if (header) {
1634 fputs("import time: self [us] | cumulative | imported package\n",
1635 stderr);
1636 header = 0;
1637 }
1638
1639 import_level++;
1640 t1 = _PyTime_GetPerfCounter();
1641 accumulated = 0;
1642 }
1643
1644 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1645 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1646
1647 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
1648 &PyId__find_and_load, abs_name,
1649 interp->import_func, NULL);
1650
1651 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1652 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1653 mod != NULL);
1654
1655 if (import_time) {
1656 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1657
1658 import_level--;
1659 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1660 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1661 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1662 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1663
1664 accumulated = accumulated_copy + cum;
1665 }
1666
1667 return mod;
1668}
1669
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001670PyObject *
1671PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1672 PyObject *locals, PyObject *fromlist,
1673 int level)
1674{
Brett Cannonfd074152012-04-14 14:10:13 -04001675 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001676 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001677 PyObject *final_mod = NULL;
1678 PyObject *mod = NULL;
1679 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001680 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001681 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001682
Brett Cannonfd074152012-04-14 14:10:13 -04001683 if (name == NULL) {
1684 PyErr_SetString(PyExc_ValueError, "Empty module name");
1685 goto error;
1686 }
1687
1688 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1689 for added performance. */
1690
1691 if (!PyUnicode_Check(name)) {
1692 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1693 goto error;
1694 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001695 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001696 goto error;
1697 }
1698 if (level < 0) {
1699 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1700 goto error;
1701 }
Brett Cannon849113a2016-01-22 15:25:50 -08001702
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001703 if (level > 0) {
1704 abs_name = resolve_name(name, globals, level);
1705 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001706 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001707 }
1708 else { /* level == 0 */
1709 if (PyUnicode_GET_LENGTH(name) == 0) {
1710 PyErr_SetString(PyExc_ValueError, "Empty module name");
1711 goto error;
1712 }
Brett Cannonfd074152012-04-14 14:10:13 -04001713 abs_name = name;
1714 Py_INCREF(abs_name);
1715 }
1716
Eric Snow3f9eee62017-09-15 16:35:20 -06001717 mod = PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001718 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001719 _Py_IDENTIFIER(__spec__);
1720 _Py_IDENTIFIER(_initializing);
1721 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001722 PyObject *value = NULL;
1723 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001724 int initializing = 0;
1725
Antoine Pitrou03989852012-08-28 00:24:52 +02001726 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001727 __spec__._initializing is true.
1728 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001729 stuffing the new module in sys.modules.
1730 */
Eric Snowb523f842013-11-22 09:05:39 -07001731 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1732 if (spec != NULL) {
1733 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1734 Py_DECREF(spec);
1735 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001736 if (value == NULL)
1737 PyErr_Clear();
1738 else {
1739 initializing = PyObject_IsTrue(value);
1740 Py_DECREF(value);
1741 if (initializing == -1)
1742 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001743 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001744 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1745 &PyId__lock_unlock_module, abs_name,
1746 NULL);
1747 if (value == NULL)
1748 goto error;
1749 Py_DECREF(value);
1750 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001751 }
Brett Cannonfd074152012-04-14 14:10:13 -04001752 }
1753 else {
Neil Schemenauer11cc2892017-12-07 16:24:59 -08001754 Py_XDECREF(mod);
Neil Schemenauereea3cc12017-12-03 09:26:03 -08001755 mod = import_find_and_load(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001756 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001757 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001758 }
1759 }
1760
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001761 has_from = 0;
1762 if (fromlist != NULL && fromlist != Py_None) {
1763 has_from = PyObject_IsTrue(fromlist);
1764 if (has_from < 0)
1765 goto error;
1766 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001767 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001768 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1769 if (level == 0 || len > 0) {
1770 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001771
Victor Stinner744c34e2016-05-20 11:36:13 +02001772 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1773 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001774 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001775 }
1776
Victor Stinner744c34e2016-05-20 11:36:13 +02001777 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001778 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001779 final_mod = mod;
1780 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001781 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001782 }
1783
Brett Cannonfd074152012-04-14 14:10:13 -04001784 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001785 PyObject *front = PyUnicode_Substring(name, 0, dot);
1786 if (front == NULL) {
1787 goto error;
1788 }
1789
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001790 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001791 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001792 }
1793 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001794 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001795 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001796 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001797 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001798 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001799 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001800 }
Brett Cannonfd074152012-04-14 14:10:13 -04001801
Eric Snow3f9eee62017-09-15 16:35:20 -06001802 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001803 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001804 if (final_mod == NULL) {
1805 PyErr_Format(PyExc_KeyError,
1806 "%R not in sys.modules as expected",
1807 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001808 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001809 }
Brett Cannonfd074152012-04-14 14:10:13 -04001810 }
1811 }
1812 else {
1813 final_mod = mod;
1814 Py_INCREF(mod);
1815 }
1816 }
1817 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001818 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001819 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001820 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001821 NULL);
1822 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001823
Brett Cannonfd074152012-04-14 14:10:13 -04001824 error:
1825 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001826 Py_XDECREF(mod);
1827 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001828 if (final_mod == NULL)
1829 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001830 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001831}
1832
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001833PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001834PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001835 PyObject *fromlist, int level)
1836{
1837 PyObject *nameobj, *mod;
1838 nameobj = PyUnicode_FromString(name);
1839 if (nameobj == NULL)
1840 return NULL;
1841 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1842 fromlist, level);
1843 Py_DECREF(nameobj);
1844 return mod;
1845}
1846
1847
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001848/* Re-import a module of any kind and return its module object, WITH
1849 INCREMENTED REFERENCE COUNT */
1850
Guido van Rossum79f25d91997-04-29 20:08:16 +00001851PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001852PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001853{
Eric Snow3f9eee62017-09-15 16:35:20 -06001854 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001855 _Py_IDENTIFIER(reload);
1856 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001857 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001858 if (imp == NULL) {
1859 imp = PyImport_ImportModule("imp");
1860 if (imp == NULL) {
1861 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001864
Victor Stinner55ba38a2016-12-09 16:09:30 +01001865 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001866 Py_DECREF(imp);
1867 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001868}
1869
1870
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001871/* Higher-level import emulator which emulates the "import" statement
1872 more accurately -- it invokes the __import__() function from the
1873 builtins of the current globals. This means that the import is
1874 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001875 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001876 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001877 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001878 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001879
1880PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001881PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 static PyObject *silly_list = NULL;
1884 static PyObject *builtins_str = NULL;
1885 static PyObject *import_str = NULL;
1886 PyObject *globals = NULL;
1887 PyObject *import = NULL;
1888 PyObject *builtins = NULL;
1889 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* Initialize constant string objects */
1892 if (silly_list == NULL) {
1893 import_str = PyUnicode_InternFromString("__import__");
1894 if (import_str == NULL)
1895 return NULL;
1896 builtins_str = PyUnicode_InternFromString("__builtins__");
1897 if (builtins_str == NULL)
1898 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001899 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (silly_list == NULL)
1901 return NULL;
1902 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* Get the builtins from current globals */
1905 globals = PyEval_GetGlobals();
1906 if (globals != NULL) {
1907 Py_INCREF(globals);
1908 builtins = PyObject_GetItem(globals, builtins_str);
1909 if (builtins == NULL)
1910 goto err;
1911 }
1912 else {
1913 /* No globals -- use standard builtins, and fake globals */
1914 builtins = PyImport_ImportModuleLevel("builtins",
1915 NULL, NULL, NULL, 0);
1916 if (builtins == NULL)
1917 return NULL;
1918 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1919 if (globals == NULL)
1920 goto err;
1921 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 /* Get the __import__ function from the builtins */
1924 if (PyDict_Check(builtins)) {
1925 import = PyObject_GetItem(builtins, import_str);
1926 if (import == NULL)
1927 PyErr_SetObject(PyExc_KeyError, import_str);
1928 }
1929 else
1930 import = PyObject_GetAttr(builtins, import_str);
1931 if (import == NULL)
1932 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001935 Always use absolute import here.
1936 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1938 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001939 if (r == NULL)
1940 goto err;
1941 Py_DECREF(r);
1942
Eric Snow3f9eee62017-09-15 16:35:20 -06001943 r = PyImport_GetModule(module_name);
1944 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001945 PyErr_SetObject(PyExc_KeyError, module_name);
1946 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001947
1948 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 Py_XDECREF(globals);
1950 Py_XDECREF(builtins);
1951 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001954}
1955
Brett Cannon4caa61d2014-01-09 19:03:32 -05001956/*[clinic input]
1957_imp.extension_suffixes
1958
1959Returns the list of file suffixes used to identify extension modules.
1960[clinic start generated code]*/
1961
Brett Cannon4caa61d2014-01-09 19:03:32 -05001962static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001963_imp_extension_suffixes_impl(PyObject *module)
1964/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001967 const char *suffix;
1968 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 list = PyList_New(0);
1971 if (list == NULL)
1972 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001973#ifdef HAVE_DYNAMIC_LOADING
1974 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1975 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (item == NULL) {
1977 Py_DECREF(list);
1978 return NULL;
1979 }
1980 if (PyList_Append(list, item) < 0) {
1981 Py_DECREF(list);
1982 Py_DECREF(item);
1983 return NULL;
1984 }
1985 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001986 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 }
Brett Cannon2657df42012-05-04 15:20:40 -04001988#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001990}
1991
Brett Cannon4caa61d2014-01-09 19:03:32 -05001992/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001993_imp.init_frozen
1994
1995 name: unicode
1996 /
1997
1998Initializes a frozen module.
1999[clinic start generated code]*/
2000
Brett Cannon4caa61d2014-01-09 19:03:32 -05002001static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002002_imp_init_frozen_impl(PyObject *module, PyObject *name)
2003/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 int ret;
2006 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002007
Victor Stinner53dc7352011-03-20 01:50:21 +01002008 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (ret < 0)
2010 return NULL;
2011 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002012 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002014 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 Py_XINCREF(m);
2016 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002017}
2018
Brett Cannon4caa61d2014-01-09 19:03:32 -05002019/*[clinic input]
2020_imp.get_frozen_object
2021
2022 name: unicode
2023 /
2024
2025Create a code object for a frozen module.
2026[clinic start generated code]*/
2027
Brett Cannon4caa61d2014-01-09 19:03:32 -05002028static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002029_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2030/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002033}
2034
Brett Cannon4caa61d2014-01-09 19:03:32 -05002035/*[clinic input]
2036_imp.is_frozen_package
2037
2038 name: unicode
2039 /
2040
2041Returns True if the module name is of a frozen package.
2042[clinic start generated code]*/
2043
Brett Cannon4caa61d2014-01-09 19:03:32 -05002044static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002045_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2046/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002049}
2050
Brett Cannon4caa61d2014-01-09 19:03:32 -05002051/*[clinic input]
2052_imp.is_builtin
2053
2054 name: unicode
2055 /
2056
2057Returns True if the module name corresponds to a built-in module.
2058[clinic start generated code]*/
2059
Guido van Rossum79f25d91997-04-29 20:08:16 +00002060static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002061_imp_is_builtin_impl(PyObject *module, PyObject *name)
2062/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002063{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002064 return PyLong_FromLong(is_builtin(name));
2065}
2066
2067/*[clinic input]
2068_imp.is_frozen
2069
2070 name: unicode
2071 /
2072
2073Returns True if the module name corresponds to a frozen module.
2074[clinic start generated code]*/
2075
Brett Cannon4caa61d2014-01-09 19:03:32 -05002076static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002077_imp_is_frozen_impl(PyObject *module, PyObject *name)
2078/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002079{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002080 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 p = find_frozen(name);
2083 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002084}
2085
Larry Hastings1df0b352015-08-24 19:53:56 -07002086/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2087static int
2088exec_builtin_or_dynamic(PyObject *mod) {
2089 PyModuleDef *def;
2090 void *state;
2091
2092 if (!PyModule_Check(mod)) {
2093 return 0;
2094 }
2095
2096 def = PyModule_GetDef(mod);
2097 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002098 return 0;
2099 }
Brett Cannon52794db2016-09-07 17:00:43 -07002100
Larry Hastings1df0b352015-08-24 19:53:56 -07002101 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002102 if (state) {
2103 /* Already initialized; skip reload */
2104 return 0;
2105 }
Brett Cannon52794db2016-09-07 17:00:43 -07002106
Larry Hastings1df0b352015-08-24 19:53:56 -07002107 return PyModule_ExecDef(mod, def);
2108}
2109
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002110#ifdef HAVE_DYNAMIC_LOADING
2111
Brett Cannon4caa61d2014-01-09 19:03:32 -05002112/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002113_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002114
Nick Coghland5cacbb2015-05-23 22:24:10 +10002115 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002116 file: object = NULL
2117 /
2118
Nick Coghland5cacbb2015-05-23 22:24:10 +10002119Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002120[clinic start generated code]*/
2121
Brett Cannon4caa61d2014-01-09 19:03:32 -05002122static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002123_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2124/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002125{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002126 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002127 FILE *fp;
2128
Nick Coghland5cacbb2015-05-23 22:24:10 +10002129 name = PyObject_GetAttrString(spec, "name");
2130 if (name == NULL) {
2131 return NULL;
2132 }
2133
2134 path = PyObject_GetAttrString(spec, "origin");
2135 if (path == NULL) {
2136 Py_DECREF(name);
2137 return NULL;
2138 }
2139
2140 mod = _PyImport_FindExtensionObject(name, path);
Miss Islington (bot)62674f32018-12-10 23:05:13 -08002141 if (mod != NULL || PyErr_Occurred()) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002142 Py_DECREF(name);
2143 Py_DECREF(path);
Miss Islington (bot)62674f32018-12-10 23:05:13 -08002144 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002145 return mod;
2146 }
2147
Brett Cannon4caa61d2014-01-09 19:03:32 -05002148 if (file != NULL) {
2149 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002150 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002151 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002152 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002154 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002156 else
2157 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002158
2159 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2160
2161 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002162 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (fp)
2164 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002165 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002166}
2167
Nick Coghland5cacbb2015-05-23 22:24:10 +10002168/*[clinic input]
2169_imp.exec_dynamic -> int
2170
2171 mod: object
2172 /
2173
2174Initialize an extension module.
2175[clinic start generated code]*/
2176
2177static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002178_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2179/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002180{
Larry Hastings1df0b352015-08-24 19:53:56 -07002181 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002182}
2183
2184
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002185#endif /* HAVE_DYNAMIC_LOADING */
2186
Larry Hastings7726ac92014-01-31 22:03:12 -08002187/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002188_imp.exec_builtin -> int
2189
2190 mod: object
2191 /
2192
2193Initialize a built-in module.
2194[clinic start generated code]*/
2195
2196static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002197_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2198/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002199{
2200 return exec_builtin_or_dynamic(mod);
2201}
2202
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002203/*[clinic input]
2204_imp.source_hash
2205
2206 key: long
2207 source: Py_buffer
2208[clinic start generated code]*/
2209
2210static PyObject *
2211_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2212/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2213{
Benjamin Peterson83620772017-12-09 12:18:56 -08002214 union {
2215 uint64_t x;
2216 char data[sizeof(uint64_t)];
2217 } hash;
2218 hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002219#if !PY_LITTLE_ENDIAN
2220 // Force to little-endian. There really ought to be a succinct standard way
2221 // to do this.
Benjamin Peterson83620772017-12-09 12:18:56 -08002222 for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2223 char tmp = hash.data[i];
2224 hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2225 hash.data[sizeof(hash.data) - i - 1] = tmp;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002226 }
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002227#endif
Benjamin Peterson83620772017-12-09 12:18:56 -08002228 return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002229}
2230
Barry Warsaw28a691b2010-04-17 00:19:56 +00002231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002232PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002233"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002234
Guido van Rossum79f25d91997-04-29 20:08:16 +00002235static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002236 _IMP_EXTENSION_SUFFIXES_METHODDEF
2237 _IMP_LOCK_HELD_METHODDEF
2238 _IMP_ACQUIRE_LOCK_METHODDEF
2239 _IMP_RELEASE_LOCK_METHODDEF
2240 _IMP_GET_FROZEN_OBJECT_METHODDEF
2241 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002242 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002243 _IMP_INIT_FROZEN_METHODDEF
2244 _IMP_IS_BUILTIN_METHODDEF
2245 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002246 _IMP_CREATE_DYNAMIC_METHODDEF
2247 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002248 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002249 _IMP__FIX_CO_FILENAME_METHODDEF
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002250 _IMP_SOURCE_HASH_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002251 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002252};
2253
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002254
Martin v. Löwis1a214512008-06-11 05:26:20 +00002255static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002257 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 doc_imp,
2259 0,
2260 imp_methods,
2261 NULL,
2262 NULL,
2263 NULL,
2264 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002265};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002266
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002267const char *_Py_CheckHashBasedPycsMode = "default";
2268
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002269PyMODINIT_FUNC
Benjamin Petersonc65ef772018-01-29 11:33:57 -08002270PyInit__imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 m = PyModule_Create(&impmodule);
2275 if (m == NULL)
2276 goto failure;
2277 d = PyModule_GetDict(m);
2278 if (d == NULL)
2279 goto failure;
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08002280 PyObject *pyc_mode = PyUnicode_FromString(_Py_CheckHashBasedPycsMode);
2281 if (pyc_mode == NULL) {
2282 goto failure;
2283 }
2284 if (PyDict_SetItemString(d, "check_hash_based_pycs", pyc_mode) < 0) {
2285 Py_DECREF(pyc_mode);
2286 goto failure;
2287 }
2288 Py_DECREF(pyc_mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002291 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 Py_XDECREF(m);
2293 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002294}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002295
2296
Guido van Rossumb18618d2000-05-03 23:44:39 +00002297/* API for embedding applications that want to add their own entries
2298 to the table of built-in modules. This should normally be called
2299 *before* Py_Initialize(). When the table resize fails, -1 is
2300 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002301
2302 After a similar function by Just van Rossum. */
2303
2304int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002305PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 struct _inittab *p;
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002308 size_t i, n;
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002309 int res = 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Count the number of entries in both tables */
2312 for (n = 0; newtab[n].name != NULL; n++)
2313 ;
2314 if (n == 0)
2315 return 0; /* Nothing to do */
2316 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2317 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002318
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002319 /* Force default raw memory allocator to get a known allocator to be able
2320 to release the memory in _PyImport_Fini2() */
2321 PyMemAllocatorEx old_alloc;
2322 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* Allocate new memory for the combined table */
Benjamin Peterson0c644fc2017-12-15 23:42:33 -08002325 p = NULL;
2326 if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002327 size_t size = sizeof(struct _inittab) * (i + n + 1);
2328 p = PyMem_RawRealloc(inittab_copy, size);
2329 }
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002330 if (p == NULL) {
2331 res = -1;
2332 goto done;
2333 }
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002334
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002335 /* Copy the tables into the new memory at the first call
2336 to PyImport_ExtendInittab(). */
2337 if (inittab_copy != PyImport_Inittab) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002339 }
2340 memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2341 PyImport_Inittab = inittab_copy = p;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002342
Victor Stinner92a3c6f2017-12-06 18:12:59 +01002343done:
2344 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2345 return res;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002346}
2347
2348/* Shorthand to add a single entry given a name and a function */
2349
2350int
Brett Cannona826f322009-04-02 03:41:46 +00002351PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002356
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002357 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002361}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002362
2363#ifdef __cplusplus
2364}
2365#endif