blob: 5e5355d48523e19e806538653ab42876c407282b [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{
Victor Stinnerd0296212011-03-14 14:04:10 -040052 initstr = PyUnicode_InternFromString("__init__");
53 if (initstr == NULL)
54 Py_FatalError("Can't initialize import variables");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055}
56
Guido van Rossum25ce5661997-08-02 03:10:38 +000057void
Just van Rossum52e14d62002-12-30 22:08:05 +000058_PyImportHooks_Init(void)
59{
Brett Cannonfd074152012-04-14 14:10:13 -040060 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000062
Brett Cannonfd074152012-04-14 14:10:13 -040063 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 v = PyList_New(0);
65 if (v == NULL)
66 goto error;
67 err = PySys_SetObject("meta_path", v);
68 Py_DECREF(v);
69 if (err)
70 goto error;
71 v = PyDict_New();
72 if (v == NULL)
73 goto error;
74 err = PySys_SetObject("path_importer_cache", v);
75 Py_DECREF(v);
76 if (err)
77 goto error;
78 path_hooks = PyList_New(0);
79 if (path_hooks == NULL)
80 goto error;
81 err = PySys_SetObject("path_hooks", path_hooks);
82 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000083 error:
Brett Cannonfd074152012-04-14 14:10:13 -040084 PyErr_Print();
85 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020086 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 }
Brett Cannonfd074152012-04-14 14:10:13 -040088 Py_DECREF(path_hooks);
89}
90
91void
92_PyImportZip_Init(void)
93{
94 PyObject *path_hooks, *zimpimport;
95 int err = 0;
96
97 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020098 if (path_hooks == NULL) {
99 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400100 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200101 }
Brett Cannonfd074152012-04-14 14:10:13 -0400102
103 if (Py_VerboseFlag)
104 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 zimpimport = PyImport_ImportModule("zipimport");
107 if (zimpimport == NULL) {
108 PyErr_Clear(); /* No zip import module -- okay */
109 if (Py_VerboseFlag)
110 PySys_WriteStderr("# can't import zipimport\n");
111 }
112 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200113 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200114 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
115 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 Py_DECREF(zimpimport);
117 if (zipimporter == NULL) {
118 PyErr_Clear(); /* No zipimporter object -- okay */
119 if (Py_VerboseFlag)
120 PySys_WriteStderr(
121 "# can't import zipimport.zipimporter\n");
122 }
123 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400124 /* sys.path_hooks.insert(0, zipimporter) */
125 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400127 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400129 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (Py_VerboseFlag)
131 PySys_WriteStderr(
132 "# installed zipimport hook\n");
133 }
134 }
Brett Cannonfd074152012-04-14 14:10:13 -0400135
136 return;
137
138 error:
139 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400140 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000141}
142
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000143/* Locking primitives to prevent parallel imports of the same module
144 in different threads to return with a partially loaded module.
145 These calls are serialized by the global interpreter lock. */
146
147#ifdef WITH_THREAD
148
Guido van Rossum49b56061998-10-01 20:42:43 +0000149#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000150
Guido van Rossum65d5b571998-12-21 19:32:43 +0000151static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000152static long import_lock_thread = -1;
153static int import_lock_level = 0;
154
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000155void
156_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 long me = PyThread_get_thread_ident();
159 if (me == -1)
160 return; /* Too bad */
161 if (import_lock == NULL) {
162 import_lock = PyThread_allocate_lock();
163 if (import_lock == NULL)
164 return; /* Nothing much we can do. */
165 }
166 if (import_lock_thread == me) {
167 import_lock_level++;
168 return;
169 }
170 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
171 {
172 PyThreadState *tstate = PyEval_SaveThread();
173 PyThread_acquire_lock(import_lock, 1);
174 PyEval_RestoreThread(tstate);
175 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100176 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 import_lock_thread = me;
178 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000179}
180
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000181int
182_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 long me = PyThread_get_thread_ident();
185 if (me == -1 || import_lock == NULL)
186 return 0; /* Too bad */
187 if (import_lock_thread != me)
188 return -1;
189 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100190 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (import_lock_level == 0) {
192 import_lock_thread = -1;
193 PyThread_release_lock(import_lock);
194 }
195 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000196}
197
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000198/* This function is called from PyOS_AfterFork to ensure that newly
199 created child processes do not share locks with the parent.
200 We now acquire the import lock around fork() calls but on some platforms
201 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000202
203void
204_PyImport_ReInitLock(void)
205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 if (import_lock != NULL)
207 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000208 if (import_lock_level > 1) {
209 /* Forked as a side effect of import */
210 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500211 /* The following could fail if the lock is already held, but forking as
212 a side-effect of an import is a) rare, b) nuts, and c) difficult to
213 do thanks to the lock only being held when doing individual module
214 locks per import. */
215 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000216 import_lock_thread = me;
217 import_lock_level--;
218 } else {
219 import_lock_thread = -1;
220 import_lock_level = 0;
221 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000222}
223
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000224#endif
225
Brett Cannon4caa61d2014-01-09 19:03:32 -0500226/*[clinic input]
227_imp.lock_held
228
229Return True if the import lock is currently held, else False.
230
231On platforms without threads, return False.
232[clinic start generated code]*/
233
234PyDoc_STRVAR(_imp_lock_held__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -0800235"sig=($module)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500236"Return True if the import lock is currently held, else False.\n"
237"\n"
238"On platforms without threads, return False.");
239
240#define _IMP_LOCK_HELD_METHODDEF \
241 {"lock_held", (PyCFunction)_imp_lock_held, METH_NOARGS, _imp_lock_held__doc__},
242
Tim Peters69232342001-08-30 05:16:13 +0000243static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500244_imp_lock_held_impl(PyModuleDef *module);
245
246static PyObject *
247_imp_lock_held(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
248{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800249 return _imp_lock_held_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500250}
251
252static PyObject *
253_imp_lock_held_impl(PyModuleDef *module)
Larry Hastings581ee362014-01-28 05:00:08 -0800254/*[clinic end generated code: output=5ce46d12a8e4c469 input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000255{
Tim Peters69232342001-08-30 05:16:13 +0000256#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000258#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000260#endif
261}
262
Brett Cannon4caa61d2014-01-09 19:03:32 -0500263/*[clinic input]
264_imp.acquire_lock
265
266Acquires the interpreter's import lock for the current thread.
267
268This lock should be used by import hooks to ensure thread-safety when importing
269modules. On platforms without threads, this function does nothing.
270[clinic start generated code]*/
271
272PyDoc_STRVAR(_imp_acquire_lock__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -0800273"sig=($module)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500274"Acquires the interpreter\'s import lock for the current thread.\n"
275"\n"
276"This lock should be used by import hooks to ensure thread-safety when importing\n"
277"modules. On platforms without threads, this function does nothing.");
278
279#define _IMP_ACQUIRE_LOCK_METHODDEF \
280 {"acquire_lock", (PyCFunction)_imp_acquire_lock, METH_NOARGS, _imp_acquire_lock__doc__},
281
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000282static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500283_imp_acquire_lock_impl(PyModuleDef *module);
284
285static PyObject *
286_imp_acquire_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
287{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800288 return _imp_acquire_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500289}
290
291static PyObject *
292_imp_acquire_lock_impl(PyModuleDef *module)
Larry Hastings581ee362014-01-28 05:00:08 -0800293/*[clinic end generated code: output=b0dd6a132ad25961 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000294{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000295#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000297#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 Py_INCREF(Py_None);
299 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000300}
301
Brett Cannon4caa61d2014-01-09 19:03:32 -0500302/*[clinic input]
303_imp.release_lock
304
305Release the interpreter's import lock.
306
307On platforms without threads, this function does nothing.
308[clinic start generated code]*/
309
310PyDoc_STRVAR(_imp_release_lock__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -0800311"sig=($module)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500312"Release the interpreter\'s import lock.\n"
313"\n"
314"On platforms without threads, this function does nothing.");
315
316#define _IMP_RELEASE_LOCK_METHODDEF \
317 {"release_lock", (PyCFunction)_imp_release_lock, METH_NOARGS, _imp_release_lock__doc__},
318
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000319static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500320_imp_release_lock_impl(PyModuleDef *module);
321
322static PyObject *
323_imp_release_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
324{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800325 return _imp_release_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500326}
327
328static PyObject *
329_imp_release_lock_impl(PyModuleDef *module)
Larry Hastings581ee362014-01-28 05:00:08 -0800330/*[clinic end generated code: output=b1e6e9d723cf5f89 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000331{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000332#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (_PyImport_ReleaseLock() < 0) {
334 PyErr_SetString(PyExc_RuntimeError,
335 "not holding the import lock");
336 return NULL;
337 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000338#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 Py_INCREF(Py_None);
340 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000341}
342
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100343void
344_PyImport_Fini(void)
345{
346 Py_XDECREF(extensions);
347 extensions = NULL;
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100348#ifdef WITH_THREAD
349 if (import_lock != NULL) {
350 PyThread_free_lock(import_lock);
351 import_lock = NULL;
352 }
353#endif
354}
355
Guido van Rossum25ce5661997-08-02 03:10:38 +0000356/* Helper for sys */
357
358PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000359PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyInterpreterState *interp = PyThreadState_GET()->interp;
362 if (interp->modules == NULL)
363 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
364 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365}
366
Guido van Rossum3f5da241990-12-20 15:06:42 +0000367
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000368/* List of names to clear in sys */
369static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 "path", "argv", "ps1", "ps2",
371 "last_type", "last_value", "last_traceback",
372 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200373 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 /* misc stuff */
375 "flags", "float_info",
376 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000377};
378
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000379static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 "stdin", "__stdin__",
381 "stdout", "__stdout__",
382 "stderr", "__stderr__",
383 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000384};
385
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000386/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000387
Guido van Rossum3f5da241990-12-20 15:06:42 +0000388void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000389PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000390{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200391 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyObject *key, *value, *dict;
393 PyInterpreterState *interp = PyThreadState_GET()->interp;
394 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200395 PyObject *builtins = interp->builtins;
396 PyObject *weaklist = NULL;
Guido van Rossum758eec01998-01-19 21:58:26 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (modules == NULL)
399 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 /* Delete some special variables first. These are common
402 places where user values hide and people complain when their
403 destructors fail. Since the modules containing them are
404 deleted *last* of all, they would come too late in the normal
405 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000406
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200407 /* XXX Perhaps these precautions are obsolete. Who knows? */
408
Victor Stinnerbd303c12013-11-07 23:07:29 +0100409 value = PyDict_GetItemString(modules, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 if (value != NULL && PyModule_Check(value)) {
411 dict = PyModule_GetDict(value);
412 if (Py_VerboseFlag)
413 PySys_WriteStderr("# clear builtins._\n");
414 PyDict_SetItemString(dict, "_", Py_None);
415 }
416 value = PyDict_GetItemString(modules, "sys");
417 if (value != NULL && PyModule_Check(value)) {
418 char **p;
419 PyObject *v;
420 dict = PyModule_GetDict(value);
421 for (p = sys_deletes; *p != NULL; p++) {
422 if (Py_VerboseFlag)
423 PySys_WriteStderr("# clear sys.%s\n", *p);
424 PyDict_SetItemString(dict, *p, Py_None);
425 }
426 for (p = sys_files; *p != NULL; p+=2) {
427 if (Py_VerboseFlag)
428 PySys_WriteStderr("# restore sys.%s\n", *p);
429 v = PyDict_GetItemString(dict, *(p+1));
430 if (v == NULL)
431 v = Py_None;
432 PyDict_SetItemString(dict, *p, v);
433 }
434 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200436 /* We prepare a list which will receive (name, weakref) tuples of
437 modules when they are removed from sys.modules. The name is used
438 for diagnosis messages (in verbose mode), while the weakref helps
439 detect those modules which have been held alive. */
440 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200441 if (weaklist == NULL)
442 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200443
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200444#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200445 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200446 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
447 if (name && wr) { \
448 PyObject *tup = PyTuple_Pack(2, name, wr); \
449 PyList_Append(weaklist, tup); \
450 Py_XDECREF(tup); \
451 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200452 Py_XDECREF(wr); \
453 if (PyErr_Occurred()) \
454 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000456
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457 /* Remove all modules from sys.modules, hoping that garbage collection
458 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 pos = 0;
460 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200461 if (PyModule_Check(value)) {
462 if (Py_VerboseFlag && PyUnicode_Check(key))
463 PySys_FormatStderr("# cleanup[2] removing %U\n", key, value);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200464 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PyDict_SetItem(modules, key, Py_None);
466 }
467 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000468
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200469 /* Clear the modules dict. */
470 PyDict_Clear(modules);
471 /* Replace the interpreter's reference to builtins with an empty dict
472 (module globals still have a reference to the original builtins). */
473 builtins = interp->builtins;
474 interp->builtins = PyDict_New();
475 Py_DECREF(builtins);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200476 /* Clear module dict copies stored in the interpreter state */
477 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200478 /* Collect references */
479 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200480 /* Dump GC stats before it's too late, since it uses the warnings
481 machinery. */
482 _PyGC_DumpShutdownStats();
483
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200484 /* Now, if there are any modules left alive, clear their globals to
485 minimize potential leaks. All C extension modules actually end
486 up here, since they are kept alive in the interpreter state. */
487 if (weaklist != NULL) {
488 Py_ssize_t i, n;
489 n = PyList_GET_SIZE(weaklist);
490 for (i = 0; i < n; i++) {
491 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200492 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200493 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
494 if (mod == Py_None)
495 continue;
496 Py_INCREF(mod);
497 assert(PyModule_Check(mod));
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200498 if (Py_VerboseFlag && PyUnicode_Check(name))
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200499 PySys_FormatStderr("# cleanup[3] wiping %U\n",
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200500 name, mod);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200501 _PyModule_Clear(mod);
502 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200503 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200504 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000506
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200507 /* Clear and delete the modules directory. Actual modules will
508 still be there only if imported during the execution of some
509 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 interp->modules = NULL;
511 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200512
513 /* Once more */
514 _PyGC_CollectNoFail();
515
516#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000517}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000518
519
Barry Warsaw28a691b2010-04-17 00:19:56 +0000520/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000521
522long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000523PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000524{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200525 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400526 PyInterpreterState *interp = PyThreadState_Get()->interp;
527 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
528 "_RAW_MAGIC_NUMBER");
529 if (pyc_magic == NULL)
530 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200531 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700532 Py_DECREF(pyc_magic);
533 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000534}
535
536
Brett Cannon3adc7b72012-07-09 14:22:12 -0400537extern const char * _PySys_ImplCacheTag;
538
Barry Warsaw28a691b2010-04-17 00:19:56 +0000539const char *
540PyImport_GetMagicTag(void)
541{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400542 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000543}
544
Brett Cannon98979b82012-07-02 15:13:11 -0400545
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546/* Magic for extension modules (built-in as well as dynamically
547 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200548 once, we keep a static dictionary 'extensions' keyed by the tuple
549 (module name, module name) (for built-in modules) or by
550 (filename, module name) (for dynamically loaded modules), containing these
551 modules. A copy of the module's dictionary is stored by calling
552 _PyImport_FixupExtensionObject() immediately after the module initialization
553 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100554 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000555
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000556 Modules which do support multiple initialization set their m_size
557 field to a non-negative number (indicating the size of the
558 module-specific state). They are still recorded in the extensions
559 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000560*/
561
562int
Victor Stinner95872862011-03-07 18:20:56 +0100563_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
564 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000565{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500566 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500568 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (extensions == NULL) {
570 extensions = PyDict_New();
571 if (extensions == NULL)
572 return -1;
573 }
574 if (mod == NULL || !PyModule_Check(mod)) {
575 PyErr_BadInternalCall();
576 return -1;
577 }
578 def = PyModule_GetDef(mod);
579 if (!def) {
580 PyErr_BadInternalCall();
581 return -1;
582 }
583 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100584 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return -1;
586 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100587 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 return -1;
589 }
590 if (def->m_size == -1) {
591 if (def->m_base.m_copy) {
592 /* Somebody already imported the module,
593 likely under a different name.
594 XXX this should really not happen. */
595 Py_DECREF(def->m_base.m_copy);
596 def->m_base.m_copy = NULL;
597 }
598 dict = PyModule_GetDict(mod);
599 if (dict == NULL)
600 return -1;
601 def->m_base.m_copy = PyDict_Copy(dict);
602 if (def->m_base.m_copy == NULL)
603 return -1;
604 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500605 key = PyTuple_Pack(2, filename, name);
606 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200607 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500608 res = PyDict_SetItem(extensions, key, (PyObject *)def);
609 Py_DECREF(key);
610 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200611 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000613}
614
Victor Stinner49d3f252010-10-17 01:24:53 +0000615int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300616_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000617{
618 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100619 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100620 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100621 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000622 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100623 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
624 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000625 return res;
626}
627
Guido van Rossum25ce5661997-08-02 03:10:38 +0000628PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100629_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500631 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyModuleDef* def;
633 if (extensions == NULL)
634 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500635 key = PyTuple_Pack(2, filename, name);
636 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200637 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500638 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
639 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (def == NULL)
641 return NULL;
642 if (def->m_size == -1) {
643 /* Module does not support repeated initialization */
644 if (def->m_base.m_copy == NULL)
645 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100646 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (mod == NULL)
648 return NULL;
649 mdict = PyModule_GetDict(mod);
650 if (mdict == NULL)
651 return NULL;
652 if (PyDict_Update(mdict, def->m_base.m_copy))
653 return NULL;
654 }
655 else {
656 if (def->m_base.m_init == NULL)
657 return NULL;
658 mod = def->m_base.m_init();
659 if (mod == NULL)
660 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200661 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
662 Py_DECREF(mod);
663 return NULL;
664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 Py_DECREF(mod);
666 }
667 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100668 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 Py_DECREF(mod);
670 return NULL;
671 }
672 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100673 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 name, filename);
675 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000676
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000677}
678
Victor Stinner49d3f252010-10-17 01:24:53 +0000679PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000680_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000681{
Victor Stinner95872862011-03-07 18:20:56 +0100682 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100683 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100684 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000685 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100686 res = _PyImport_FindExtensionObject(nameobj, nameobj);
687 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000688 return res;
689}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000690
691/* Get the module object corresponding to a module name.
692 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000693 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000694 Because the former action is most common, THIS DOES NOT RETURN A
695 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696
Guido van Rossum79f25d91997-04-29 20:08:16 +0000697PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000698PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject *modules = PyImport_GetModuleDict();
701 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702
Victor Stinner27ee0892011-03-04 12:57:09 +0000703 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyModule_Check(m))
705 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000706 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (m == NULL)
708 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000709 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_DECREF(m);
711 return NULL;
712 }
713 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000716}
717
Victor Stinner27ee0892011-03-04 12:57:09 +0000718PyObject *
719PyImport_AddModule(const char *name)
720{
721 PyObject *nameobj, *module;
722 nameobj = PyUnicode_FromString(name);
723 if (nameobj == NULL)
724 return NULL;
725 module = PyImport_AddModuleObject(nameobj);
726 Py_DECREF(nameobj);
727 return module;
728}
729
730
Tim Peters1cd70172004-08-02 03:52:12 +0000731/* Remove name from sys.modules, if it's there. */
732static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000733remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000736 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000738 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 Py_FatalError("import: deleting existing key in"
740 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000741}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000742
Christian Heimes3b06e532008-01-07 20:12:44 +0000743
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000744/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000745 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
746 * removed from sys.modules, to avoid leaving damaged module objects
747 * in sys.modules. The caller may wish to restore the original
748 * module object (if any) in this case; PyImport_ReloadModule is an
749 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000750 *
751 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
752 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000753 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000754PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300755PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 return PyImport_ExecCodeModuleWithPathnames(
758 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000759}
760
761PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300762PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 return PyImport_ExecCodeModuleWithPathnames(
765 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000766}
767
768PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300769PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
770 const char *pathname,
771 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000772{
Victor Stinner27ee0892011-03-04 12:57:09 +0000773 PyObject *m = NULL;
774 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
775
776 nameobj = PyUnicode_FromString(name);
777 if (nameobj == NULL)
778 return NULL;
779
Victor Stinner27ee0892011-03-04 12:57:09 +0000780 if (cpathname != NULL) {
781 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
782 if (cpathobj == NULL)
783 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400784 }
785 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000786 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400787
788 if (pathname != NULL) {
789 pathobj = PyUnicode_DecodeFSDefault(pathname);
790 if (pathobj == NULL)
791 goto error;
792 }
793 else if (cpathobj != NULL) {
794 PyInterpreterState *interp = PyThreadState_GET()->interp;
795 _Py_IDENTIFIER(_get_sourcefile);
796
797 if (interp == NULL) {
798 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
799 "no interpreter!");
800 }
801
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -0700802 pathobj = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannona6473f92012-07-13 13:57:03 -0400803 &PyId__get_sourcefile, cpathobj,
804 NULL);
805 if (pathobj == NULL)
806 PyErr_Clear();
807 }
808 else
809 pathobj = NULL;
810
Victor Stinner27ee0892011-03-04 12:57:09 +0000811 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
812error:
813 Py_DECREF(nameobj);
814 Py_XDECREF(pathobj);
815 Py_XDECREF(cpathobj);
816 return m;
817}
818
819PyObject*
820PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
821 PyObject *cpathname)
822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 PyObject *modules = PyImport_GetModuleDict();
824 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000825
Victor Stinner27ee0892011-03-04 12:57:09 +0000826 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (m == NULL)
828 return NULL;
829 /* If the module is being reloaded, we get the old module back
830 and re-use its dict to exec the new code. */
831 d = PyModule_GetDict(m);
832 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
833 if (PyDict_SetItemString(d, "__builtins__",
834 PyEval_GetBuiltins()) != 0)
835 goto error;
836 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (pathname != NULL) {
Brett Cannona6473f92012-07-13 13:57:03 -0400838 v = pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
Brett Cannona6473f92012-07-13 13:57:03 -0400840 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 v = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
Brett Cannona6473f92012-07-13 13:57:03 -0400843 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (PyDict_SetItemString(d, "__file__", v) != 0)
845 PyErr_Clear(); /* Not important enough to report */
846 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000849 if (cpathname != NULL)
850 v = cpathname;
851 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (PyDict_SetItemString(d, "__cached__", v) != 0)
854 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000855
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000856 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (v == NULL)
858 goto error;
859 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000860
Victor Stinner27ee0892011-03-04 12:57:09 +0000861 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000863 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 name);
865 return NULL;
866 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000871
872 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 remove_module(name);
874 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000875}
876
877
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000878static void
879update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyObject *constants, *tmp;
882 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (PyUnicode_Compare(co->co_filename, oldname))
885 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 tmp = co->co_filename;
888 co->co_filename = newname;
889 Py_INCREF(co->co_filename);
890 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 constants = co->co_consts;
893 n = PyTuple_GET_SIZE(constants);
894 for (i = 0; i < n; i++) {
895 tmp = PyTuple_GET_ITEM(constants, i);
896 if (PyCode_Check(tmp))
897 update_code_filenames((PyCodeObject *)tmp,
898 oldname, newname);
899 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000900}
901
Victor Stinner2f42ae52011-03-20 00:41:24 +0100902static void
903update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000904{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100905 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000906
Victor Stinner2f42ae52011-03-20 00:41:24 +0100907 if (PyUnicode_Compare(co->co_filename, newname) == 0)
908 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 oldname = co->co_filename;
911 Py_INCREF(oldname);
912 update_code_filenames(co, oldname, newname);
913 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000914}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000915
Brett Cannon4caa61d2014-01-09 19:03:32 -0500916/*[clinic input]
917_imp._fix_co_filename
918
919 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
920 Code object to change.
921
922 path: unicode
923 File path to use.
924 /
925
926Changes code.co_filename to specify the passed-in file path.
927[clinic start generated code]*/
928
929PyDoc_STRVAR(_imp__fix_co_filename__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -0800930"sig=($module, code, path)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500931"Changes code.co_filename to specify the passed-in file path.\n"
932"\n"
933" code\n"
934" Code object to change.\n"
935" path\n"
936" File path to use.");
937
938#define _IMP__FIX_CO_FILENAME_METHODDEF \
939 {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_VARARGS, _imp__fix_co_filename__doc__},
940
Brett Cannon442c9b92011-03-23 16:14:42 -0700941static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500942_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path);
943
944static PyObject *
945_imp__fix_co_filename(PyModuleDef *module, PyObject *args)
Brett Cannon442c9b92011-03-23 16:14:42 -0700946{
Brett Cannon4caa61d2014-01-09 19:03:32 -0500947 PyObject *return_value = NULL;
948 PyCodeObject *code;
949 PyObject *path;
Brett Cannon442c9b92011-03-23 16:14:42 -0700950
Brett Cannon4caa61d2014-01-09 19:03:32 -0500951 if (!PyArg_ParseTuple(args,
952 "O!U:_fix_co_filename",
953 &PyCode_Type, &code, &path))
954 goto exit;
955 return_value = _imp__fix_co_filename_impl(module, code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700956
Brett Cannon4caa61d2014-01-09 19:03:32 -0500957exit:
958 return return_value;
959}
Brett Cannon442c9b92011-03-23 16:14:42 -0700960
Brett Cannon4caa61d2014-01-09 19:03:32 -0500961static PyObject *
962_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Larry Hastings581ee362014-01-28 05:00:08 -0800963/*[clinic end generated code: output=3fe5b5a1b0d497df input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700964
Brett Cannon4caa61d2014-01-09 19:03:32 -0500965{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500966 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700967
968 Py_RETURN_NONE;
969}
970
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000971
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000972/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700973static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000974
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000975
976/* Helper to test for built-in module */
977
978static int
Victor Stinner95872862011-03-07 18:20:56 +0100979is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000980{
Victor Stinner95872862011-03-07 18:20:56 +0100981 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +0100983 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
984 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (PyImport_Inittab[i].initfunc == NULL)
986 return -1;
987 else
988 return 1;
989 }
990 }
991 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000992}
993
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000994
Just van Rossum52e14d62002-12-30 22:08:05 +0000995/* Return an importer object for a sys.path/pkg.__path__ item 'p',
996 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000997 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000998 that can handle the path item. Return None if no hook could;
999 this tells our caller it should fall back to the builtin
1000 import mechanism. Cache the result in path_importer_cache.
1001 Returns a borrowed reference. */
1002
1003static PyObject *
1004get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PyObject *importer;
1008 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* These conditions are the caller's responsibility: */
1011 assert(PyList_Check(path_hooks));
1012 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 nhooks = PyList_Size(path_hooks);
1015 if (nhooks < 0)
1016 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 importer = PyDict_GetItem(path_importer_cache, p);
1019 if (importer != NULL)
1020 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* set path_importer_cache[p] to None to avoid recursion */
1023 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1024 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 for (j = 0; j < nhooks; j++) {
1027 PyObject *hook = PyList_GetItem(path_hooks, j);
1028 if (hook == NULL)
1029 return NULL;
1030 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1031 if (importer != NULL)
1032 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1035 return NULL;
1036 }
1037 PyErr_Clear();
1038 }
1039 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001040 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 }
1042 if (importer != NULL) {
1043 int err = PyDict_SetItem(path_importer_cache, p, importer);
1044 Py_DECREF(importer);
1045 if (err != 0)
1046 return NULL;
1047 }
1048 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001049}
1050
Christian Heimes9cd17752007-11-18 19:35:23 +00001051PyAPI_FUNC(PyObject *)
1052PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001054
Victor Stinner1e53bba2013-07-16 22:26:05 +02001055 path_importer_cache = PySys_GetObject("path_importer_cache");
1056 path_hooks = PySys_GetObject("path_hooks");
1057 if (path_importer_cache != NULL && path_hooks != NULL) {
1058 importer = get_path_importer(path_importer_cache,
1059 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 }
1061 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1062 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001063}
1064
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001065
Victor Stinner95872862011-03-07 18:20:56 +01001066static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001067
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001069 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001070 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001071
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001072static int
Victor Stinner95872862011-03-07 18:20:56 +01001073init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001076 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001077
Victor Stinner5eb4f592013-11-14 22:38:52 +01001078 mod = _PyImport_FindExtensionObject(name, name);
1079 if (PyErr_Occurred())
1080 return -1;
1081 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 for (p = PyImport_Inittab; p->name != NULL; p++) {
1085 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001086 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001087 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (p->initfunc == NULL) {
1089 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001090 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 name);
1092 return -1;
1093 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 mod = (*p->initfunc)();
1095 if (mod == 0)
1096 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001097 /* Remember pointer to module init function. */
1098 def = PyModule_GetDef(mod);
1099 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001100 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 return -1;
1102 /* FixupExtension has put the module into sys.modules,
1103 so we can release our own reference. */
1104 Py_DECREF(mod);
1105 return 1;
1106 }
1107 }
1108 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001109}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001110
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001111
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001112/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001113
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001114static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001115find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001116{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001117 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001118
Victor Stinner53dc7352011-03-20 01:50:21 +01001119 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 for (p = PyImport_FrozenModules; ; p++) {
1123 if (p->name == NULL)
1124 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001125 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 break;
1127 }
1128 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001129}
1130
Guido van Rossum79f25d91997-04-29 20:08:16 +00001131static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001132get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001133{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001134 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (p == NULL) {
1138 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001139 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 name);
1141 return NULL;
1142 }
1143 if (p->code == NULL) {
1144 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001145 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 name);
1147 return NULL;
1148 }
1149 size = p->size;
1150 if (size < 0)
1151 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001152 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001153}
1154
Brett Cannon8d110132009-03-15 02:20:16 +00001155static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001156is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001157{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001158 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (p == NULL) {
1162 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001163 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 name);
1165 return NULL;
1166 }
Brett Cannon8d110132009-03-15 02:20:16 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (size < 0)
1171 Py_RETURN_TRUE;
1172 else
1173 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001174}
1175
1176
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001177/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001178 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001179 an exception set if the initialization failed.
1180 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001181
1182int
Victor Stinner53dc7352011-03-20 01:50:21 +01001183PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001184{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001185 const struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01001186 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 int ispackage;
1188 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001189
Victor Stinner53dc7352011-03-20 01:50:21 +01001190 p = find_frozen(name);
1191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (p == NULL)
1193 return 0;
1194 if (p->code == NULL) {
1195 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001196 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 name);
1198 return -1;
1199 }
1200 size = p->size;
1201 ispackage = (size < 0);
1202 if (ispackage)
1203 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001204 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (co == NULL)
1206 return -1;
1207 if (!PyCode_Check(co)) {
1208 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001209 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 name);
1211 goto err_return;
1212 }
1213 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001214 /* Set __path__ to the empty list */
Victor Stinner53dc7352011-03-20 01:50:21 +01001215 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001217 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 if (m == NULL)
1219 goto err_return;
1220 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001221 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 goto err_return;
1224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 err = PyDict_SetItemString(d, "__path__", l);
1226 Py_DECREF(l);
1227 if (err != 0)
1228 goto err_return;
1229 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001230 path = PyUnicode_FromString("<frozen>");
1231 if (path == NULL)
1232 goto err_return;
1233 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1234 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (m == NULL)
1236 goto err_return;
1237 Py_DECREF(co);
1238 Py_DECREF(m);
1239 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001240err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 Py_DECREF(co);
1242 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001243}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001244
Victor Stinner53dc7352011-03-20 01:50:21 +01001245int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001246PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001247{
1248 PyObject *nameobj;
1249 int ret;
1250 nameobj = PyUnicode_InternFromString(name);
1251 if (nameobj == NULL)
1252 return -1;
1253 ret = PyImport_ImportFrozenModuleObject(nameobj);
1254 Py_DECREF(nameobj);
1255 return ret;
1256}
1257
Guido van Rossum74e6a111994-08-29 12:54:38 +00001258
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001259/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001260 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001261
Guido van Rossum79f25d91997-04-29 20:08:16 +00001262PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001263PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyObject *pname;
1266 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 pname = PyUnicode_FromString(name);
1269 if (pname == NULL)
1270 return NULL;
1271 result = PyImport_Import(pname);
1272 Py_DECREF(pname);
1273 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001274}
1275
Christian Heimes072c0f12008-01-03 23:01:04 +00001276/* Import a module without blocking
1277 *
1278 * At first it tries to fetch the module from sys.modules. If the module was
1279 * never loaded before it loads it with PyImport_ImportModule() unless another
1280 * thread holds the import lock. In the latter case the function raises an
1281 * ImportError instead of blocking.
1282 *
1283 * Returns the module object with incremented ref count.
1284 */
1285PyObject *
1286PyImport_ImportModuleNoBlock(const char *name)
1287{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001288 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001289}
1290
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001291
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001292/* Remove importlib frames from the traceback,
1293 * except in Verbose mode. */
1294static void
1295remove_importlib_frames(void)
1296{
1297 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001298 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001299 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001300 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001301 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001302 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001303
1304 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001305 from the traceback. We always trim chunks
1306 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001307
1308 PyErr_Fetch(&exception, &value, &base_tb);
1309 if (!exception || Py_VerboseFlag)
1310 goto done;
1311 if (PyType_IsSubtype((PyTypeObject *) exception,
1312 (PyTypeObject *) PyExc_ImportError))
1313 always_trim = 1;
1314
1315 prev_link = &base_tb;
1316 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001317 while (tb != NULL) {
1318 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1319 PyObject *next = (PyObject *) traceback->tb_next;
1320 PyFrameObject *frame = traceback->tb_frame;
1321 PyCodeObject *code = frame->f_code;
1322 int now_in_importlib;
1323
1324 assert(PyTraceBack_Check(tb));
1325 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1326 code->co_filename,
1327 importlib_filename) == 0);
1328 if (now_in_importlib && !in_importlib) {
1329 /* This is the link to this chunk of importlib tracebacks */
1330 outer_link = prev_link;
1331 }
1332 in_importlib = now_in_importlib;
1333
1334 if (in_importlib &&
1335 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001336 PyUnicode_CompareWithASCIIString(code->co_name,
1337 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001338 PyObject *tmp = *outer_link;
1339 *outer_link = next;
1340 Py_XINCREF(next);
1341 Py_DECREF(tmp);
1342 prev_link = outer_link;
1343 }
1344 else {
1345 prev_link = (PyObject **) &traceback->tb_next;
1346 }
1347 tb = next;
1348 }
1349done:
1350 PyErr_Restore(exception, value, base_tb);
1351}
1352
1353
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001354PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001355PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1356 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001357 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001358{
Brett Cannonfd074152012-04-14 14:10:13 -04001359 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001360 _Py_IDENTIFIER(__spec__);
1361 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001362 _Py_IDENTIFIER(__package__);
1363 _Py_IDENTIFIER(__path__);
1364 _Py_IDENTIFIER(__name__);
1365 _Py_IDENTIFIER(_find_and_load);
1366 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001367 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001368 _Py_static_string(single_dot, ".");
1369 PyObject *abs_name = NULL;
1370 PyObject *builtins_import = NULL;
1371 PyObject *final_mod = NULL;
1372 PyObject *mod = NULL;
1373 PyObject *package = NULL;
1374 PyObject *globals = NULL;
1375 PyObject *fromlist = NULL;
1376 PyInterpreterState *interp = PyThreadState_GET()->interp;
1377
1378 /* Make sure to use default values so as to not have
1379 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1380 NULL argument. */
1381 if (given_globals == NULL) {
1382 globals = PyDict_New();
1383 if (globals == NULL) {
1384 goto error;
1385 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 }
Brett Cannonfd074152012-04-14 14:10:13 -04001387 else {
1388 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001389 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001390 if (level > 0 && !PyDict_Check(given_globals)) {
1391 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1392 goto error;
1393 }
1394 globals = given_globals;
1395 Py_INCREF(globals);
1396 }
1397
1398 if (given_fromlist == NULL) {
1399 fromlist = PyList_New(0);
1400 if (fromlist == NULL) {
1401 goto error;
1402 }
1403 }
1404 else {
1405 fromlist = given_fromlist;
1406 Py_INCREF(fromlist);
1407 }
1408 if (name == NULL) {
1409 PyErr_SetString(PyExc_ValueError, "Empty module name");
1410 goto error;
1411 }
1412
1413 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1414 for added performance. */
1415
1416 if (!PyUnicode_Check(name)) {
1417 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1418 goto error;
1419 }
1420 else if (PyUnicode_READY(name) < 0) {
1421 goto error;
1422 }
1423 if (level < 0) {
1424 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1425 goto error;
1426 }
1427 else if (level > 0) {
1428 package = _PyDict_GetItemId(globals, &PyId___package__);
1429 if (package != NULL && package != Py_None) {
1430 Py_INCREF(package);
1431 if (!PyUnicode_Check(package)) {
1432 PyErr_SetString(PyExc_TypeError, "package must be a string");
1433 goto error;
1434 }
1435 }
1436 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001437 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001438 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001439 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001440 goto error;
1441 }
1442 else if (!PyUnicode_Check(package)) {
1443 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1444 }
1445 Py_INCREF(package);
1446
1447 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001448 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001449 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1450 if (borrowed_dot == NULL) {
1451 goto error;
1452 }
Brett Cannon740fce02012-04-14 14:23:49 -04001453 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001454 Py_DECREF(package);
1455 if (partition == NULL) {
1456 goto error;
1457 }
1458 package = PyTuple_GET_ITEM(partition, 0);
1459 Py_INCREF(package);
1460 Py_DECREF(partition);
1461 }
1462 }
1463
1464 if (PyDict_GetItem(interp->modules, package) == NULL) {
1465 PyErr_Format(PyExc_SystemError,
1466 "Parent module %R not loaded, cannot perform relative "
1467 "import", package);
1468 goto error;
1469 }
1470 }
1471 else { /* level == 0 */
1472 if (PyUnicode_GET_LENGTH(name) == 0) {
1473 PyErr_SetString(PyExc_ValueError, "Empty module name");
1474 goto error;
1475 }
1476 package = Py_None;
1477 Py_INCREF(package);
1478 }
1479
1480 if (level > 0) {
1481 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1482 PyObject *base = NULL;
1483 int level_up = 1;
1484
1485 for (level_up = 1; level_up < level; level_up += 1) {
1486 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1487 if (last_dot == -2) {
1488 goto error;
1489 }
1490 else if (last_dot == -1) {
1491 PyErr_SetString(PyExc_ValueError,
1492 "attempted relative import beyond top-level "
1493 "package");
1494 goto error;
1495 }
1496 }
Victor Stinner22af2592013-11-13 12:11:36 +01001497
Brett Cannonfd074152012-04-14 14:10:13 -04001498 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001499 if (base == NULL)
1500 goto error;
1501
Brett Cannonfd074152012-04-14 14:10:13 -04001502 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001503 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001504
1505 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001506 seq = PyTuple_Pack(2, base, name);
1507 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001508 if (borrowed_dot == NULL || seq == NULL) {
1509 goto error;
1510 }
1511
1512 abs_name = PyUnicode_Join(borrowed_dot, seq);
1513 Py_DECREF(seq);
1514 if (abs_name == NULL) {
1515 goto error;
1516 }
1517 }
1518 else {
1519 abs_name = base;
1520 }
1521 }
1522 else {
1523 abs_name = name;
1524 Py_INCREF(abs_name);
1525 }
1526
Brian Curtine6b299f2012-04-14 14:19:33 -05001527#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001528 _PyImport_AcquireLock();
1529#endif
1530 /* From this point forward, goto error_with_unlock! */
1531 if (PyDict_Check(globals)) {
1532 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1533 }
1534 if (builtins_import == NULL) {
1535 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1536 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001537 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1538 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001539 }
1540 }
1541 Py_INCREF(builtins_import);
1542
1543 mod = PyDict_GetItem(interp->modules, abs_name);
1544 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001545 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1546 "None in sys.modules", abs_name);
1547 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001548 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001549 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001550 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001551 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001552 goto error_with_unlock;
1553 }
1554 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001555 PyObject *value = NULL;
1556 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001557 int initializing = 0;
1558
Brett Cannonfd074152012-04-14 14:10:13 -04001559 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001560 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001561 __spec__._initializing is true.
1562 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001563 stuffing the new module in sys.modules.
1564 */
Eric Snowb523f842013-11-22 09:05:39 -07001565 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1566 if (spec != NULL) {
1567 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1568 Py_DECREF(spec);
1569 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001570 if (value == NULL)
1571 PyErr_Clear();
1572 else {
1573 initializing = PyObject_IsTrue(value);
1574 Py_DECREF(value);
1575 if (initializing == -1)
1576 PyErr_Clear();
1577 }
1578 if (initializing > 0) {
1579 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001580 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001581 &PyId__lock_unlock_module, abs_name,
1582 NULL);
1583 if (value == NULL)
1584 goto error;
1585 Py_DECREF(value);
1586 }
1587 else {
1588#ifdef WITH_THREAD
1589 if (_PyImport_ReleaseLock() < 0) {
1590 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1591 goto error;
1592 }
1593#endif
1594 }
Brett Cannonfd074152012-04-14 14:10:13 -04001595 }
1596 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001597 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001598 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001599 &PyId__find_and_load, abs_name,
1600 builtins_import, NULL);
1601 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001602 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001603 }
1604 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001605 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001606
1607 if (PyObject_Not(fromlist)) {
1608 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1609 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001610 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001611 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1612
1613 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001614 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001615 }
1616
Brian Curtine6b299f2012-04-14 14:19:33 -05001617 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001618 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001619 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001620 }
1621
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001622 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1623 /* No dot in module name, simple exit */
1624 Py_DECREF(partition);
1625 final_mod = mod;
1626 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001627 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001628 }
1629
Brett Cannonfd074152012-04-14 14:10:13 -04001630 front = PyTuple_GET_ITEM(partition, 0);
1631 Py_INCREF(front);
1632 Py_DECREF(partition);
1633
1634 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001635 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001636 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001637 }
1638 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001639 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1640 PyUnicode_GET_LENGTH(front);
1641 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001642 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001643 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001644 Py_DECREF(front);
1645 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001646 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001647 }
Brett Cannonfd074152012-04-14 14:10:13 -04001648
1649 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001650 if (final_mod == NULL) {
1651 PyErr_Format(PyExc_KeyError,
1652 "%R not in sys.modules as expected",
1653 to_return);
1654 }
1655 else {
1656 Py_INCREF(final_mod);
1657 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001658 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001659 }
1660 }
1661 else {
1662 final_mod = mod;
1663 Py_INCREF(mod);
1664 }
1665 }
1666 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001667 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001668 &PyId__handle_fromlist, mod,
1669 fromlist, builtins_import,
1670 NULL);
1671 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001672 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001673
Brett Cannonfd074152012-04-14 14:10:13 -04001674 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001675#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001676 if (_PyImport_ReleaseLock() < 0) {
1677 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1678 }
1679#endif
1680 error:
1681 Py_XDECREF(abs_name);
1682 Py_XDECREF(builtins_import);
1683 Py_XDECREF(mod);
1684 Py_XDECREF(package);
1685 Py_XDECREF(globals);
1686 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001687 if (final_mod == NULL)
1688 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001689 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001690}
1691
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001692PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001693PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001694 PyObject *fromlist, int level)
1695{
1696 PyObject *nameobj, *mod;
1697 nameobj = PyUnicode_FromString(name);
1698 if (nameobj == NULL)
1699 return NULL;
1700 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1701 fromlist, level);
1702 Py_DECREF(nameobj);
1703 return mod;
1704}
1705
1706
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001707/* Re-import a module of any kind and return its module object, WITH
1708 INCREMENTED REFERENCE COUNT */
1709
Guido van Rossum79f25d91997-04-29 20:08:16 +00001710PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001711PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001712{
Brett Cannon62228db2012-04-29 14:38:11 -04001713 _Py_IDENTIFIER(reload);
1714 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001716 PyObject *imp = PyDict_GetItemString(modules, "imp");
1717 if (imp == NULL) {
1718 imp = PyImport_ImportModule("imp");
1719 if (imp == NULL) {
1720 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 }
Brett Cannon62228db2012-04-29 14:38:11 -04001723 else {
1724 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001726
Brett Cannon62228db2012-04-29 14:38:11 -04001727 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1728 Py_DECREF(imp);
1729 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001730}
1731
1732
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001733/* Higher-level import emulator which emulates the "import" statement
1734 more accurately -- it invokes the __import__() function from the
1735 builtins of the current globals. This means that the import is
1736 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001737 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001738 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001739 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001740 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001741
1742PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001743PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 static PyObject *silly_list = NULL;
1746 static PyObject *builtins_str = NULL;
1747 static PyObject *import_str = NULL;
1748 PyObject *globals = NULL;
1749 PyObject *import = NULL;
1750 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001751 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* Initialize constant string objects */
1755 if (silly_list == NULL) {
1756 import_str = PyUnicode_InternFromString("__import__");
1757 if (import_str == NULL)
1758 return NULL;
1759 builtins_str = PyUnicode_InternFromString("__builtins__");
1760 if (builtins_str == NULL)
1761 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001762 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (silly_list == NULL)
1764 return NULL;
1765 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 /* Get the builtins from current globals */
1768 globals = PyEval_GetGlobals();
1769 if (globals != NULL) {
1770 Py_INCREF(globals);
1771 builtins = PyObject_GetItem(globals, builtins_str);
1772 if (builtins == NULL)
1773 goto err;
1774 }
1775 else {
1776 /* No globals -- use standard builtins, and fake globals */
1777 builtins = PyImport_ImportModuleLevel("builtins",
1778 NULL, NULL, NULL, 0);
1779 if (builtins == NULL)
1780 return NULL;
1781 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1782 if (globals == NULL)
1783 goto err;
1784 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 /* Get the __import__ function from the builtins */
1787 if (PyDict_Check(builtins)) {
1788 import = PyObject_GetItem(builtins, import_str);
1789 if (import == NULL)
1790 PyErr_SetObject(PyExc_KeyError, import_str);
1791 }
1792 else
1793 import = PyObject_GetAttr(builtins, import_str);
1794 if (import == NULL)
1795 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001798 Always use absolute import here.
1799 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1801 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001802 if (r == NULL)
1803 goto err;
1804 Py_DECREF(r);
1805
1806 modules = PyImport_GetModuleDict();
1807 r = PyDict_GetItem(modules, module_name);
1808 if (r != NULL)
1809 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001810
1811 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 Py_XDECREF(globals);
1813 Py_XDECREF(builtins);
1814 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001817}
1818
Brett Cannon4caa61d2014-01-09 19:03:32 -05001819/*[clinic input]
1820_imp.extension_suffixes
1821
1822Returns the list of file suffixes used to identify extension modules.
1823[clinic start generated code]*/
1824
1825PyDoc_STRVAR(_imp_extension_suffixes__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08001826"sig=($module)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001827"Returns the list of file suffixes used to identify extension modules.");
1828
1829#define _IMP_EXTENSION_SUFFIXES_METHODDEF \
1830 {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
1831
Barry Warsaw28a691b2010-04-17 00:19:56 +00001832static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001833_imp_extension_suffixes_impl(PyModuleDef *module);
1834
1835static PyObject *
1836_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1837{
Larry Hastingsbebf7352014-01-17 17:47:17 -08001838 return _imp_extension_suffixes_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001839}
1840
1841static PyObject *
1842_imp_extension_suffixes_impl(PyModuleDef *module)
Larry Hastings581ee362014-01-28 05:00:08 -08001843/*[clinic end generated code: output=c1bcfbddabefa00a input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001846 const char *suffix;
1847 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 list = PyList_New(0);
1850 if (list == NULL)
1851 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001852#ifdef HAVE_DYNAMIC_LOADING
1853 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1854 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (item == NULL) {
1856 Py_DECREF(list);
1857 return NULL;
1858 }
1859 if (PyList_Append(list, item) < 0) {
1860 Py_DECREF(list);
1861 Py_DECREF(item);
1862 return NULL;
1863 }
1864 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001865 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 }
Brett Cannon2657df42012-05-04 15:20:40 -04001867#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001869}
1870
Brett Cannon4caa61d2014-01-09 19:03:32 -05001871/*[clinic input]
1872_imp.init_builtin
1873
1874 name: unicode
1875 /
1876
1877Initializes a built-in module.
1878[clinic start generated code]*/
1879
1880PyDoc_STRVAR(_imp_init_builtin__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08001881"sig=($module, name)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001882"Initializes a built-in module.");
1883
1884#define _IMP_INIT_BUILTIN_METHODDEF \
1885 {"init_builtin", (PyCFunction)_imp_init_builtin, METH_VARARGS, _imp_init_builtin__doc__},
1886
Guido van Rossum79f25d91997-04-29 20:08:16 +00001887static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001888_imp_init_builtin_impl(PyModuleDef *module, PyObject *name);
1889
1890static PyObject *
1891_imp_init_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001892{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001893 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01001894 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001895
1896 if (!PyArg_ParseTuple(args,
1897 "U:init_builtin",
1898 &name))
1899 goto exit;
1900 return_value = _imp_init_builtin_impl(module, name);
1901
1902exit:
1903 return return_value;
1904}
1905
1906static PyObject *
1907_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings581ee362014-01-28 05:00:08 -08001908/*[clinic end generated code: output=02437efd4668f53e input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 int ret;
1911 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 ret = init_builtin(name);
1914 if (ret < 0)
1915 return NULL;
1916 if (ret == 0) {
1917 Py_INCREF(Py_None);
1918 return Py_None;
1919 }
Victor Stinner95872862011-03-07 18:20:56 +01001920 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 Py_XINCREF(m);
1922 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001923}
1924
Brett Cannon4caa61d2014-01-09 19:03:32 -05001925/*[clinic input]
1926_imp.init_frozen
1927
1928 name: unicode
1929 /
1930
1931Initializes a frozen module.
1932[clinic start generated code]*/
1933
1934PyDoc_STRVAR(_imp_init_frozen__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08001935"sig=($module, name)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001936"Initializes a frozen module.");
1937
1938#define _IMP_INIT_FROZEN_METHODDEF \
1939 {"init_frozen", (PyCFunction)_imp_init_frozen, METH_VARARGS, _imp_init_frozen__doc__},
1940
Guido van Rossum79f25d91997-04-29 20:08:16 +00001941static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001942_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
1943
1944static PyObject *
1945_imp_init_frozen(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001946{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001947 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001948 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001949
1950 if (!PyArg_ParseTuple(args,
1951 "U:init_frozen",
1952 &name))
1953 goto exit;
1954 return_value = _imp_init_frozen_impl(module, name);
1955
1956exit:
1957 return return_value;
1958}
1959
1960static PyObject *
1961_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings581ee362014-01-28 05:00:08 -08001962/*[clinic end generated code: output=20cea421af513afe input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 int ret;
1965 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001966
Victor Stinner53dc7352011-03-20 01:50:21 +01001967 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 if (ret < 0)
1969 return NULL;
1970 if (ret == 0) {
1971 Py_INCREF(Py_None);
1972 return Py_None;
1973 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001974 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 Py_XINCREF(m);
1976 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001977}
1978
Brett Cannon4caa61d2014-01-09 19:03:32 -05001979/*[clinic input]
1980_imp.get_frozen_object
1981
1982 name: unicode
1983 /
1984
1985Create a code object for a frozen module.
1986[clinic start generated code]*/
1987
1988PyDoc_STRVAR(_imp_get_frozen_object__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08001989"sig=($module, name)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990"Create a code object for a frozen module.");
1991
1992#define _IMP_GET_FROZEN_OBJECT_METHODDEF \
1993 {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_VARARGS, _imp_get_frozen_object__doc__},
1994
Guido van Rossum79f25d91997-04-29 20:08:16 +00001995static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001996_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
1997
1998static PyObject *
1999_imp_get_frozen_object(PyModuleDef *module, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002000{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002001 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002002 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002003
Brett Cannon4caa61d2014-01-09 19:03:32 -05002004 if (!PyArg_ParseTuple(args,
2005 "U:get_frozen_object",
2006 &name))
2007 goto exit;
2008 return_value = _imp_get_frozen_object_impl(module, name);
2009
2010exit:
2011 return return_value;
2012}
2013
2014static PyObject *
2015_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Larry Hastings581ee362014-01-28 05:00:08 -08002016/*[clinic end generated code: output=f00d01ae30ec842f input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002019}
2020
Brett Cannon4caa61d2014-01-09 19:03:32 -05002021/*[clinic input]
2022_imp.is_frozen_package
2023
2024 name: unicode
2025 /
2026
2027Returns True if the module name is of a frozen package.
2028[clinic start generated code]*/
2029
2030PyDoc_STRVAR(_imp_is_frozen_package__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08002031"sig=($module, name)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002032"Returns True if the module name is of a frozen package.");
2033
2034#define _IMP_IS_FROZEN_PACKAGE_METHODDEF \
2035 {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_VARARGS, _imp_is_frozen_package__doc__},
2036
Guido van Rossum79f25d91997-04-29 20:08:16 +00002037static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002038_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
2039
2040static PyObject *
2041_imp_is_frozen_package(PyModuleDef *module, PyObject *args)
Brett Cannon8d110132009-03-15 02:20:16 +00002042{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002043 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002044 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002045
Brett Cannon4caa61d2014-01-09 19:03:32 -05002046 if (!PyArg_ParseTuple(args,
2047 "U:is_frozen_package",
2048 &name))
2049 goto exit;
2050 return_value = _imp_is_frozen_package_impl(module, name);
2051
2052exit:
2053 return return_value;
2054}
2055
2056static PyObject *
2057_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Larry Hastings581ee362014-01-28 05:00:08 -08002058/*[clinic end generated code: output=35c78f2448c6fcff input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002061}
2062
Brett Cannon4caa61d2014-01-09 19:03:32 -05002063/*[clinic input]
2064_imp.is_builtin
2065
2066 name: unicode
2067 /
2068
2069Returns True if the module name corresponds to a built-in module.
2070[clinic start generated code]*/
2071
2072PyDoc_STRVAR(_imp_is_builtin__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08002073"sig=($module, name)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002074"Returns True if the module name corresponds to a built-in module.");
2075
2076#define _IMP_IS_BUILTIN_METHODDEF \
2077 {"is_builtin", (PyCFunction)_imp_is_builtin, METH_VARARGS, _imp_is_builtin__doc__},
2078
Brett Cannon8d110132009-03-15 02:20:16 +00002079static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002080_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
2081
2082static PyObject *
2083_imp_is_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002084{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002085 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01002086 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002087
2088 if (!PyArg_ParseTuple(args,
2089 "U:is_builtin",
2090 &name))
2091 goto exit;
2092 return_value = _imp_is_builtin_impl(module, name);
2093
2094exit:
2095 return return_value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002096}
2097
Guido van Rossum79f25d91997-04-29 20:08:16 +00002098static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002099_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings581ee362014-01-28 05:00:08 -08002100/*[clinic end generated code: output=641689f833347f66 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002101{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002102 return PyLong_FromLong(is_builtin(name));
2103}
2104
2105/*[clinic input]
2106_imp.is_frozen
2107
2108 name: unicode
2109 /
2110
2111Returns True if the module name corresponds to a frozen module.
2112[clinic start generated code]*/
2113
2114PyDoc_STRVAR(_imp_is_frozen__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08002115"sig=($module, name)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002116"Returns True if the module name corresponds to a frozen module.");
2117
2118#define _IMP_IS_FROZEN_METHODDEF \
2119 {"is_frozen", (PyCFunction)_imp_is_frozen, METH_VARARGS, _imp_is_frozen__doc__},
2120
2121static PyObject *
2122_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
2123
2124static PyObject *
2125_imp_is_frozen(PyModuleDef *module, PyObject *args)
2126{
2127 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002128 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002129
2130 if (!PyArg_ParseTuple(args,
2131 "U:is_frozen",
2132 &name))
2133 goto exit;
2134 return_value = _imp_is_frozen_impl(module, name);
2135
2136exit:
2137 return return_value;
2138}
2139
2140static PyObject *
2141_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings581ee362014-01-28 05:00:08 -08002142/*[clinic end generated code: output=0f80c7a3f283a686 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002143{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002144 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 p = find_frozen(name);
2147 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002148}
2149
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002150#ifdef HAVE_DYNAMIC_LOADING
2151
Brett Cannon4caa61d2014-01-09 19:03:32 -05002152/*[clinic input]
2153_imp.load_dynamic
2154
2155 name: unicode
2156 path: fs_unicode
2157 file: object = NULL
2158 /
2159
2160Loads an extension module.
2161[clinic start generated code]*/
2162
2163PyDoc_STRVAR(_imp_load_dynamic__doc__,
Larry Hastings581ee362014-01-28 05:00:08 -08002164"sig=($module, name, path, file=None)\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002165"Loads an extension module.");
2166
2167#define _IMP_LOAD_DYNAMIC_METHODDEF \
2168 {"load_dynamic", (PyCFunction)_imp_load_dynamic, METH_VARARGS, _imp_load_dynamic__doc__},
2169
Guido van Rossum79f25d91997-04-29 20:08:16 +00002170static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002171_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file);
2172
2173static PyObject *
2174_imp_load_dynamic(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002175{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002176 PyObject *return_value = NULL;
2177 PyObject *name;
2178 PyObject *path;
2179 PyObject *file = NULL;
2180
2181 if (!PyArg_ParseTuple(args,
2182 "UO&|O:load_dynamic",
2183 &name, PyUnicode_FSDecoder, &path, &file))
2184 goto exit;
2185 return_value = _imp_load_dynamic_impl(module, name, path, file);
2186
2187exit:
2188 return return_value;
2189}
2190
2191static PyObject *
2192_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Larry Hastings581ee362014-01-28 05:00:08 -08002193/*[clinic end generated code: output=8f33f48dc6252948 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002194{
2195 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002196 FILE *fp;
2197
Brett Cannon4caa61d2014-01-09 19:03:32 -05002198 if (file != NULL) {
2199 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002200 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002201 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002202 if (!PyErr_Occurred())
2203 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002205 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002207 else
2208 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002209 mod = _PyImport_LoadDynamicModule(name, path, fp);
2210 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (fp)
2212 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002213 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002214}
2215
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002216#endif /* HAVE_DYNAMIC_LOADING */
2217
Larry Hastings7726ac92014-01-31 22:03:12 -08002218/*[clinic input]
2219dump buffer
2220[clinic start generated code]*/
2221
2222#ifndef _IMP_LOAD_DYNAMIC_METHODDEF
2223 #define _IMP_LOAD_DYNAMIC_METHODDEF
2224#endif /* !defined(_IMP_LOAD_DYNAMIC_METHODDEF) */
2225/*[clinic end generated code: output=d07c1d4a343a9579 input=524ce2e021e4eba6]*/
2226
Barry Warsaw28a691b2010-04-17 00:19:56 +00002227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002228PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002229"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002230
Guido van Rossum79f25d91997-04-29 20:08:16 +00002231static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002232 _IMP_EXTENSION_SUFFIXES_METHODDEF
2233 _IMP_LOCK_HELD_METHODDEF
2234 _IMP_ACQUIRE_LOCK_METHODDEF
2235 _IMP_RELEASE_LOCK_METHODDEF
2236 _IMP_GET_FROZEN_OBJECT_METHODDEF
2237 _IMP_IS_FROZEN_PACKAGE_METHODDEF
2238 _IMP_INIT_BUILTIN_METHODDEF
2239 _IMP_INIT_FROZEN_METHODDEF
2240 _IMP_IS_BUILTIN_METHODDEF
2241 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002242 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002243 _IMP__FIX_CO_FILENAME_METHODDEF
2244 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002245};
2246
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002247
Martin v. Löwis1a214512008-06-11 05:26:20 +00002248static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002250 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 doc_imp,
2252 0,
2253 imp_methods,
2254 NULL,
2255 NULL,
2256 NULL,
2257 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002258};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002259
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002260PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002261PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 m = PyModule_Create(&impmodule);
2266 if (m == NULL)
2267 goto failure;
2268 d = PyModule_GetDict(m);
2269 if (d == NULL)
2270 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002273 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 Py_XDECREF(m);
2275 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002276}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002277
2278
Guido van Rossumb18618d2000-05-03 23:44:39 +00002279/* API for embedding applications that want to add their own entries
2280 to the table of built-in modules. This should normally be called
2281 *before* Py_Initialize(). When the table resize fails, -1 is
2282 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002283
2284 After a similar function by Just van Rossum. */
2285
2286int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002287PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 static struct _inittab *our_copy = NULL;
2290 struct _inittab *p;
2291 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 /* Count the number of entries in both tables */
2294 for (n = 0; newtab[n].name != NULL; n++)
2295 ;
2296 if (n == 0)
2297 return 0; /* Nothing to do */
2298 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2299 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* Allocate new memory for the combined table */
2302 p = our_copy;
2303 PyMem_RESIZE(p, struct _inittab, i+n+1);
2304 if (p == NULL)
2305 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Copy the tables into the new memory */
2308 if (our_copy != PyImport_Inittab)
2309 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2310 PyImport_Inittab = our_copy = p;
2311 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002314}
2315
2316/* Shorthand to add a single entry given a name and a function */
2317
2318int
Brett Cannona826f322009-04-02 03:41:46 +00002319PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 newtab[0].name = (char *)name;
2326 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002329}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002330
2331#ifdef __cplusplus
2332}
2333#endif
Larry Hastings7726ac92014-01-31 22:03:12 -08002334