blob: 4f0765a13a0d3778ccd8d733a47a8fba2c9522fc [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;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001419 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001420
1421 /* Make sure to use default values so as to not have
1422 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1423 NULL argument. */
1424 if (given_globals == NULL) {
1425 globals = PyDict_New();
1426 if (globals == NULL) {
1427 goto error;
1428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 }
Brett Cannonfd074152012-04-14 14:10:13 -04001430 else {
1431 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001432 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001433 if (level > 0 && !PyDict_Check(given_globals)) {
1434 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1435 goto error;
1436 }
1437 globals = given_globals;
1438 Py_INCREF(globals);
1439 }
1440
1441 if (given_fromlist == NULL) {
1442 fromlist = PyList_New(0);
1443 if (fromlist == NULL) {
1444 goto error;
1445 }
1446 }
1447 else {
1448 fromlist = given_fromlist;
1449 Py_INCREF(fromlist);
1450 }
1451 if (name == NULL) {
1452 PyErr_SetString(PyExc_ValueError, "Empty module name");
1453 goto error;
1454 }
1455
1456 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1457 for added performance. */
1458
1459 if (!PyUnicode_Check(name)) {
1460 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1461 goto error;
1462 }
1463 else if (PyUnicode_READY(name) < 0) {
1464 goto error;
1465 }
1466 if (level < 0) {
1467 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1468 goto error;
1469 }
1470 else if (level > 0) {
1471 package = _PyDict_GetItemId(globals, &PyId___package__);
1472 if (package != NULL && package != Py_None) {
1473 Py_INCREF(package);
1474 if (!PyUnicode_Check(package)) {
1475 PyErr_SetString(PyExc_TypeError, "package must be a string");
1476 goto error;
1477 }
1478 }
1479 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001480 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001481 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001482 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001483 goto error;
1484 }
1485 else if (!PyUnicode_Check(package)) {
1486 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1487 }
1488 Py_INCREF(package);
1489
1490 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001491 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001492 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1493 if (borrowed_dot == NULL) {
1494 goto error;
1495 }
Brett Cannon740fce02012-04-14 14:23:49 -04001496 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001497 Py_DECREF(package);
1498 if (partition == NULL) {
1499 goto error;
1500 }
1501 package = PyTuple_GET_ITEM(partition, 0);
1502 Py_INCREF(package);
1503 Py_DECREF(partition);
1504 }
1505 }
1506
1507 if (PyDict_GetItem(interp->modules, package) == NULL) {
1508 PyErr_Format(PyExc_SystemError,
1509 "Parent module %R not loaded, cannot perform relative "
1510 "import", package);
1511 goto error;
1512 }
1513 }
1514 else { /* level == 0 */
1515 if (PyUnicode_GET_LENGTH(name) == 0) {
1516 PyErr_SetString(PyExc_ValueError, "Empty module name");
1517 goto error;
1518 }
1519 package = Py_None;
1520 Py_INCREF(package);
1521 }
1522
1523 if (level > 0) {
1524 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1525 PyObject *base = NULL;
1526 int level_up = 1;
1527
1528 for (level_up = 1; level_up < level; level_up += 1) {
1529 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1530 if (last_dot == -2) {
1531 goto error;
1532 }
1533 else if (last_dot == -1) {
1534 PyErr_SetString(PyExc_ValueError,
1535 "attempted relative import beyond top-level "
1536 "package");
1537 goto error;
1538 }
1539 }
Victor Stinner22af2592013-11-13 12:11:36 +01001540
Brett Cannonfd074152012-04-14 14:10:13 -04001541 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001542 if (base == NULL)
1543 goto error;
1544
Brett Cannonfd074152012-04-14 14:10:13 -04001545 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001546 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001547
1548 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001549 seq = PyTuple_Pack(2, base, name);
1550 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001551 if (borrowed_dot == NULL || seq == NULL) {
1552 goto error;
1553 }
1554
1555 abs_name = PyUnicode_Join(borrowed_dot, seq);
1556 Py_DECREF(seq);
1557 if (abs_name == NULL) {
1558 goto error;
1559 }
1560 }
1561 else {
1562 abs_name = base;
1563 }
1564 }
1565 else {
1566 abs_name = name;
1567 Py_INCREF(abs_name);
1568 }
1569
Brian Curtine6b299f2012-04-14 14:19:33 -05001570#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001571 _PyImport_AcquireLock();
1572#endif
1573 /* From this point forward, goto error_with_unlock! */
1574 if (PyDict_Check(globals)) {
1575 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1576 }
1577 if (builtins_import == NULL) {
1578 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1579 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001580 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1581 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001582 }
1583 }
1584 Py_INCREF(builtins_import);
1585
1586 mod = PyDict_GetItem(interp->modules, abs_name);
1587 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001588 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1589 "None in sys.modules", abs_name);
1590 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001591 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001592 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001593 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001594 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001595 goto error_with_unlock;
1596 }
1597 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001598 PyObject *value = NULL;
1599 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001600 int initializing = 0;
1601
Brett Cannonfd074152012-04-14 14:10:13 -04001602 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001603 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001604 __spec__._initializing is true.
1605 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001606 stuffing the new module in sys.modules.
1607 */
Eric Snowb523f842013-11-22 09:05:39 -07001608 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1609 if (spec != NULL) {
1610 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1611 Py_DECREF(spec);
1612 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001613 if (value == NULL)
1614 PyErr_Clear();
1615 else {
1616 initializing = PyObject_IsTrue(value);
1617 Py_DECREF(value);
1618 if (initializing == -1)
1619 PyErr_Clear();
1620 }
1621 if (initializing > 0) {
1622 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001623 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001624 &PyId__lock_unlock_module, abs_name,
1625 NULL);
1626 if (value == NULL)
1627 goto error;
1628 Py_DECREF(value);
1629 }
1630 else {
1631#ifdef WITH_THREAD
1632 if (_PyImport_ReleaseLock() < 0) {
1633 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1634 goto error;
1635 }
1636#endif
1637 }
Brett Cannonfd074152012-04-14 14:10:13 -04001638 }
1639 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001640 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001641 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001642 &PyId__find_and_load, abs_name,
1643 builtins_import, NULL);
1644 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001645 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001646 }
1647 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001648 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001649
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001650 has_from = PyObject_IsTrue(fromlist);
1651 if (has_from < 0)
1652 goto error;
1653 if (!has_from) {
Brett Cannonfd074152012-04-14 14:10:13 -04001654 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1655 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001656 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001657 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1658
1659 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001660 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001661 }
1662
Brian Curtine6b299f2012-04-14 14:19:33 -05001663 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001664 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001665 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001666 }
1667
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001668 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1669 /* No dot in module name, simple exit */
1670 Py_DECREF(partition);
1671 final_mod = mod;
1672 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001673 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001674 }
1675
Brett Cannonfd074152012-04-14 14:10:13 -04001676 front = PyTuple_GET_ITEM(partition, 0);
1677 Py_INCREF(front);
1678 Py_DECREF(partition);
1679
1680 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001681 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001682 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001683 }
1684 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001685 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1686 PyUnicode_GET_LENGTH(front);
1687 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001688 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001689 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001690 Py_DECREF(front);
1691 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001692 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001693 }
Brett Cannonfd074152012-04-14 14:10:13 -04001694
1695 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001696 if (final_mod == NULL) {
1697 PyErr_Format(PyExc_KeyError,
1698 "%R not in sys.modules as expected",
1699 to_return);
1700 }
1701 else {
1702 Py_INCREF(final_mod);
1703 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001704 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001705 }
1706 }
1707 else {
1708 final_mod = mod;
1709 Py_INCREF(mod);
1710 }
1711 }
1712 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001713 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001714 &PyId__handle_fromlist, mod,
1715 fromlist, builtins_import,
1716 NULL);
1717 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001718 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001719
Brett Cannonfd074152012-04-14 14:10:13 -04001720 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001721#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001722 if (_PyImport_ReleaseLock() < 0) {
1723 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1724 }
1725#endif
1726 error:
1727 Py_XDECREF(abs_name);
1728 Py_XDECREF(builtins_import);
1729 Py_XDECREF(mod);
1730 Py_XDECREF(package);
1731 Py_XDECREF(globals);
1732 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001733 if (final_mod == NULL)
1734 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001735 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001736}
1737
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001738PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001739PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001740 PyObject *fromlist, int level)
1741{
1742 PyObject *nameobj, *mod;
1743 nameobj = PyUnicode_FromString(name);
1744 if (nameobj == NULL)
1745 return NULL;
1746 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1747 fromlist, level);
1748 Py_DECREF(nameobj);
1749 return mod;
1750}
1751
1752
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001753/* Re-import a module of any kind and return its module object, WITH
1754 INCREMENTED REFERENCE COUNT */
1755
Guido van Rossum79f25d91997-04-29 20:08:16 +00001756PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001757PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001758{
Brett Cannon62228db2012-04-29 14:38:11 -04001759 _Py_IDENTIFIER(reload);
1760 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001762 PyObject *imp = PyDict_GetItemString(modules, "imp");
1763 if (imp == NULL) {
1764 imp = PyImport_ImportModule("imp");
1765 if (imp == NULL) {
1766 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Brett Cannon62228db2012-04-29 14:38:11 -04001769 else {
1770 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001772
Brett Cannon62228db2012-04-29 14:38:11 -04001773 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1774 Py_DECREF(imp);
1775 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776}
1777
1778
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001779/* Higher-level import emulator which emulates the "import" statement
1780 more accurately -- it invokes the __import__() function from the
1781 builtins of the current globals. This means that the import is
1782 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001783 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001784 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001785 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001786 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001787
1788PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001789PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 static PyObject *silly_list = NULL;
1792 static PyObject *builtins_str = NULL;
1793 static PyObject *import_str = NULL;
1794 PyObject *globals = NULL;
1795 PyObject *import = NULL;
1796 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001797 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 /* Initialize constant string objects */
1801 if (silly_list == NULL) {
1802 import_str = PyUnicode_InternFromString("__import__");
1803 if (import_str == NULL)
1804 return NULL;
1805 builtins_str = PyUnicode_InternFromString("__builtins__");
1806 if (builtins_str == NULL)
1807 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001808 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (silly_list == NULL)
1810 return NULL;
1811 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 /* Get the builtins from current globals */
1814 globals = PyEval_GetGlobals();
1815 if (globals != NULL) {
1816 Py_INCREF(globals);
1817 builtins = PyObject_GetItem(globals, builtins_str);
1818 if (builtins == NULL)
1819 goto err;
1820 }
1821 else {
1822 /* No globals -- use standard builtins, and fake globals */
1823 builtins = PyImport_ImportModuleLevel("builtins",
1824 NULL, NULL, NULL, 0);
1825 if (builtins == NULL)
1826 return NULL;
1827 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1828 if (globals == NULL)
1829 goto err;
1830 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 /* Get the __import__ function from the builtins */
1833 if (PyDict_Check(builtins)) {
1834 import = PyObject_GetItem(builtins, import_str);
1835 if (import == NULL)
1836 PyErr_SetObject(PyExc_KeyError, import_str);
1837 }
1838 else
1839 import = PyObject_GetAttr(builtins, import_str);
1840 if (import == NULL)
1841 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001844 Always use absolute import here.
1845 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1847 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001848 if (r == NULL)
1849 goto err;
1850 Py_DECREF(r);
1851
1852 modules = PyImport_GetModuleDict();
1853 r = PyDict_GetItem(modules, module_name);
1854 if (r != NULL)
1855 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001856
1857 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 Py_XDECREF(globals);
1859 Py_XDECREF(builtins);
1860 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001863}
1864
Brett Cannon4caa61d2014-01-09 19:03:32 -05001865/*[clinic input]
1866_imp.extension_suffixes
1867
1868Returns the list of file suffixes used to identify extension modules.
1869[clinic start generated code]*/
1870
1871PyDoc_STRVAR(_imp_extension_suffixes__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001872"extension_suffixes($module, /)\n"
1873"--\n"
1874"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001875"Returns the list of file suffixes used to identify extension modules.");
1876
1877#define _IMP_EXTENSION_SUFFIXES_METHODDEF \
1878 {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
1879
Barry Warsaw28a691b2010-04-17 00:19:56 +00001880static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001881_imp_extension_suffixes_impl(PyModuleDef *module);
1882
1883static PyObject *
1884_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1885{
Larry Hastingsbebf7352014-01-17 17:47:17 -08001886 return _imp_extension_suffixes_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001887}
1888
1889static PyObject *
1890_imp_extension_suffixes_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001891/*[clinic end generated code: output=bb30a2438167798c input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001894 const char *suffix;
1895 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 list = PyList_New(0);
1898 if (list == NULL)
1899 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001900#ifdef HAVE_DYNAMIC_LOADING
1901 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1902 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 if (item == NULL) {
1904 Py_DECREF(list);
1905 return NULL;
1906 }
1907 if (PyList_Append(list, item) < 0) {
1908 Py_DECREF(list);
1909 Py_DECREF(item);
1910 return NULL;
1911 }
1912 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001913 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 }
Brett Cannon2657df42012-05-04 15:20:40 -04001915#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001917}
1918
Brett Cannon4caa61d2014-01-09 19:03:32 -05001919/*[clinic input]
1920_imp.init_builtin
1921
1922 name: unicode
1923 /
1924
1925Initializes a built-in module.
1926[clinic start generated code]*/
1927
1928PyDoc_STRVAR(_imp_init_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001929"init_builtin($module, name, /)\n"
1930"--\n"
1931"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001932"Initializes a built-in module.");
1933
1934#define _IMP_INIT_BUILTIN_METHODDEF \
1935 {"init_builtin", (PyCFunction)_imp_init_builtin, METH_VARARGS, _imp_init_builtin__doc__},
1936
Guido van Rossum79f25d91997-04-29 20:08:16 +00001937static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001938_imp_init_builtin_impl(PyModuleDef *module, PyObject *name);
1939
1940static PyObject *
1941_imp_init_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001942{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001943 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01001944 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001945
1946 if (!PyArg_ParseTuple(args,
1947 "U:init_builtin",
1948 &name))
1949 goto exit;
1950 return_value = _imp_init_builtin_impl(module, name);
1951
1952exit:
1953 return return_value;
1954}
1955
1956static PyObject *
1957_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001958/*[clinic end generated code: output=a0244948a43f8e26 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 int ret;
1961 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 ret = init_builtin(name);
1964 if (ret < 0)
1965 return NULL;
1966 if (ret == 0) {
1967 Py_INCREF(Py_None);
1968 return Py_None;
1969 }
Victor Stinner95872862011-03-07 18:20:56 +01001970 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 Py_XINCREF(m);
1972 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001973}
1974
Brett Cannon4caa61d2014-01-09 19:03:32 -05001975/*[clinic input]
1976_imp.init_frozen
1977
1978 name: unicode
1979 /
1980
1981Initializes a frozen module.
1982[clinic start generated code]*/
1983
1984PyDoc_STRVAR(_imp_init_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001985"init_frozen($module, name, /)\n"
1986"--\n"
1987"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001988"Initializes a frozen module.");
1989
1990#define _IMP_INIT_FROZEN_METHODDEF \
1991 {"init_frozen", (PyCFunction)_imp_init_frozen, METH_VARARGS, _imp_init_frozen__doc__},
1992
Guido van Rossum79f25d91997-04-29 20:08:16 +00001993static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001994_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
1995
1996static PyObject *
1997_imp_init_frozen(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001998{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001999 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002000 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002001
2002 if (!PyArg_ParseTuple(args,
2003 "U:init_frozen",
2004 &name))
2005 goto exit;
2006 return_value = _imp_init_frozen_impl(module, name);
2007
2008exit:
2009 return return_value;
2010}
2011
2012static PyObject *
2013_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002014/*[clinic end generated code: output=e4bc2bff296f8f22 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 int ret;
2017 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002018
Victor Stinner53dc7352011-03-20 01:50:21 +01002019 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (ret < 0)
2021 return NULL;
2022 if (ret == 0) {
2023 Py_INCREF(Py_None);
2024 return Py_None;
2025 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002026 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 Py_XINCREF(m);
2028 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002029}
2030
Brett Cannon4caa61d2014-01-09 19:03:32 -05002031/*[clinic input]
2032_imp.get_frozen_object
2033
2034 name: unicode
2035 /
2036
2037Create a code object for a frozen module.
2038[clinic start generated code]*/
2039
2040PyDoc_STRVAR(_imp_get_frozen_object__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002041"get_frozen_object($module, name, /)\n"
2042"--\n"
2043"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002044"Create a code object for a frozen module.");
2045
2046#define _IMP_GET_FROZEN_OBJECT_METHODDEF \
2047 {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_VARARGS, _imp_get_frozen_object__doc__},
2048
Guido van Rossum79f25d91997-04-29 20:08:16 +00002049static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002050_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
2051
2052static PyObject *
2053_imp_get_frozen_object(PyModuleDef *module, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002054{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002055 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002056 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002057
Brett Cannon4caa61d2014-01-09 19:03:32 -05002058 if (!PyArg_ParseTuple(args,
2059 "U:get_frozen_object",
2060 &name))
2061 goto exit;
2062 return_value = _imp_get_frozen_object_impl(module, name);
2063
2064exit:
2065 return return_value;
2066}
2067
2068static PyObject *
2069_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002070/*[clinic end generated code: output=4089ec702a9d70c5 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002073}
2074
Brett Cannon4caa61d2014-01-09 19:03:32 -05002075/*[clinic input]
2076_imp.is_frozen_package
2077
2078 name: unicode
2079 /
2080
2081Returns True if the module name is of a frozen package.
2082[clinic start generated code]*/
2083
2084PyDoc_STRVAR(_imp_is_frozen_package__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002085"is_frozen_package($module, name, /)\n"
2086"--\n"
2087"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002088"Returns True if the module name is of a frozen package.");
2089
2090#define _IMP_IS_FROZEN_PACKAGE_METHODDEF \
2091 {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_VARARGS, _imp_is_frozen_package__doc__},
2092
Guido van Rossum79f25d91997-04-29 20:08:16 +00002093static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002094_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
2095
2096static PyObject *
2097_imp_is_frozen_package(PyModuleDef *module, PyObject *args)
Brett Cannon8d110132009-03-15 02:20:16 +00002098{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002099 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002100 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002101
Brett Cannon4caa61d2014-01-09 19:03:32 -05002102 if (!PyArg_ParseTuple(args,
2103 "U:is_frozen_package",
2104 &name))
2105 goto exit;
2106 return_value = _imp_is_frozen_package_impl(module, name);
2107
2108exit:
2109 return return_value;
2110}
2111
2112static PyObject *
2113_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002114/*[clinic end generated code: output=86aab14dcd4b959b input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002117}
2118
Brett Cannon4caa61d2014-01-09 19:03:32 -05002119/*[clinic input]
2120_imp.is_builtin
2121
2122 name: unicode
2123 /
2124
2125Returns True if the module name corresponds to a built-in module.
2126[clinic start generated code]*/
2127
2128PyDoc_STRVAR(_imp_is_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002129"is_builtin($module, name, /)\n"
2130"--\n"
2131"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002132"Returns True if the module name corresponds to a built-in module.");
2133
2134#define _IMP_IS_BUILTIN_METHODDEF \
2135 {"is_builtin", (PyCFunction)_imp_is_builtin, METH_VARARGS, _imp_is_builtin__doc__},
2136
Brett Cannon8d110132009-03-15 02:20:16 +00002137static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002138_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
2139
2140static PyObject *
2141_imp_is_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002142{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002143 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01002144 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002145
2146 if (!PyArg_ParseTuple(args,
2147 "U:is_builtin",
2148 &name))
2149 goto exit;
2150 return_value = _imp_is_builtin_impl(module, name);
2151
2152exit:
2153 return return_value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002154}
2155
Guido van Rossum79f25d91997-04-29 20:08:16 +00002156static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002157_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002158/*[clinic end generated code: output=d5847f8cac50946e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002159{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002160 return PyLong_FromLong(is_builtin(name));
2161}
2162
2163/*[clinic input]
2164_imp.is_frozen
2165
2166 name: unicode
2167 /
2168
2169Returns True if the module name corresponds to a frozen module.
2170[clinic start generated code]*/
2171
2172PyDoc_STRVAR(_imp_is_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002173"is_frozen($module, name, /)\n"
2174"--\n"
2175"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002176"Returns True if the module name corresponds to a frozen module.");
2177
2178#define _IMP_IS_FROZEN_METHODDEF \
2179 {"is_frozen", (PyCFunction)_imp_is_frozen, METH_VARARGS, _imp_is_frozen__doc__},
2180
2181static PyObject *
2182_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
2183
2184static PyObject *
2185_imp_is_frozen(PyModuleDef *module, PyObject *args)
2186{
2187 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002188 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002189
2190 if (!PyArg_ParseTuple(args,
2191 "U:is_frozen",
2192 &name))
2193 goto exit;
2194 return_value = _imp_is_frozen_impl(module, name);
2195
2196exit:
2197 return return_value;
2198}
2199
2200static PyObject *
2201_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002202/*[clinic end generated code: output=6691af884ba4987d input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002203{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002204 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 p = find_frozen(name);
2207 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002208}
2209
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002210#ifdef HAVE_DYNAMIC_LOADING
2211
Brett Cannon4caa61d2014-01-09 19:03:32 -05002212/*[clinic input]
2213_imp.load_dynamic
2214
2215 name: unicode
2216 path: fs_unicode
2217 file: object = NULL
2218 /
2219
2220Loads an extension module.
2221[clinic start generated code]*/
2222
2223PyDoc_STRVAR(_imp_load_dynamic__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002224"load_dynamic($module, name, path, file=None, /)\n"
2225"--\n"
2226"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002227"Loads an extension module.");
2228
2229#define _IMP_LOAD_DYNAMIC_METHODDEF \
2230 {"load_dynamic", (PyCFunction)_imp_load_dynamic, METH_VARARGS, _imp_load_dynamic__doc__},
2231
Guido van Rossum79f25d91997-04-29 20:08:16 +00002232static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002233_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file);
2234
2235static PyObject *
2236_imp_load_dynamic(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002237{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002238 PyObject *return_value = NULL;
2239 PyObject *name;
2240 PyObject *path;
2241 PyObject *file = NULL;
2242
2243 if (!PyArg_ParseTuple(args,
2244 "UO&|O:load_dynamic",
2245 &name, PyUnicode_FSDecoder, &path, &file))
2246 goto exit;
2247 return_value = _imp_load_dynamic_impl(module, name, path, file);
2248
2249exit:
2250 return return_value;
2251}
2252
2253static PyObject *
2254_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002255/*[clinic end generated code: output=81d11a1fbd1ea0a8 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002256{
2257 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002258 FILE *fp;
2259
Brett Cannon4caa61d2014-01-09 19:03:32 -05002260 if (file != NULL) {
2261 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002262 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002263 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002264 if (!PyErr_Occurred())
2265 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002267 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002269 else
2270 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002271 mod = _PyImport_LoadDynamicModule(name, path, fp);
2272 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (fp)
2274 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002275 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002276}
2277
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002278#endif /* HAVE_DYNAMIC_LOADING */
2279
Larry Hastings7726ac92014-01-31 22:03:12 -08002280/*[clinic input]
2281dump buffer
2282[clinic start generated code]*/
2283
2284#ifndef _IMP_LOAD_DYNAMIC_METHODDEF
2285 #define _IMP_LOAD_DYNAMIC_METHODDEF
2286#endif /* !defined(_IMP_LOAD_DYNAMIC_METHODDEF) */
2287/*[clinic end generated code: output=d07c1d4a343a9579 input=524ce2e021e4eba6]*/
2288
Barry Warsaw28a691b2010-04-17 00:19:56 +00002289
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002290PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002291"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002292
Guido van Rossum79f25d91997-04-29 20:08:16 +00002293static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002294 _IMP_EXTENSION_SUFFIXES_METHODDEF
2295 _IMP_LOCK_HELD_METHODDEF
2296 _IMP_ACQUIRE_LOCK_METHODDEF
2297 _IMP_RELEASE_LOCK_METHODDEF
2298 _IMP_GET_FROZEN_OBJECT_METHODDEF
2299 _IMP_IS_FROZEN_PACKAGE_METHODDEF
2300 _IMP_INIT_BUILTIN_METHODDEF
2301 _IMP_INIT_FROZEN_METHODDEF
2302 _IMP_IS_BUILTIN_METHODDEF
2303 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002304 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002305 _IMP__FIX_CO_FILENAME_METHODDEF
2306 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002307};
2308
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002309
Martin v. Löwis1a214512008-06-11 05:26:20 +00002310static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002312 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 doc_imp,
2314 0,
2315 imp_methods,
2316 NULL,
2317 NULL,
2318 NULL,
2319 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002320};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002321
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002322PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002323PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 m = PyModule_Create(&impmodule);
2328 if (m == NULL)
2329 goto failure;
2330 d = PyModule_GetDict(m);
2331 if (d == NULL)
2332 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002335 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 Py_XDECREF(m);
2337 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002338}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002339
2340
Guido van Rossumb18618d2000-05-03 23:44:39 +00002341/* API for embedding applications that want to add their own entries
2342 to the table of built-in modules. This should normally be called
2343 *before* Py_Initialize(). When the table resize fails, -1 is
2344 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002345
2346 After a similar function by Just van Rossum. */
2347
2348int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002349PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 static struct _inittab *our_copy = NULL;
2352 struct _inittab *p;
2353 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* Count the number of entries in both tables */
2356 for (n = 0; newtab[n].name != NULL; n++)
2357 ;
2358 if (n == 0)
2359 return 0; /* Nothing to do */
2360 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2361 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Allocate new memory for the combined table */
2364 p = our_copy;
2365 PyMem_RESIZE(p, struct _inittab, i+n+1);
2366 if (p == NULL)
2367 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* Copy the tables into the new memory */
2370 if (our_copy != PyImport_Inittab)
2371 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2372 PyImport_Inittab = our_copy = p;
2373 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002376}
2377
2378/* Shorthand to add a single entry given a name and a function */
2379
2380int
Brett Cannona826f322009-04-02 03:41:46 +00002381PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 newtab[0].name = (char *)name;
2388 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002391}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002392
2393#ifdef __cplusplus
2394}
2395#endif
Larry Hastings7726ac92014-01-31 22:03:12 -08002396