blob: 34f4fd504d81722675fd01e04335e702dc2155a7 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020011#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000014
Guido van Rossum55a83382000-09-20 20:31:38 +000015#ifdef HAVE_FCNTL_H
16#include <fcntl.h>
17#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000019extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000021
Barry Warsaw28a691b2010-04-17 00:19:56 +000022#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000023
Victor Stinner95872862011-03-07 18:20:56 +010024/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000025static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Guido van Rossum771c6c81997-10-31 18:37:24 +000027/* This table is defined in config.c: */
28extern struct _inittab _PyImport_Inittab[];
29
30struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000031
Victor Stinnerd0296212011-03-14 14:04:10 -040032static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033
Brett Cannon4caa61d2014-01-09 19:03:32 -050034/*[clinic input]
35module _imp
36[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080037/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050038
39/*[python input]
40class fs_unicode_converter(CConverter):
41 type = 'PyObject *'
42 converter = 'PyUnicode_FSDecoder'
43
44[python start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080045/*[python end generated code: output=da39a3ee5e6b4b0d input=9d6786230166006e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050046
Guido van Rossum1ae940a1995-01-02 19:04:15 +000047/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000048
49void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000050_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020052 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040053 initstr = PyUnicode_InternFromString("__init__");
54 if (initstr == NULL)
55 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020056 interp->builtins_copy = PyDict_Copy(interp->builtins);
57 if (interp->builtins_copy == NULL)
58 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059}
60
Guido van Rossum25ce5661997-08-02 03:10:38 +000061void
Just van Rossum52e14d62002-12-30 22:08:05 +000062_PyImportHooks_Init(void)
63{
Brett Cannonfd074152012-04-14 14:10:13 -040064 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000066
Brett Cannonfd074152012-04-14 14:10:13 -040067 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 v = PyList_New(0);
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("meta_path", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 v = PyDict_New();
76 if (v == NULL)
77 goto error;
78 err = PySys_SetObject("path_importer_cache", v);
79 Py_DECREF(v);
80 if (err)
81 goto error;
82 path_hooks = PyList_New(0);
83 if (path_hooks == NULL)
84 goto error;
85 err = PySys_SetObject("path_hooks", path_hooks);
86 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000087 error:
Brett Cannonfd074152012-04-14 14:10:13 -040088 PyErr_Print();
89 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020090 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
Brett Cannonfd074152012-04-14 14:10:13 -040092 Py_DECREF(path_hooks);
93}
94
95void
96_PyImportZip_Init(void)
97{
98 PyObject *path_hooks, *zimpimport;
99 int err = 0;
100
101 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200102 if (path_hooks == NULL) {
103 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400104 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200105 }
Brett Cannonfd074152012-04-14 14:10:13 -0400106
107 if (Py_VerboseFlag)
108 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 zimpimport = PyImport_ImportModule("zipimport");
111 if (zimpimport == NULL) {
112 PyErr_Clear(); /* No zip import module -- okay */
113 if (Py_VerboseFlag)
114 PySys_WriteStderr("# can't import zipimport\n");
115 }
116 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200117 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200118 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
119 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 Py_DECREF(zimpimport);
121 if (zipimporter == NULL) {
122 PyErr_Clear(); /* No zipimporter object -- okay */
123 if (Py_VerboseFlag)
124 PySys_WriteStderr(
125 "# can't import zipimport.zipimporter\n");
126 }
127 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400128 /* sys.path_hooks.insert(0, zipimporter) */
129 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400131 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (Py_VerboseFlag)
135 PySys_WriteStderr(
136 "# installed zipimport hook\n");
137 }
138 }
Brett Cannonfd074152012-04-14 14:10:13 -0400139
140 return;
141
142 error:
143 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400144 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000145}
146
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147/* Locking primitives to prevent parallel imports of the same module
148 in different threads to return with a partially loaded module.
149 These calls are serialized by the global interpreter lock. */
150
151#ifdef WITH_THREAD
152
Guido van Rossum49b56061998-10-01 20:42:43 +0000153#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154
Guido van Rossum65d5b571998-12-21 19:32:43 +0000155static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156static long import_lock_thread = -1;
157static int import_lock_level = 0;
158
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000159void
160_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 long me = PyThread_get_thread_ident();
163 if (me == -1)
164 return; /* Too bad */
165 if (import_lock == NULL) {
166 import_lock = PyThread_allocate_lock();
167 if (import_lock == NULL)
168 return; /* Nothing much we can do. */
169 }
170 if (import_lock_thread == me) {
171 import_lock_level++;
172 return;
173 }
174 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
175 {
176 PyThreadState *tstate = PyEval_SaveThread();
177 PyThread_acquire_lock(import_lock, 1);
178 PyEval_RestoreThread(tstate);
179 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100180 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 import_lock_thread = me;
182 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000183}
184
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000185int
186_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 long me = PyThread_get_thread_ident();
189 if (me == -1 || import_lock == NULL)
190 return 0; /* Too bad */
191 if (import_lock_thread != me)
192 return -1;
193 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100194 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (import_lock_level == 0) {
196 import_lock_thread = -1;
197 PyThread_release_lock(import_lock);
198 }
199 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000200}
201
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000202/* This function is called from PyOS_AfterFork to ensure that newly
203 created child processes do not share locks with the parent.
204 We now acquire the import lock around fork() calls but on some platforms
205 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000206
207void
208_PyImport_ReInitLock(void)
209{
Christian Heimes418fd742015-04-19 21:08:42 +0200210 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200212 if (import_lock == NULL) {
213 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
214 }
215 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000216 if (import_lock_level > 1) {
217 /* Forked as a side effect of import */
218 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500219 /* The following could fail if the lock is already held, but forking as
220 a side-effect of an import is a) rare, b) nuts, and c) difficult to
221 do thanks to the lock only being held when doing individual module
222 locks per import. */
223 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000224 import_lock_thread = me;
225 import_lock_level--;
226 } else {
227 import_lock_thread = -1;
228 import_lock_level = 0;
229 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000230}
231
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000232#endif
233
Brett Cannon4caa61d2014-01-09 19:03:32 -0500234/*[clinic input]
235_imp.lock_held
236
237Return True if the import lock is currently held, else False.
238
239On platforms without threads, return False.
240[clinic start generated code]*/
241
242PyDoc_STRVAR(_imp_lock_held__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800243"lock_held($module, /)\n"
244"--\n"
245"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500246"Return True if the import lock is currently held, else False.\n"
247"\n"
248"On platforms without threads, return False.");
249
250#define _IMP_LOCK_HELD_METHODDEF \
251 {"lock_held", (PyCFunction)_imp_lock_held, METH_NOARGS, _imp_lock_held__doc__},
252
Tim Peters69232342001-08-30 05:16:13 +0000253static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500254_imp_lock_held_impl(PyModuleDef *module);
255
256static PyObject *
257_imp_lock_held(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
258{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800259 return _imp_lock_held_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500260}
261
262static PyObject *
263_imp_lock_held_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800264/*[clinic end generated code: output=dae65674966baa65 input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000265{
Tim Peters69232342001-08-30 05:16:13 +0000266#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000268#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000270#endif
271}
272
Brett Cannon4caa61d2014-01-09 19:03:32 -0500273/*[clinic input]
274_imp.acquire_lock
275
276Acquires the interpreter's import lock for the current thread.
277
278This lock should be used by import hooks to ensure thread-safety when importing
279modules. On platforms without threads, this function does nothing.
280[clinic start generated code]*/
281
282PyDoc_STRVAR(_imp_acquire_lock__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800283"acquire_lock($module, /)\n"
284"--\n"
285"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500286"Acquires the interpreter\'s import lock for the current thread.\n"
287"\n"
288"This lock should be used by import hooks to ensure thread-safety when importing\n"
289"modules. On platforms without threads, this function does nothing.");
290
291#define _IMP_ACQUIRE_LOCK_METHODDEF \
292 {"acquire_lock", (PyCFunction)_imp_acquire_lock, METH_NOARGS, _imp_acquire_lock__doc__},
293
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000294static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500295_imp_acquire_lock_impl(PyModuleDef *module);
296
297static PyObject *
298_imp_acquire_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
299{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800300 return _imp_acquire_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500301}
302
303static PyObject *
304_imp_acquire_lock_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800305/*[clinic end generated code: output=478f1fa089fdb9a4 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000306{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000307#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000309#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 Py_INCREF(Py_None);
311 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000312}
313
Brett Cannon4caa61d2014-01-09 19:03:32 -0500314/*[clinic input]
315_imp.release_lock
316
317Release the interpreter's import lock.
318
319On platforms without threads, this function does nothing.
320[clinic start generated code]*/
321
322PyDoc_STRVAR(_imp_release_lock__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800323"release_lock($module, /)\n"
324"--\n"
325"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500326"Release the interpreter\'s import lock.\n"
327"\n"
328"On platforms without threads, this function does nothing.");
329
330#define _IMP_RELEASE_LOCK_METHODDEF \
331 {"release_lock", (PyCFunction)_imp_release_lock, METH_NOARGS, _imp_release_lock__doc__},
332
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000333static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500334_imp_release_lock_impl(PyModuleDef *module);
335
336static PyObject *
337_imp_release_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
338{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800339 return _imp_release_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500340}
341
342static PyObject *
343_imp_release_lock_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800344/*[clinic end generated code: output=36c77a6832fdafd4 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000345{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000346#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (_PyImport_ReleaseLock() < 0) {
348 PyErr_SetString(PyExc_RuntimeError,
349 "not holding the import lock");
350 return NULL;
351 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000352#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 Py_INCREF(Py_None);
354 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000355}
356
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100357void
358_PyImport_Fini(void)
359{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200360 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100361#ifdef WITH_THREAD
362 if (import_lock != NULL) {
363 PyThread_free_lock(import_lock);
364 import_lock = NULL;
365 }
366#endif
367}
368
Guido van Rossum25ce5661997-08-02 03:10:38 +0000369/* Helper for sys */
370
371PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000372PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyInterpreterState *interp = PyThreadState_GET()->interp;
375 if (interp->modules == NULL)
376 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
377 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378}
379
Guido van Rossum3f5da241990-12-20 15:06:42 +0000380
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000381/* List of names to clear in sys */
382static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 "path", "argv", "ps1", "ps2",
384 "last_type", "last_value", "last_traceback",
385 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200386 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 /* misc stuff */
388 "flags", "float_info",
389 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000390};
391
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000392static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 "stdin", "__stdin__",
394 "stdout", "__stdout__",
395 "stderr", "__stderr__",
396 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000397};
398
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000399/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000400
Guido van Rossum3f5da241990-12-20 15:06:42 +0000401void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000402PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000403{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200404 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 PyObject *key, *value, *dict;
406 PyInterpreterState *interp = PyThreadState_GET()->interp;
407 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200408 PyObject *weaklist = NULL;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200409 char **p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (modules == NULL)
412 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 /* Delete some special variables first. These are common
415 places where user values hide and people complain when their
416 destructors fail. Since the modules containing them are
417 deleted *last* of all, they would come too late in the normal
418 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000419
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200420 /* XXX Perhaps these precautions are obsolete. Who knows? */
421
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200422 if (Py_VerboseFlag)
423 PySys_WriteStderr("# clear builtins._\n");
424 PyDict_SetItemString(interp->builtins, "_", Py_None);
425
426 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200428 PySys_WriteStderr("# clear sys.%s\n", *p);
429 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200431 for (p = sys_files; *p != NULL; p+=2) {
432 if (Py_VerboseFlag)
433 PySys_WriteStderr("# restore sys.%s\n", *p);
434 value = PyDict_GetItemString(interp->sysdict, *(p+1));
435 if (value == NULL)
436 value = Py_None;
437 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000439
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200440 /* We prepare a list which will receive (name, weakref) tuples of
441 modules when they are removed from sys.modules. The name is used
442 for diagnosis messages (in verbose mode), while the weakref helps
443 detect those modules which have been held alive. */
444 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200445 if (weaklist == NULL)
446 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200447
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200448#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200449 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200450 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
451 if (name && wr) { \
452 PyObject *tup = PyTuple_Pack(2, name, wr); \
453 PyList_Append(weaklist, tup); \
454 Py_XDECREF(tup); \
455 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200456 Py_XDECREF(wr); \
457 if (PyErr_Occurred()) \
458 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000460
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200461 /* Remove all modules from sys.modules, hoping that garbage collection
462 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 pos = 0;
464 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200465 if (PyModule_Check(value)) {
466 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200467 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200468 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 PyDict_SetItem(modules, key, Py_None);
470 }
471 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000472
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200473 /* Clear the modules dict. */
474 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200475 /* Restore the original builtins dict, to ensure that any
476 user data gets cleared. */
477 dict = PyDict_Copy(interp->builtins);
478 if (dict == NULL)
479 PyErr_Clear();
480 PyDict_Clear(interp->builtins);
481 if (PyDict_Update(interp->builtins, interp->builtins_copy))
482 PyErr_Clear();
483 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200484 /* Clear module dict copies stored in the interpreter state */
485 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200486 /* Collect references */
487 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200488 /* Dump GC stats before it's too late, since it uses the warnings
489 machinery. */
490 _PyGC_DumpShutdownStats();
491
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200492 /* Now, if there are any modules left alive, clear their globals to
493 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200494 up here, since they are kept alive in the interpreter state.
495
496 The special treatment of "builtins" here is because even
497 when it's not referenced as a module, its dictionary is
498 referenced by almost every module's __builtins__. Since
499 deleting a module clears its dictionary (even if there are
500 references left to it), we need to delete the "builtins"
501 module last. Likewise, we don't delete sys until the very
502 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200503 if (weaklist != NULL) {
504 Py_ssize_t i, n;
505 n = PyList_GET_SIZE(weaklist);
506 for (i = 0; i < n; i++) {
507 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200508 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200509 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
510 if (mod == Py_None)
511 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200512 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200513 dict = PyModule_GetDict(mod);
514 if (dict == interp->builtins || dict == interp->sysdict)
515 continue;
516 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200517 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200518 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200519 _PyModule_Clear(mod);
520 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200521 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200522 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000524
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200525 /* Next, delete sys and builtins (in that order) */
526 if (Py_VerboseFlag)
527 PySys_FormatStderr("# cleanup[3] wiping sys\n");
528 _PyModule_ClearDict(interp->sysdict);
529 if (Py_VerboseFlag)
530 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
531 _PyModule_ClearDict(interp->builtins);
532
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200533 /* Clear and delete the modules directory. Actual modules will
534 still be there only if imported during the execution of some
535 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 interp->modules = NULL;
537 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200538
539 /* Once more */
540 _PyGC_CollectNoFail();
541
542#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000543}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000544
545
Barry Warsaw28a691b2010-04-17 00:19:56 +0000546/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547
548long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000549PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200551 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400552 PyInterpreterState *interp = PyThreadState_Get()->interp;
553 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
554 "_RAW_MAGIC_NUMBER");
555 if (pyc_magic == NULL)
556 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200557 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700558 Py_DECREF(pyc_magic);
559 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000560}
561
562
Brett Cannon3adc7b72012-07-09 14:22:12 -0400563extern const char * _PySys_ImplCacheTag;
564
Barry Warsaw28a691b2010-04-17 00:19:56 +0000565const char *
566PyImport_GetMagicTag(void)
567{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400568 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000569}
570
Brett Cannon98979b82012-07-02 15:13:11 -0400571
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572/* Magic for extension modules (built-in as well as dynamically
573 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200574 once, we keep a static dictionary 'extensions' keyed by the tuple
575 (module name, module name) (for built-in modules) or by
576 (filename, module name) (for dynamically loaded modules), containing these
577 modules. A copy of the module's dictionary is stored by calling
578 _PyImport_FixupExtensionObject() immediately after the module initialization
579 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100580 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000581
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000582 Modules which do support multiple initialization set their m_size
583 field to a non-negative number (indicating the size of the
584 module-specific state). They are still recorded in the extensions
585 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000586*/
587
588int
Victor Stinner95872862011-03-07 18:20:56 +0100589_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
590 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000591{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500592 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500594 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (extensions == NULL) {
596 extensions = PyDict_New();
597 if (extensions == NULL)
598 return -1;
599 }
600 if (mod == NULL || !PyModule_Check(mod)) {
601 PyErr_BadInternalCall();
602 return -1;
603 }
604 def = PyModule_GetDef(mod);
605 if (!def) {
606 PyErr_BadInternalCall();
607 return -1;
608 }
609 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100610 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return -1;
612 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100613 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 return -1;
615 }
616 if (def->m_size == -1) {
617 if (def->m_base.m_copy) {
618 /* Somebody already imported the module,
619 likely under a different name.
620 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200621 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 }
623 dict = PyModule_GetDict(mod);
624 if (dict == NULL)
625 return -1;
626 def->m_base.m_copy = PyDict_Copy(dict);
627 if (def->m_base.m_copy == NULL)
628 return -1;
629 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500630 key = PyTuple_Pack(2, filename, name);
631 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200632 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500633 res = PyDict_SetItem(extensions, key, (PyObject *)def);
634 Py_DECREF(key);
635 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200636 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638}
639
Victor Stinner49d3f252010-10-17 01:24:53 +0000640int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300641_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000642{
643 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100644 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100645 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100646 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000647 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100648 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
649 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000650 return res;
651}
652
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100654_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000655{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500656 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyModuleDef* def;
658 if (extensions == NULL)
659 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500660 key = PyTuple_Pack(2, filename, name);
661 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200662 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500663 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
664 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (def == NULL)
666 return NULL;
667 if (def->m_size == -1) {
668 /* Module does not support repeated initialization */
669 if (def->m_base.m_copy == NULL)
670 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100671 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (mod == NULL)
673 return NULL;
674 mdict = PyModule_GetDict(mod);
675 if (mdict == NULL)
676 return NULL;
677 if (PyDict_Update(mdict, def->m_base.m_copy))
678 return NULL;
679 }
680 else {
681 if (def->m_base.m_init == NULL)
682 return NULL;
683 mod = def->m_base.m_init();
684 if (mod == NULL)
685 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200686 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
687 Py_DECREF(mod);
688 return NULL;
689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 Py_DECREF(mod);
691 }
692 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100693 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 Py_DECREF(mod);
695 return NULL;
696 }
697 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100698 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 name, filename);
700 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000701
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702}
703
Victor Stinner49d3f252010-10-17 01:24:53 +0000704PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000705_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000706{
Victor Stinner95872862011-03-07 18:20:56 +0100707 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100708 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100709 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000710 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100711 res = _PyImport_FindExtensionObject(nameobj, nameobj);
712 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000713 return res;
714}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000715
716/* Get the module object corresponding to a module name.
717 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000718 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000719 Because the former action is most common, THIS DOES NOT RETURN A
720 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000721
Guido van Rossum79f25d91997-04-29 20:08:16 +0000722PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000723PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyObject *modules = PyImport_GetModuleDict();
726 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000727
Victor Stinner27ee0892011-03-04 12:57:09 +0000728 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyModule_Check(m))
730 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000731 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (m == NULL)
733 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000734 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 Py_DECREF(m);
736 return NULL;
737 }
738 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000741}
742
Victor Stinner27ee0892011-03-04 12:57:09 +0000743PyObject *
744PyImport_AddModule(const char *name)
745{
746 PyObject *nameobj, *module;
747 nameobj = PyUnicode_FromString(name);
748 if (nameobj == NULL)
749 return NULL;
750 module = PyImport_AddModuleObject(nameobj);
751 Py_DECREF(nameobj);
752 return module;
753}
754
755
Tim Peters1cd70172004-08-02 03:52:12 +0000756/* Remove name from sys.modules, if it's there. */
757static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000758remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000761 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000763 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 Py_FatalError("import: deleting existing key in"
765 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000766}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767
Christian Heimes3b06e532008-01-07 20:12:44 +0000768
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000769/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000770 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
771 * removed from sys.modules, to avoid leaving damaged module objects
772 * in sys.modules. The caller may wish to restore the original
773 * module object (if any) in this case; PyImport_ReloadModule is an
774 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000775 *
776 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
777 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000778 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000779PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300780PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 return PyImport_ExecCodeModuleWithPathnames(
783 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000784}
785
786PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300787PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 return PyImport_ExecCodeModuleWithPathnames(
790 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000791}
792
793PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300794PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
795 const char *pathname,
796 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000797{
Victor Stinner27ee0892011-03-04 12:57:09 +0000798 PyObject *m = NULL;
799 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
800
801 nameobj = PyUnicode_FromString(name);
802 if (nameobj == NULL)
803 return NULL;
804
Victor Stinner27ee0892011-03-04 12:57:09 +0000805 if (cpathname != NULL) {
806 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
807 if (cpathobj == NULL)
808 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400809 }
810 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000811 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400812
813 if (pathname != NULL) {
814 pathobj = PyUnicode_DecodeFSDefault(pathname);
815 if (pathobj == NULL)
816 goto error;
817 }
818 else if (cpathobj != NULL) {
819 PyInterpreterState *interp = PyThreadState_GET()->interp;
820 _Py_IDENTIFIER(_get_sourcefile);
821
822 if (interp == NULL) {
823 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
824 "no interpreter!");
825 }
826
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -0700827 pathobj = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannona6473f92012-07-13 13:57:03 -0400828 &PyId__get_sourcefile, cpathobj,
829 NULL);
830 if (pathobj == NULL)
831 PyErr_Clear();
832 }
833 else
834 pathobj = NULL;
835
Victor Stinner27ee0892011-03-04 12:57:09 +0000836 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
837error:
838 Py_DECREF(nameobj);
839 Py_XDECREF(pathobj);
840 Py_XDECREF(cpathobj);
841 return m;
842}
843
Brett Cannon18fc4e72014-04-04 10:01:46 -0400844static PyObject *
845module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000846{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400847 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000848
Victor Stinner27ee0892011-03-04 12:57:09 +0000849 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (m == NULL)
851 return NULL;
852 /* If the module is being reloaded, we get the old module back
853 and re-use its dict to exec the new code. */
854 d = PyModule_GetDict(m);
855 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
856 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400857 PyEval_GetBuiltins()) != 0) {
858 remove_module(name);
859 return NULL;
860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400862
Eric Snow08197a42014-05-12 17:54:55 -0600863 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400864}
865
866static PyObject *
867exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
868{
869 PyObject *modules = PyImport_GetModuleDict();
870 PyObject *v, *m;
871
872 v = PyEval_EvalCode(code_object, module_dict, module_dict);
873 if (v == NULL) {
874 remove_module(name);
875 return NULL;
876 }
877 Py_DECREF(v);
878
879 if ((m = PyDict_GetItem(modules, name)) == NULL) {
880 PyErr_Format(PyExc_ImportError,
881 "Loaded module %R not found in sys.modules",
882 name);
883 return NULL;
884 }
885
886 Py_INCREF(m);
887
888 return m;
889}
890
891PyObject*
892PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
893 PyObject *cpathname)
894{
Eric Snow08197a42014-05-12 17:54:55 -0600895 PyObject *d, *res;
896 PyInterpreterState *interp = PyThreadState_GET()->interp;
897 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400898
899 d = module_dict_for_exec(name);
900 if (d == NULL) {
901 return NULL;
902 }
903
Eric Snow08197a42014-05-12 17:54:55 -0600904 if (pathname == NULL) {
905 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
Eric Snow08197a42014-05-12 17:54:55 -0600907 res = _PyObject_CallMethodIdObjArgs(interp->importlib,
908 &PyId__fix_up_module,
909 d, name, pathname, cpathname, NULL);
910 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600911 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600912 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 }
Eric Snow08197a42014-05-12 17:54:55 -0600914 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000915}
916
917
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000918static void
919update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyObject *constants, *tmp;
922 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (PyUnicode_Compare(co->co_filename, oldname))
925 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 tmp = co->co_filename;
928 co->co_filename = newname;
929 Py_INCREF(co->co_filename);
930 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 constants = co->co_consts;
933 n = PyTuple_GET_SIZE(constants);
934 for (i = 0; i < n; i++) {
935 tmp = PyTuple_GET_ITEM(constants, i);
936 if (PyCode_Check(tmp))
937 update_code_filenames((PyCodeObject *)tmp,
938 oldname, newname);
939 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000940}
941
Victor Stinner2f42ae52011-03-20 00:41:24 +0100942static void
943update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000944{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100945 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000946
Victor Stinner2f42ae52011-03-20 00:41:24 +0100947 if (PyUnicode_Compare(co->co_filename, newname) == 0)
948 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 oldname = co->co_filename;
951 Py_INCREF(oldname);
952 update_code_filenames(co, oldname, newname);
953 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000954}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000955
Brett Cannon4caa61d2014-01-09 19:03:32 -0500956/*[clinic input]
957_imp._fix_co_filename
958
959 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
960 Code object to change.
961
962 path: unicode
963 File path to use.
964 /
965
966Changes code.co_filename to specify the passed-in file path.
967[clinic start generated code]*/
968
969PyDoc_STRVAR(_imp__fix_co_filename__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800970"_fix_co_filename($module, code, path, /)\n"
971"--\n"
972"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500973"Changes code.co_filename to specify the passed-in file path.\n"
974"\n"
975" code\n"
976" Code object to change.\n"
977" path\n"
978" File path to use.");
979
980#define _IMP__FIX_CO_FILENAME_METHODDEF \
981 {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_VARARGS, _imp__fix_co_filename__doc__},
982
Brett Cannon442c9b92011-03-23 16:14:42 -0700983static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500984_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path);
985
986static PyObject *
987_imp__fix_co_filename(PyModuleDef *module, PyObject *args)
Brett Cannon442c9b92011-03-23 16:14:42 -0700988{
Brett Cannon4caa61d2014-01-09 19:03:32 -0500989 PyObject *return_value = NULL;
990 PyCodeObject *code;
991 PyObject *path;
Brett Cannon442c9b92011-03-23 16:14:42 -0700992
Brett Cannon4caa61d2014-01-09 19:03:32 -0500993 if (!PyArg_ParseTuple(args,
994 "O!U:_fix_co_filename",
995 &PyCode_Type, &code, &path))
996 goto exit;
997 return_value = _imp__fix_co_filename_impl(module, code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700998
Brett Cannon4caa61d2014-01-09 19:03:32 -0500999exit:
1000 return return_value;
1001}
Brett Cannon442c9b92011-03-23 16:14:42 -07001002
Brett Cannon4caa61d2014-01-09 19:03:32 -05001003static PyObject *
1004_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001005/*[clinic end generated code: output=6b4b1edeb0d55c5d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001006
Brett Cannon4caa61d2014-01-09 19:03:32 -05001007{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001008 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001009
1010 Py_RETURN_NONE;
1011}
1012
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001013
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001014/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001015static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001016
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017
1018/* Helper to test for built-in module */
1019
1020static int
Victor Stinner95872862011-03-07 18:20:56 +01001021is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001022{
Victor Stinner95872862011-03-07 18:20:56 +01001023 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001025 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1026 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (PyImport_Inittab[i].initfunc == NULL)
1028 return -1;
1029 else
1030 return 1;
1031 }
1032 }
1033 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001034}
1035
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001036
Just van Rossum52e14d62002-12-30 22:08:05 +00001037/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1038 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001039 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001040 that can handle the path item. Return None if no hook could;
1041 this tells our caller it should fall back to the builtin
1042 import mechanism. Cache the result in path_importer_cache.
1043 Returns a borrowed reference. */
1044
1045static PyObject *
1046get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 PyObject *importer;
1050 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* These conditions are the caller's responsibility: */
1053 assert(PyList_Check(path_hooks));
1054 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 nhooks = PyList_Size(path_hooks);
1057 if (nhooks < 0)
1058 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 importer = PyDict_GetItem(path_importer_cache, p);
1061 if (importer != NULL)
1062 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* set path_importer_cache[p] to None to avoid recursion */
1065 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1066 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 for (j = 0; j < nhooks; j++) {
1069 PyObject *hook = PyList_GetItem(path_hooks, j);
1070 if (hook == NULL)
1071 return NULL;
1072 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1073 if (importer != NULL)
1074 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1077 return NULL;
1078 }
1079 PyErr_Clear();
1080 }
1081 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001082 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
1084 if (importer != NULL) {
1085 int err = PyDict_SetItem(path_importer_cache, p, importer);
1086 Py_DECREF(importer);
1087 if (err != 0)
1088 return NULL;
1089 }
1090 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001091}
1092
Christian Heimes9cd17752007-11-18 19:35:23 +00001093PyAPI_FUNC(PyObject *)
1094PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001096
Victor Stinner1e53bba2013-07-16 22:26:05 +02001097 path_importer_cache = PySys_GetObject("path_importer_cache");
1098 path_hooks = PySys_GetObject("path_hooks");
1099 if (path_importer_cache != NULL && path_hooks != NULL) {
1100 importer = get_path_importer(path_importer_cache,
1101 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
1103 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1104 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001105}
1106
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001107
Victor Stinner95872862011-03-07 18:20:56 +01001108static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001109
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001110/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001111 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001112 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001113
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001114static int
Victor Stinner95872862011-03-07 18:20:56 +01001115init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001118 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001119
Victor Stinner5eb4f592013-11-14 22:38:52 +01001120 mod = _PyImport_FindExtensionObject(name, name);
1121 if (PyErr_Occurred())
1122 return -1;
1123 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 for (p = PyImport_Inittab; p->name != NULL; p++) {
1127 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001128 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001129 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (p->initfunc == NULL) {
1131 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001132 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 name);
1134 return -1;
1135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 mod = (*p->initfunc)();
1137 if (mod == 0)
1138 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001139 /* Remember pointer to module init function. */
1140 def = PyModule_GetDef(mod);
1141 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001142 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 return -1;
1144 /* FixupExtension has put the module into sys.modules,
1145 so we can release our own reference. */
1146 Py_DECREF(mod);
1147 return 1;
1148 }
1149 }
1150 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001151}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001152
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001153
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001154/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001155
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001156static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001157find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001158{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001159 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001160
Victor Stinner53dc7352011-03-20 01:50:21 +01001161 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 for (p = PyImport_FrozenModules; ; p++) {
1165 if (p->name == NULL)
1166 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001167 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 break;
1169 }
1170 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001171}
1172
Guido van Rossum79f25d91997-04-29 20:08:16 +00001173static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001174get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001175{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001176 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (p == NULL) {
1180 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001181 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 name);
1183 return NULL;
1184 }
1185 if (p->code == NULL) {
1186 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001187 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 name);
1189 return NULL;
1190 }
1191 size = p->size;
1192 if (size < 0)
1193 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001194 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001195}
1196
Brett Cannon8d110132009-03-15 02:20:16 +00001197static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001198is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001199{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001200 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (p == NULL) {
1204 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001205 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 name);
1207 return NULL;
1208 }
Brett Cannon8d110132009-03-15 02:20:16 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (size < 0)
1213 Py_RETURN_TRUE;
1214 else
1215 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001216}
1217
1218
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001219/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001220 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001221 an exception set if the initialization failed.
1222 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001223
1224int
Victor Stinner53dc7352011-03-20 01:50:21 +01001225PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001226{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001227 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001228 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 int ispackage;
1230 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001231
Victor Stinner53dc7352011-03-20 01:50:21 +01001232 p = find_frozen(name);
1233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (p == NULL)
1235 return 0;
1236 if (p->code == NULL) {
1237 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001238 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 name);
1240 return -1;
1241 }
1242 size = p->size;
1243 ispackage = (size < 0);
1244 if (ispackage)
1245 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001246 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (co == NULL)
1248 return -1;
1249 if (!PyCode_Check(co)) {
1250 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001251 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 name);
1253 goto err_return;
1254 }
1255 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001256 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001257 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001259 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (m == NULL)
1261 goto err_return;
1262 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001263 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 goto err_return;
1266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 err = PyDict_SetItemString(d, "__path__", l);
1268 Py_DECREF(l);
1269 if (err != 0)
1270 goto err_return;
1271 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001272 d = module_dict_for_exec(name);
1273 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001274 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001275 }
1276 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (m == NULL)
1278 goto err_return;
1279 Py_DECREF(co);
1280 Py_DECREF(m);
1281 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001282err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 Py_DECREF(co);
1284 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001285}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001286
Victor Stinner53dc7352011-03-20 01:50:21 +01001287int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001288PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001289{
1290 PyObject *nameobj;
1291 int ret;
1292 nameobj = PyUnicode_InternFromString(name);
1293 if (nameobj == NULL)
1294 return -1;
1295 ret = PyImport_ImportFrozenModuleObject(nameobj);
1296 Py_DECREF(nameobj);
1297 return ret;
1298}
1299
Guido van Rossum74e6a111994-08-29 12:54:38 +00001300
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001301/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001302 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001303
Guido van Rossum79f25d91997-04-29 20:08:16 +00001304PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001305PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 PyObject *pname;
1308 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 pname = PyUnicode_FromString(name);
1311 if (pname == NULL)
1312 return NULL;
1313 result = PyImport_Import(pname);
1314 Py_DECREF(pname);
1315 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001316}
1317
Christian Heimes072c0f12008-01-03 23:01:04 +00001318/* Import a module without blocking
1319 *
1320 * At first it tries to fetch the module from sys.modules. If the module was
1321 * never loaded before it loads it with PyImport_ImportModule() unless another
1322 * thread holds the import lock. In the latter case the function raises an
1323 * ImportError instead of blocking.
1324 *
1325 * Returns the module object with incremented ref count.
1326 */
1327PyObject *
1328PyImport_ImportModuleNoBlock(const char *name)
1329{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001330 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001331}
1332
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001333
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001334/* Remove importlib frames from the traceback,
1335 * except in Verbose mode. */
1336static void
1337remove_importlib_frames(void)
1338{
1339 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001340 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001341 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001342 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001343 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001344 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001345
1346 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001347 from the traceback. We always trim chunks
1348 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001349
1350 PyErr_Fetch(&exception, &value, &base_tb);
1351 if (!exception || Py_VerboseFlag)
1352 goto done;
1353 if (PyType_IsSubtype((PyTypeObject *) exception,
1354 (PyTypeObject *) PyExc_ImportError))
1355 always_trim = 1;
1356
1357 prev_link = &base_tb;
1358 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001359 while (tb != NULL) {
1360 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1361 PyObject *next = (PyObject *) traceback->tb_next;
1362 PyFrameObject *frame = traceback->tb_frame;
1363 PyCodeObject *code = frame->f_code;
1364 int now_in_importlib;
1365
1366 assert(PyTraceBack_Check(tb));
1367 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1368 code->co_filename,
1369 importlib_filename) == 0);
1370 if (now_in_importlib && !in_importlib) {
1371 /* This is the link to this chunk of importlib tracebacks */
1372 outer_link = prev_link;
1373 }
1374 in_importlib = now_in_importlib;
1375
1376 if (in_importlib &&
1377 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001378 PyUnicode_CompareWithASCIIString(code->co_name,
1379 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001380 PyObject *tmp = *outer_link;
1381 *outer_link = next;
1382 Py_XINCREF(next);
1383 Py_DECREF(tmp);
1384 prev_link = outer_link;
1385 }
1386 else {
1387 prev_link = (PyObject **) &traceback->tb_next;
1388 }
1389 tb = next;
1390 }
1391done:
1392 PyErr_Restore(exception, value, base_tb);
1393}
1394
1395
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001396PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001397PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1398 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001399 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001400{
Brett Cannonfd074152012-04-14 14:10:13 -04001401 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001402 _Py_IDENTIFIER(__spec__);
1403 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001404 _Py_IDENTIFIER(__package__);
1405 _Py_IDENTIFIER(__path__);
1406 _Py_IDENTIFIER(__name__);
1407 _Py_IDENTIFIER(_find_and_load);
1408 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001409 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001410 _Py_static_string(single_dot, ".");
1411 PyObject *abs_name = NULL;
1412 PyObject *builtins_import = NULL;
1413 PyObject *final_mod = NULL;
1414 PyObject *mod = NULL;
1415 PyObject *package = NULL;
1416 PyObject *globals = NULL;
1417 PyObject *fromlist = NULL;
1418 PyInterpreterState *interp = PyThreadState_GET()->interp;
1419
1420 /* Make sure to use default values so as to not have
1421 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1422 NULL argument. */
1423 if (given_globals == NULL) {
1424 globals = PyDict_New();
1425 if (globals == NULL) {
1426 goto error;
1427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 }
Brett Cannonfd074152012-04-14 14:10:13 -04001429 else {
1430 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001431 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001432 if (level > 0 && !PyDict_Check(given_globals)) {
1433 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1434 goto error;
1435 }
1436 globals = given_globals;
1437 Py_INCREF(globals);
1438 }
1439
1440 if (given_fromlist == NULL) {
1441 fromlist = PyList_New(0);
1442 if (fromlist == NULL) {
1443 goto error;
1444 }
1445 }
1446 else {
1447 fromlist = given_fromlist;
1448 Py_INCREF(fromlist);
1449 }
1450 if (name == NULL) {
1451 PyErr_SetString(PyExc_ValueError, "Empty module name");
1452 goto error;
1453 }
1454
1455 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1456 for added performance. */
1457
1458 if (!PyUnicode_Check(name)) {
1459 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1460 goto error;
1461 }
1462 else if (PyUnicode_READY(name) < 0) {
1463 goto error;
1464 }
1465 if (level < 0) {
1466 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1467 goto error;
1468 }
1469 else if (level > 0) {
1470 package = _PyDict_GetItemId(globals, &PyId___package__);
1471 if (package != NULL && package != Py_None) {
1472 Py_INCREF(package);
1473 if (!PyUnicode_Check(package)) {
1474 PyErr_SetString(PyExc_TypeError, "package must be a string");
1475 goto error;
1476 }
1477 }
1478 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001479 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001480 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001481 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001482 goto error;
1483 }
1484 else if (!PyUnicode_Check(package)) {
1485 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1486 }
1487 Py_INCREF(package);
1488
1489 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001490 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001491 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1492 if (borrowed_dot == NULL) {
1493 goto error;
1494 }
Brett Cannon740fce02012-04-14 14:23:49 -04001495 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001496 Py_DECREF(package);
1497 if (partition == NULL) {
1498 goto error;
1499 }
1500 package = PyTuple_GET_ITEM(partition, 0);
1501 Py_INCREF(package);
1502 Py_DECREF(partition);
1503 }
1504 }
1505
1506 if (PyDict_GetItem(interp->modules, package) == NULL) {
1507 PyErr_Format(PyExc_SystemError,
1508 "Parent module %R not loaded, cannot perform relative "
1509 "import", package);
1510 goto error;
1511 }
1512 }
1513 else { /* level == 0 */
1514 if (PyUnicode_GET_LENGTH(name) == 0) {
1515 PyErr_SetString(PyExc_ValueError, "Empty module name");
1516 goto error;
1517 }
1518 package = Py_None;
1519 Py_INCREF(package);
1520 }
1521
1522 if (level > 0) {
1523 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1524 PyObject *base = NULL;
1525 int level_up = 1;
1526
1527 for (level_up = 1; level_up < level; level_up += 1) {
1528 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1529 if (last_dot == -2) {
1530 goto error;
1531 }
1532 else if (last_dot == -1) {
1533 PyErr_SetString(PyExc_ValueError,
1534 "attempted relative import beyond top-level "
1535 "package");
1536 goto error;
1537 }
1538 }
Victor Stinner22af2592013-11-13 12:11:36 +01001539
Brett Cannonfd074152012-04-14 14:10:13 -04001540 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001541 if (base == NULL)
1542 goto error;
1543
Brett Cannonfd074152012-04-14 14:10:13 -04001544 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001545 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001546
1547 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001548 seq = PyTuple_Pack(2, base, name);
1549 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001550 if (borrowed_dot == NULL || seq == NULL) {
1551 goto error;
1552 }
1553
1554 abs_name = PyUnicode_Join(borrowed_dot, seq);
1555 Py_DECREF(seq);
1556 if (abs_name == NULL) {
1557 goto error;
1558 }
1559 }
1560 else {
1561 abs_name = base;
1562 }
1563 }
1564 else {
1565 abs_name = name;
1566 Py_INCREF(abs_name);
1567 }
1568
Brian Curtine6b299f2012-04-14 14:19:33 -05001569#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001570 _PyImport_AcquireLock();
1571#endif
1572 /* From this point forward, goto error_with_unlock! */
1573 if (PyDict_Check(globals)) {
1574 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1575 }
1576 if (builtins_import == NULL) {
1577 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1578 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001579 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1580 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001581 }
1582 }
1583 Py_INCREF(builtins_import);
1584
1585 mod = PyDict_GetItem(interp->modules, abs_name);
1586 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001587 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1588 "None in sys.modules", abs_name);
1589 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001590 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001591 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001592 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001593 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001594 goto error_with_unlock;
1595 }
1596 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001597 PyObject *value = NULL;
1598 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001599 int initializing = 0;
1600
Brett Cannonfd074152012-04-14 14:10:13 -04001601 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001602 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001603 __spec__._initializing is true.
1604 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001605 stuffing the new module in sys.modules.
1606 */
Eric Snowb523f842013-11-22 09:05:39 -07001607 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1608 if (spec != NULL) {
1609 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1610 Py_DECREF(spec);
1611 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001612 if (value == NULL)
1613 PyErr_Clear();
1614 else {
1615 initializing = PyObject_IsTrue(value);
1616 Py_DECREF(value);
1617 if (initializing == -1)
1618 PyErr_Clear();
1619 }
1620 if (initializing > 0) {
1621 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001622 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001623 &PyId__lock_unlock_module, abs_name,
1624 NULL);
1625 if (value == NULL)
1626 goto error;
1627 Py_DECREF(value);
1628 }
1629 else {
1630#ifdef WITH_THREAD
1631 if (_PyImport_ReleaseLock() < 0) {
1632 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1633 goto error;
1634 }
1635#endif
1636 }
Brett Cannonfd074152012-04-14 14:10:13 -04001637 }
1638 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001639 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001640 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001641 &PyId__find_and_load, abs_name,
1642 builtins_import, NULL);
1643 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001644 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001645 }
1646 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001647 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001648
1649 if (PyObject_Not(fromlist)) {
1650 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1651 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001652 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001653 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1654
1655 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001656 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001657 }
1658
Brian Curtine6b299f2012-04-14 14:19:33 -05001659 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001660 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001661 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001662 }
1663
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001664 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1665 /* No dot in module name, simple exit */
1666 Py_DECREF(partition);
1667 final_mod = mod;
1668 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001669 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001670 }
1671
Brett Cannonfd074152012-04-14 14:10:13 -04001672 front = PyTuple_GET_ITEM(partition, 0);
1673 Py_INCREF(front);
1674 Py_DECREF(partition);
1675
1676 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001677 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001678 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001679 }
1680 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001681 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1682 PyUnicode_GET_LENGTH(front);
1683 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001684 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001685 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001686 Py_DECREF(front);
1687 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001688 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001689 }
Brett Cannonfd074152012-04-14 14:10:13 -04001690
1691 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001692 if (final_mod == NULL) {
1693 PyErr_Format(PyExc_KeyError,
1694 "%R not in sys.modules as expected",
1695 to_return);
1696 }
1697 else {
1698 Py_INCREF(final_mod);
1699 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001700 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001701 }
1702 }
1703 else {
1704 final_mod = mod;
1705 Py_INCREF(mod);
1706 }
1707 }
1708 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001709 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001710 &PyId__handle_fromlist, mod,
1711 fromlist, builtins_import,
1712 NULL);
1713 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001714 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001715
Brett Cannonfd074152012-04-14 14:10:13 -04001716 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001717#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001718 if (_PyImport_ReleaseLock() < 0) {
1719 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1720 }
1721#endif
1722 error:
1723 Py_XDECREF(abs_name);
1724 Py_XDECREF(builtins_import);
1725 Py_XDECREF(mod);
1726 Py_XDECREF(package);
1727 Py_XDECREF(globals);
1728 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001729 if (final_mod == NULL)
1730 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001731 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001732}
1733
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001734PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001735PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001736 PyObject *fromlist, int level)
1737{
1738 PyObject *nameobj, *mod;
1739 nameobj = PyUnicode_FromString(name);
1740 if (nameobj == NULL)
1741 return NULL;
1742 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1743 fromlist, level);
1744 Py_DECREF(nameobj);
1745 return mod;
1746}
1747
1748
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001749/* Re-import a module of any kind and return its module object, WITH
1750 INCREMENTED REFERENCE COUNT */
1751
Guido van Rossum79f25d91997-04-29 20:08:16 +00001752PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001753PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001754{
Brett Cannon62228db2012-04-29 14:38:11 -04001755 _Py_IDENTIFIER(reload);
1756 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001758 PyObject *imp = PyDict_GetItemString(modules, "imp");
1759 if (imp == NULL) {
1760 imp = PyImport_ImportModule("imp");
1761 if (imp == NULL) {
1762 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 }
Brett Cannon62228db2012-04-29 14:38:11 -04001765 else {
1766 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001768
Brett Cannon62228db2012-04-29 14:38:11 -04001769 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1770 Py_DECREF(imp);
1771 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001772}
1773
1774
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001775/* Higher-level import emulator which emulates the "import" statement
1776 more accurately -- it invokes the __import__() function from the
1777 builtins of the current globals. This means that the import is
1778 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001779 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001780 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001781 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001782 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001783
1784PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001785PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 static PyObject *silly_list = NULL;
1788 static PyObject *builtins_str = NULL;
1789 static PyObject *import_str = NULL;
1790 PyObject *globals = NULL;
1791 PyObject *import = NULL;
1792 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001793 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Initialize constant string objects */
1797 if (silly_list == NULL) {
1798 import_str = PyUnicode_InternFromString("__import__");
1799 if (import_str == NULL)
1800 return NULL;
1801 builtins_str = PyUnicode_InternFromString("__builtins__");
1802 if (builtins_str == NULL)
1803 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001804 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (silly_list == NULL)
1806 return NULL;
1807 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* Get the builtins from current globals */
1810 globals = PyEval_GetGlobals();
1811 if (globals != NULL) {
1812 Py_INCREF(globals);
1813 builtins = PyObject_GetItem(globals, builtins_str);
1814 if (builtins == NULL)
1815 goto err;
1816 }
1817 else {
1818 /* No globals -- use standard builtins, and fake globals */
1819 builtins = PyImport_ImportModuleLevel("builtins",
1820 NULL, NULL, NULL, 0);
1821 if (builtins == NULL)
1822 return NULL;
1823 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1824 if (globals == NULL)
1825 goto err;
1826 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 /* Get the __import__ function from the builtins */
1829 if (PyDict_Check(builtins)) {
1830 import = PyObject_GetItem(builtins, import_str);
1831 if (import == NULL)
1832 PyErr_SetObject(PyExc_KeyError, import_str);
1833 }
1834 else
1835 import = PyObject_GetAttr(builtins, import_str);
1836 if (import == NULL)
1837 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001840 Always use absolute import here.
1841 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1843 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001844 if (r == NULL)
1845 goto err;
1846 Py_DECREF(r);
1847
1848 modules = PyImport_GetModuleDict();
1849 r = PyDict_GetItem(modules, module_name);
1850 if (r != NULL)
1851 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001852
1853 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 Py_XDECREF(globals);
1855 Py_XDECREF(builtins);
1856 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001859}
1860
Brett Cannon4caa61d2014-01-09 19:03:32 -05001861/*[clinic input]
1862_imp.extension_suffixes
1863
1864Returns the list of file suffixes used to identify extension modules.
1865[clinic start generated code]*/
1866
1867PyDoc_STRVAR(_imp_extension_suffixes__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001868"extension_suffixes($module, /)\n"
1869"--\n"
1870"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001871"Returns the list of file suffixes used to identify extension modules.");
1872
1873#define _IMP_EXTENSION_SUFFIXES_METHODDEF \
1874 {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
1875
Barry Warsaw28a691b2010-04-17 00:19:56 +00001876static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001877_imp_extension_suffixes_impl(PyModuleDef *module);
1878
1879static PyObject *
1880_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1881{
Larry Hastingsbebf7352014-01-17 17:47:17 -08001882 return _imp_extension_suffixes_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001883}
1884
1885static PyObject *
1886_imp_extension_suffixes_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001887/*[clinic end generated code: output=bb30a2438167798c input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001890 const char *suffix;
1891 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 list = PyList_New(0);
1894 if (list == NULL)
1895 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001896#ifdef HAVE_DYNAMIC_LOADING
1897 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1898 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (item == NULL) {
1900 Py_DECREF(list);
1901 return NULL;
1902 }
1903 if (PyList_Append(list, item) < 0) {
1904 Py_DECREF(list);
1905 Py_DECREF(item);
1906 return NULL;
1907 }
1908 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001909 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 }
Brett Cannon2657df42012-05-04 15:20:40 -04001911#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001913}
1914
Brett Cannon4caa61d2014-01-09 19:03:32 -05001915/*[clinic input]
1916_imp.init_builtin
1917
1918 name: unicode
1919 /
1920
1921Initializes a built-in module.
1922[clinic start generated code]*/
1923
1924PyDoc_STRVAR(_imp_init_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001925"init_builtin($module, name, /)\n"
1926"--\n"
1927"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001928"Initializes a built-in module.");
1929
1930#define _IMP_INIT_BUILTIN_METHODDEF \
1931 {"init_builtin", (PyCFunction)_imp_init_builtin, METH_VARARGS, _imp_init_builtin__doc__},
1932
Guido van Rossum79f25d91997-04-29 20:08:16 +00001933static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001934_imp_init_builtin_impl(PyModuleDef *module, PyObject *name);
1935
1936static PyObject *
1937_imp_init_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001938{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001939 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01001940 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001941
1942 if (!PyArg_ParseTuple(args,
1943 "U:init_builtin",
1944 &name))
1945 goto exit;
1946 return_value = _imp_init_builtin_impl(module, name);
1947
1948exit:
1949 return return_value;
1950}
1951
1952static PyObject *
1953_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001954/*[clinic end generated code: output=a0244948a43f8e26 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 int ret;
1957 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 ret = init_builtin(name);
1960 if (ret < 0)
1961 return NULL;
1962 if (ret == 0) {
1963 Py_INCREF(Py_None);
1964 return Py_None;
1965 }
Victor Stinner95872862011-03-07 18:20:56 +01001966 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 Py_XINCREF(m);
1968 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001969}
1970
Brett Cannon4caa61d2014-01-09 19:03:32 -05001971/*[clinic input]
1972_imp.init_frozen
1973
1974 name: unicode
1975 /
1976
1977Initializes a frozen module.
1978[clinic start generated code]*/
1979
1980PyDoc_STRVAR(_imp_init_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001981"init_frozen($module, name, /)\n"
1982"--\n"
1983"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001984"Initializes a frozen module.");
1985
1986#define _IMP_INIT_FROZEN_METHODDEF \
1987 {"init_frozen", (PyCFunction)_imp_init_frozen, METH_VARARGS, _imp_init_frozen__doc__},
1988
Guido van Rossum79f25d91997-04-29 20:08:16 +00001989static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
1991
1992static PyObject *
1993_imp_init_frozen(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001994{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001995 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001996 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001997
1998 if (!PyArg_ParseTuple(args,
1999 "U:init_frozen",
2000 &name))
2001 goto exit;
2002 return_value = _imp_init_frozen_impl(module, name);
2003
2004exit:
2005 return return_value;
2006}
2007
2008static PyObject *
2009_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002010/*[clinic end generated code: output=e4bc2bff296f8f22 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 int ret;
2013 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002014
Victor Stinner53dc7352011-03-20 01:50:21 +01002015 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (ret < 0)
2017 return NULL;
2018 if (ret == 0) {
2019 Py_INCREF(Py_None);
2020 return Py_None;
2021 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002022 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 Py_XINCREF(m);
2024 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002025}
2026
Brett Cannon4caa61d2014-01-09 19:03:32 -05002027/*[clinic input]
2028_imp.get_frozen_object
2029
2030 name: unicode
2031 /
2032
2033Create a code object for a frozen module.
2034[clinic start generated code]*/
2035
2036PyDoc_STRVAR(_imp_get_frozen_object__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002037"get_frozen_object($module, name, /)\n"
2038"--\n"
2039"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002040"Create a code object for a frozen module.");
2041
2042#define _IMP_GET_FROZEN_OBJECT_METHODDEF \
2043 {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_VARARGS, _imp_get_frozen_object__doc__},
2044
Guido van Rossum79f25d91997-04-29 20:08:16 +00002045static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002046_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
2047
2048static PyObject *
2049_imp_get_frozen_object(PyModuleDef *module, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002050{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002051 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002052 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002053
Brett Cannon4caa61d2014-01-09 19:03:32 -05002054 if (!PyArg_ParseTuple(args,
2055 "U:get_frozen_object",
2056 &name))
2057 goto exit;
2058 return_value = _imp_get_frozen_object_impl(module, name);
2059
2060exit:
2061 return return_value;
2062}
2063
2064static PyObject *
2065_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002066/*[clinic end generated code: output=4089ec702a9d70c5 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002069}
2070
Brett Cannon4caa61d2014-01-09 19:03:32 -05002071/*[clinic input]
2072_imp.is_frozen_package
2073
2074 name: unicode
2075 /
2076
2077Returns True if the module name is of a frozen package.
2078[clinic start generated code]*/
2079
2080PyDoc_STRVAR(_imp_is_frozen_package__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002081"is_frozen_package($module, name, /)\n"
2082"--\n"
2083"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002084"Returns True if the module name is of a frozen package.");
2085
2086#define _IMP_IS_FROZEN_PACKAGE_METHODDEF \
2087 {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_VARARGS, _imp_is_frozen_package__doc__},
2088
Guido van Rossum79f25d91997-04-29 20:08:16 +00002089static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002090_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
2091
2092static PyObject *
2093_imp_is_frozen_package(PyModuleDef *module, PyObject *args)
Brett Cannon8d110132009-03-15 02:20:16 +00002094{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002095 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002096 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002097
Brett Cannon4caa61d2014-01-09 19:03:32 -05002098 if (!PyArg_ParseTuple(args,
2099 "U:is_frozen_package",
2100 &name))
2101 goto exit;
2102 return_value = _imp_is_frozen_package_impl(module, name);
2103
2104exit:
2105 return return_value;
2106}
2107
2108static PyObject *
2109_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002110/*[clinic end generated code: output=86aab14dcd4b959b input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002113}
2114
Brett Cannon4caa61d2014-01-09 19:03:32 -05002115/*[clinic input]
2116_imp.is_builtin
2117
2118 name: unicode
2119 /
2120
2121Returns True if the module name corresponds to a built-in module.
2122[clinic start generated code]*/
2123
2124PyDoc_STRVAR(_imp_is_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002125"is_builtin($module, name, /)\n"
2126"--\n"
2127"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002128"Returns True if the module name corresponds to a built-in module.");
2129
2130#define _IMP_IS_BUILTIN_METHODDEF \
2131 {"is_builtin", (PyCFunction)_imp_is_builtin, METH_VARARGS, _imp_is_builtin__doc__},
2132
Brett Cannon8d110132009-03-15 02:20:16 +00002133static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002134_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
2135
2136static PyObject *
2137_imp_is_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002138{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002139 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01002140 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002141
2142 if (!PyArg_ParseTuple(args,
2143 "U:is_builtin",
2144 &name))
2145 goto exit;
2146 return_value = _imp_is_builtin_impl(module, name);
2147
2148exit:
2149 return return_value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002150}
2151
Guido van Rossum79f25d91997-04-29 20:08:16 +00002152static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002153_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002154/*[clinic end generated code: output=d5847f8cac50946e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002155{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002156 return PyLong_FromLong(is_builtin(name));
2157}
2158
2159/*[clinic input]
2160_imp.is_frozen
2161
2162 name: unicode
2163 /
2164
2165Returns True if the module name corresponds to a frozen module.
2166[clinic start generated code]*/
2167
2168PyDoc_STRVAR(_imp_is_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002169"is_frozen($module, name, /)\n"
2170"--\n"
2171"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002172"Returns True if the module name corresponds to a frozen module.");
2173
2174#define _IMP_IS_FROZEN_METHODDEF \
2175 {"is_frozen", (PyCFunction)_imp_is_frozen, METH_VARARGS, _imp_is_frozen__doc__},
2176
2177static PyObject *
2178_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
2179
2180static PyObject *
2181_imp_is_frozen(PyModuleDef *module, PyObject *args)
2182{
2183 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002184 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002185
2186 if (!PyArg_ParseTuple(args,
2187 "U:is_frozen",
2188 &name))
2189 goto exit;
2190 return_value = _imp_is_frozen_impl(module, name);
2191
2192exit:
2193 return return_value;
2194}
2195
2196static PyObject *
2197_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002198/*[clinic end generated code: output=6691af884ba4987d input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002199{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002200 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 p = find_frozen(name);
2203 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002204}
2205
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002206#ifdef HAVE_DYNAMIC_LOADING
2207
Brett Cannon4caa61d2014-01-09 19:03:32 -05002208/*[clinic input]
2209_imp.load_dynamic
2210
2211 name: unicode
2212 path: fs_unicode
2213 file: object = NULL
2214 /
2215
2216Loads an extension module.
2217[clinic start generated code]*/
2218
2219PyDoc_STRVAR(_imp_load_dynamic__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002220"load_dynamic($module, name, path, file=None, /)\n"
2221"--\n"
2222"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002223"Loads an extension module.");
2224
2225#define _IMP_LOAD_DYNAMIC_METHODDEF \
2226 {"load_dynamic", (PyCFunction)_imp_load_dynamic, METH_VARARGS, _imp_load_dynamic__doc__},
2227
Guido van Rossum79f25d91997-04-29 20:08:16 +00002228static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002229_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file);
2230
2231static PyObject *
2232_imp_load_dynamic(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002233{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002234 PyObject *return_value = NULL;
2235 PyObject *name;
2236 PyObject *path;
2237 PyObject *file = NULL;
2238
2239 if (!PyArg_ParseTuple(args,
2240 "UO&|O:load_dynamic",
2241 &name, PyUnicode_FSDecoder, &path, &file))
2242 goto exit;
2243 return_value = _imp_load_dynamic_impl(module, name, path, file);
2244
2245exit:
2246 return return_value;
2247}
2248
2249static PyObject *
2250_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002251/*[clinic end generated code: output=81d11a1fbd1ea0a8 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002252{
2253 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002254 FILE *fp;
2255
Brett Cannon4caa61d2014-01-09 19:03:32 -05002256 if (file != NULL) {
2257 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002258 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002259 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002260 if (!PyErr_Occurred())
2261 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002265 else
2266 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002267 mod = _PyImport_LoadDynamicModule(name, path, fp);
2268 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (fp)
2270 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002271 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002272}
2273
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002274#endif /* HAVE_DYNAMIC_LOADING */
2275
Larry Hastings7726ac92014-01-31 22:03:12 -08002276/*[clinic input]
2277dump buffer
2278[clinic start generated code]*/
2279
2280#ifndef _IMP_LOAD_DYNAMIC_METHODDEF
2281 #define _IMP_LOAD_DYNAMIC_METHODDEF
2282#endif /* !defined(_IMP_LOAD_DYNAMIC_METHODDEF) */
2283/*[clinic end generated code: output=d07c1d4a343a9579 input=524ce2e021e4eba6]*/
2284
Barry Warsaw28a691b2010-04-17 00:19:56 +00002285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002286PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002287"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002288
Guido van Rossum79f25d91997-04-29 20:08:16 +00002289static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002290 _IMP_EXTENSION_SUFFIXES_METHODDEF
2291 _IMP_LOCK_HELD_METHODDEF
2292 _IMP_ACQUIRE_LOCK_METHODDEF
2293 _IMP_RELEASE_LOCK_METHODDEF
2294 _IMP_GET_FROZEN_OBJECT_METHODDEF
2295 _IMP_IS_FROZEN_PACKAGE_METHODDEF
2296 _IMP_INIT_BUILTIN_METHODDEF
2297 _IMP_INIT_FROZEN_METHODDEF
2298 _IMP_IS_BUILTIN_METHODDEF
2299 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002300 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002301 _IMP__FIX_CO_FILENAME_METHODDEF
2302 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002303};
2304
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002305
Martin v. Löwis1a214512008-06-11 05:26:20 +00002306static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002308 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 doc_imp,
2310 0,
2311 imp_methods,
2312 NULL,
2313 NULL,
2314 NULL,
2315 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002316};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002317
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002318PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002319PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 m = PyModule_Create(&impmodule);
2324 if (m == NULL)
2325 goto failure;
2326 d = PyModule_GetDict(m);
2327 if (d == NULL)
2328 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002331 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 Py_XDECREF(m);
2333 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002334}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002335
2336
Guido van Rossumb18618d2000-05-03 23:44:39 +00002337/* API for embedding applications that want to add their own entries
2338 to the table of built-in modules. This should normally be called
2339 *before* Py_Initialize(). When the table resize fails, -1 is
2340 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002341
2342 After a similar function by Just van Rossum. */
2343
2344int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002345PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 static struct _inittab *our_copy = NULL;
2348 struct _inittab *p;
2349 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* Count the number of entries in both tables */
2352 for (n = 0; newtab[n].name != NULL; n++)
2353 ;
2354 if (n == 0)
2355 return 0; /* Nothing to do */
2356 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2357 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* Allocate new memory for the combined table */
2360 p = our_copy;
2361 PyMem_RESIZE(p, struct _inittab, i+n+1);
2362 if (p == NULL)
2363 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Copy the tables into the new memory */
2366 if (our_copy != PyImport_Inittab)
2367 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2368 PyImport_Inittab = our_copy = p;
2369 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002372}
2373
2374/* Shorthand to add a single entry given a name and a function */
2375
2376int
Brett Cannona826f322009-04-02 03:41:46 +00002377PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 newtab[0].name = (char *)name;
2384 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002387}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002388
2389#ifdef __cplusplus
2390}
2391#endif
Larry Hastings7726ac92014-01-31 22:03:12 -08002392