blob: 4c8f67f49934c7e6551789d78db4a5e2e7db2c70 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020011#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000014
Guido van Rossum55a83382000-09-20 20:31:38 +000015#ifdef HAVE_FCNTL_H
16#include <fcntl.h>
17#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000019extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000021
Barry Warsaw28a691b2010-04-17 00:19:56 +000022#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000023
Victor Stinner95872862011-03-07 18:20:56 +010024/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000025static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Guido van Rossum771c6c81997-10-31 18:37:24 +000027/* This table is defined in config.c: */
28extern struct _inittab _PyImport_Inittab[];
29
30struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000031
Victor Stinnerd0296212011-03-14 14:04:10 -040032static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033
Brett Cannon4caa61d2014-01-09 19:03:32 -050034/*[clinic input]
35module _imp
36[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080037/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050038
39/*[python input]
40class fs_unicode_converter(CConverter):
41 type = 'PyObject *'
42 converter = 'PyUnicode_FSDecoder'
43
44[python start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080045/*[python end generated code: output=da39a3ee5e6b4b0d input=9d6786230166006e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050046
Guido van Rossum1ae940a1995-01-02 19:04:15 +000047/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000048
49void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000050_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020052 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040053 initstr = PyUnicode_InternFromString("__init__");
54 if (initstr == NULL)
55 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020056 interp->builtins_copy = PyDict_Copy(interp->builtins);
57 if (interp->builtins_copy == NULL)
58 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059}
60
Guido van Rossum25ce5661997-08-02 03:10:38 +000061void
Just van Rossum52e14d62002-12-30 22:08:05 +000062_PyImportHooks_Init(void)
63{
Brett Cannonfd074152012-04-14 14:10:13 -040064 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000066
Brett Cannonfd074152012-04-14 14:10:13 -040067 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 v = PyList_New(0);
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("meta_path", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 v = PyDict_New();
76 if (v == NULL)
77 goto error;
78 err = PySys_SetObject("path_importer_cache", v);
79 Py_DECREF(v);
80 if (err)
81 goto error;
82 path_hooks = PyList_New(0);
83 if (path_hooks == NULL)
84 goto error;
85 err = PySys_SetObject("path_hooks", path_hooks);
86 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000087 error:
Brett Cannonfd074152012-04-14 14:10:13 -040088 PyErr_Print();
89 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020090 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
Brett Cannonfd074152012-04-14 14:10:13 -040092 Py_DECREF(path_hooks);
93}
94
95void
96_PyImportZip_Init(void)
97{
98 PyObject *path_hooks, *zimpimport;
99 int err = 0;
100
101 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200102 if (path_hooks == NULL) {
103 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400104 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200105 }
Brett Cannonfd074152012-04-14 14:10:13 -0400106
107 if (Py_VerboseFlag)
108 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 zimpimport = PyImport_ImportModule("zipimport");
111 if (zimpimport == NULL) {
112 PyErr_Clear(); /* No zip import module -- okay */
113 if (Py_VerboseFlag)
114 PySys_WriteStderr("# can't import zipimport\n");
115 }
116 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200117 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200118 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
119 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 Py_DECREF(zimpimport);
121 if (zipimporter == NULL) {
122 PyErr_Clear(); /* No zipimporter object -- okay */
123 if (Py_VerboseFlag)
124 PySys_WriteStderr(
125 "# can't import zipimport.zipimporter\n");
126 }
127 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400128 /* sys.path_hooks.insert(0, zipimporter) */
129 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400131 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (Py_VerboseFlag)
135 PySys_WriteStderr(
136 "# installed zipimport hook\n");
137 }
138 }
Brett Cannonfd074152012-04-14 14:10:13 -0400139
140 return;
141
142 error:
143 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400144 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000145}
146
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147/* Locking primitives to prevent parallel imports of the same module
148 in different threads to return with a partially loaded module.
149 These calls are serialized by the global interpreter lock. */
150
151#ifdef WITH_THREAD
152
Guido van Rossum49b56061998-10-01 20:42:43 +0000153#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154
Guido van Rossum65d5b571998-12-21 19:32:43 +0000155static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156static long import_lock_thread = -1;
157static int import_lock_level = 0;
158
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000159void
160_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 long me = PyThread_get_thread_ident();
163 if (me == -1)
164 return; /* Too bad */
165 if (import_lock == NULL) {
166 import_lock = PyThread_allocate_lock();
167 if (import_lock == NULL)
168 return; /* Nothing much we can do. */
169 }
170 if (import_lock_thread == me) {
171 import_lock_level++;
172 return;
173 }
174 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
175 {
176 PyThreadState *tstate = PyEval_SaveThread();
177 PyThread_acquire_lock(import_lock, 1);
178 PyEval_RestoreThread(tstate);
179 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100180 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 import_lock_thread = me;
182 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000183}
184
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000185int
186_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 long me = PyThread_get_thread_ident();
189 if (me == -1 || import_lock == NULL)
190 return 0; /* Too bad */
191 if (import_lock_thread != me)
192 return -1;
193 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100194 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (import_lock_level == 0) {
196 import_lock_thread = -1;
197 PyThread_release_lock(import_lock);
198 }
199 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000200}
201
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000202/* This function is called from PyOS_AfterFork to ensure that newly
203 created child processes do not share locks with the parent.
204 We now acquire the import lock around fork() calls but on some platforms
205 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000206
207void
208_PyImport_ReInitLock(void)
209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (import_lock != NULL)
211 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000212 if (import_lock_level > 1) {
213 /* Forked as a side effect of import */
214 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500215 /* The following could fail if the lock is already held, but forking as
216 a side-effect of an import is a) rare, b) nuts, and c) difficult to
217 do thanks to the lock only being held when doing individual module
218 locks per import. */
219 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000220 import_lock_thread = me;
221 import_lock_level--;
222 } else {
223 import_lock_thread = -1;
224 import_lock_level = 0;
225 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000226}
227
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000228#endif
229
Brett Cannon4caa61d2014-01-09 19:03:32 -0500230/*[clinic input]
231_imp.lock_held
232
233Return True if the import lock is currently held, else False.
234
235On platforms without threads, return False.
236[clinic start generated code]*/
237
238PyDoc_STRVAR(_imp_lock_held__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800239"lock_held($module, /)\n"
240"--\n"
241"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500242"Return True if the import lock is currently held, else False.\n"
243"\n"
244"On platforms without threads, return False.");
245
246#define _IMP_LOCK_HELD_METHODDEF \
247 {"lock_held", (PyCFunction)_imp_lock_held, METH_NOARGS, _imp_lock_held__doc__},
248
Tim Peters69232342001-08-30 05:16:13 +0000249static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500250_imp_lock_held_impl(PyModuleDef *module);
251
252static PyObject *
253_imp_lock_held(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
254{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800255 return _imp_lock_held_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500256}
257
258static PyObject *
259_imp_lock_held_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800260/*[clinic end generated code: output=dae65674966baa65 input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000261{
Tim Peters69232342001-08-30 05:16:13 +0000262#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000264#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000266#endif
267}
268
Brett Cannon4caa61d2014-01-09 19:03:32 -0500269/*[clinic input]
270_imp.acquire_lock
271
272Acquires the interpreter's import lock for the current thread.
273
274This lock should be used by import hooks to ensure thread-safety when importing
275modules. On platforms without threads, this function does nothing.
276[clinic start generated code]*/
277
278PyDoc_STRVAR(_imp_acquire_lock__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800279"acquire_lock($module, /)\n"
280"--\n"
281"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500282"Acquires the interpreter\'s import lock for the current thread.\n"
283"\n"
284"This lock should be used by import hooks to ensure thread-safety when importing\n"
285"modules. On platforms without threads, this function does nothing.");
286
287#define _IMP_ACQUIRE_LOCK_METHODDEF \
288 {"acquire_lock", (PyCFunction)_imp_acquire_lock, METH_NOARGS, _imp_acquire_lock__doc__},
289
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000290static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500291_imp_acquire_lock_impl(PyModuleDef *module);
292
293static PyObject *
294_imp_acquire_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
295{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800296 return _imp_acquire_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500297}
298
299static PyObject *
300_imp_acquire_lock_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800301/*[clinic end generated code: output=478f1fa089fdb9a4 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000302{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000303#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000305#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 Py_INCREF(Py_None);
307 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000308}
309
Brett Cannon4caa61d2014-01-09 19:03:32 -0500310/*[clinic input]
311_imp.release_lock
312
313Release the interpreter's import lock.
314
315On platforms without threads, this function does nothing.
316[clinic start generated code]*/
317
318PyDoc_STRVAR(_imp_release_lock__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800319"release_lock($module, /)\n"
320"--\n"
321"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500322"Release the interpreter\'s import lock.\n"
323"\n"
324"On platforms without threads, this function does nothing.");
325
326#define _IMP_RELEASE_LOCK_METHODDEF \
327 {"release_lock", (PyCFunction)_imp_release_lock, METH_NOARGS, _imp_release_lock__doc__},
328
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000329static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500330_imp_release_lock_impl(PyModuleDef *module);
331
332static PyObject *
333_imp_release_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
334{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800335 return _imp_release_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500336}
337
338static PyObject *
339_imp_release_lock_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800340/*[clinic end generated code: output=36c77a6832fdafd4 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000341{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000342#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (_PyImport_ReleaseLock() < 0) {
344 PyErr_SetString(PyExc_RuntimeError,
345 "not holding the import lock");
346 return NULL;
347 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Py_INCREF(Py_None);
350 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000351}
352
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100353void
354_PyImport_Fini(void)
355{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200356 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100357#ifdef WITH_THREAD
358 if (import_lock != NULL) {
359 PyThread_free_lock(import_lock);
360 import_lock = NULL;
361 }
362#endif
363}
364
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365/* Helper for sys */
366
367PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000368PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyInterpreterState *interp = PyThreadState_GET()->interp;
371 if (interp->modules == NULL)
372 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
373 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374}
375
Guido van Rossum3f5da241990-12-20 15:06:42 +0000376
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000377/* List of names to clear in sys */
378static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 "path", "argv", "ps1", "ps2",
380 "last_type", "last_value", "last_traceback",
381 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200382 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 /* misc stuff */
384 "flags", "float_info",
385 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000386};
387
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000388static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 "stdin", "__stdin__",
390 "stdout", "__stdout__",
391 "stderr", "__stderr__",
392 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000393};
394
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000395/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000398PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000399{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200400 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject *key, *value, *dict;
402 PyInterpreterState *interp = PyThreadState_GET()->interp;
403 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200404 PyObject *weaklist = NULL;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200405 char **p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (modules == NULL)
408 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* Delete some special variables first. These are common
411 places where user values hide and people complain when their
412 destructors fail. Since the modules containing them are
413 deleted *last* of all, they would come too late in the normal
414 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000415
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200416 /* XXX Perhaps these precautions are obsolete. Who knows? */
417
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200418 if (Py_VerboseFlag)
419 PySys_WriteStderr("# clear builtins._\n");
420 PyDict_SetItemString(interp->builtins, "_", Py_None);
421
422 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200424 PySys_WriteStderr("# clear sys.%s\n", *p);
425 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200427 for (p = sys_files; *p != NULL; p+=2) {
428 if (Py_VerboseFlag)
429 PySys_WriteStderr("# restore sys.%s\n", *p);
430 value = PyDict_GetItemString(interp->sysdict, *(p+1));
431 if (value == NULL)
432 value = Py_None;
433 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200436 /* We prepare a list which will receive (name, weakref) tuples of
437 modules when they are removed from sys.modules. The name is used
438 for diagnosis messages (in verbose mode), while the weakref helps
439 detect those modules which have been held alive. */
440 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200441 if (weaklist == NULL)
442 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200443
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200444#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200445 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200446 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
447 if (name && wr) { \
448 PyObject *tup = PyTuple_Pack(2, name, wr); \
449 PyList_Append(weaklist, tup); \
450 Py_XDECREF(tup); \
451 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200452 Py_XDECREF(wr); \
453 if (PyErr_Occurred()) \
454 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 }
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);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200471 /* Restore the original builtins dict, to ensure that any
472 user data gets cleared. */
473 dict = PyDict_Copy(interp->builtins);
474 if (dict == NULL)
475 PyErr_Clear();
476 PyDict_Clear(interp->builtins);
477 if (PyDict_Update(interp->builtins, interp->builtins_copy))
478 PyErr_Clear();
479 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200480 /* Clear module dict copies stored in the interpreter state */
481 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200482 /* Collect references */
483 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200484 /* Dump GC stats before it's too late, since it uses the warnings
485 machinery. */
486 _PyGC_DumpShutdownStats();
487
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200488 /* Now, if there are any modules left alive, clear their globals to
489 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200490 up here, since they are kept alive in the interpreter state.
491
492 The special treatment of "builtins" here is because even
493 when it's not referenced as a module, its dictionary is
494 referenced by almost every module's __builtins__. Since
495 deleting a module clears its dictionary (even if there are
496 references left to it), we need to delete the "builtins"
497 module last. Likewise, we don't delete sys until the very
498 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200499 if (weaklist != NULL) {
500 Py_ssize_t i, n;
501 n = PyList_GET_SIZE(weaklist);
502 for (i = 0; i < n; i++) {
503 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200504 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200505 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
506 if (mod == Py_None)
507 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200508 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200509 dict = PyModule_GetDict(mod);
510 if (dict == interp->builtins || dict == interp->sysdict)
511 continue;
512 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200513 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200514 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200515 _PyModule_Clear(mod);
516 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200517 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200518 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000520
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200521 /* Next, delete sys and builtins (in that order) */
522 if (Py_VerboseFlag)
523 PySys_FormatStderr("# cleanup[3] wiping sys\n");
524 _PyModule_ClearDict(interp->sysdict);
525 if (Py_VerboseFlag)
526 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
527 _PyModule_ClearDict(interp->builtins);
528
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200529 /* Clear and delete the modules directory. Actual modules will
530 still be there only if imported during the execution of some
531 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 interp->modules = NULL;
533 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200534
535 /* Once more */
536 _PyGC_CollectNoFail();
537
538#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000539}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000540
541
Barry Warsaw28a691b2010-04-17 00:19:56 +0000542/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000543
544long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000545PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000546{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200547 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400548 PyInterpreterState *interp = PyThreadState_Get()->interp;
549 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
550 "_RAW_MAGIC_NUMBER");
551 if (pyc_magic == NULL)
552 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200553 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700554 Py_DECREF(pyc_magic);
555 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000556}
557
558
Brett Cannon3adc7b72012-07-09 14:22:12 -0400559extern const char * _PySys_ImplCacheTag;
560
Barry Warsaw28a691b2010-04-17 00:19:56 +0000561const char *
562PyImport_GetMagicTag(void)
563{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400564 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000565}
566
Brett Cannon98979b82012-07-02 15:13:11 -0400567
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568/* Magic for extension modules (built-in as well as dynamically
569 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200570 once, we keep a static dictionary 'extensions' keyed by the tuple
571 (module name, module name) (for built-in modules) or by
572 (filename, module name) (for dynamically loaded modules), containing these
573 modules. A copy of the module's dictionary is stored by calling
574 _PyImport_FixupExtensionObject() immediately after the module initialization
575 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100576 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000577
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000578 Modules which do support multiple initialization set their m_size
579 field to a non-negative number (indicating the size of the
580 module-specific state). They are still recorded in the extensions
581 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000582*/
583
584int
Victor Stinner95872862011-03-07 18:20:56 +0100585_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
586 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500588 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500590 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (extensions == NULL) {
592 extensions = PyDict_New();
593 if (extensions == NULL)
594 return -1;
595 }
596 if (mod == NULL || !PyModule_Check(mod)) {
597 PyErr_BadInternalCall();
598 return -1;
599 }
600 def = PyModule_GetDef(mod);
601 if (!def) {
602 PyErr_BadInternalCall();
603 return -1;
604 }
605 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100606 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 return -1;
608 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100609 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return -1;
611 }
612 if (def->m_size == -1) {
613 if (def->m_base.m_copy) {
614 /* Somebody already imported the module,
615 likely under a different name.
616 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200617 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 }
619 dict = PyModule_GetDict(mod);
620 if (dict == NULL)
621 return -1;
622 def->m_base.m_copy = PyDict_Copy(dict);
623 if (def->m_base.m_copy == NULL)
624 return -1;
625 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500626 key = PyTuple_Pack(2, filename, name);
627 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200628 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500629 res = PyDict_SetItem(extensions, key, (PyObject *)def);
630 Py_DECREF(key);
631 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200632 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634}
635
Victor Stinner49d3f252010-10-17 01:24:53 +0000636int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300637_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000638{
639 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100640 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100641 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100642 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000643 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100644 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
645 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000646 return res;
647}
648
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100650_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000651{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500652 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyModuleDef* def;
654 if (extensions == NULL)
655 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500656 key = PyTuple_Pack(2, filename, name);
657 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200658 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500659 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
660 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (def == NULL)
662 return NULL;
663 if (def->m_size == -1) {
664 /* Module does not support repeated initialization */
665 if (def->m_base.m_copy == NULL)
666 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100667 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (mod == NULL)
669 return NULL;
670 mdict = PyModule_GetDict(mod);
671 if (mdict == NULL)
672 return NULL;
673 if (PyDict_Update(mdict, def->m_base.m_copy))
674 return NULL;
675 }
676 else {
677 if (def->m_base.m_init == NULL)
678 return NULL;
679 mod = def->m_base.m_init();
680 if (mod == NULL)
681 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200682 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
683 Py_DECREF(mod);
684 return NULL;
685 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 Py_DECREF(mod);
687 }
688 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100689 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 Py_DECREF(mod);
691 return NULL;
692 }
693 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100694 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 name, filename);
696 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000697
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000698}
699
Victor Stinner49d3f252010-10-17 01:24:53 +0000700PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000701_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000702{
Victor Stinner95872862011-03-07 18:20:56 +0100703 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100704 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100705 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000706 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100707 res = _PyImport_FindExtensionObject(nameobj, nameobj);
708 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000709 return res;
710}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000711
712/* Get the module object corresponding to a module name.
713 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000714 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000715 Because the former action is most common, THIS DOES NOT RETURN A
716 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717
Guido van Rossum79f25d91997-04-29 20:08:16 +0000718PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000719PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 PyObject *modules = PyImport_GetModuleDict();
722 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000723
Victor Stinner27ee0892011-03-04 12:57:09 +0000724 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyModule_Check(m))
726 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000727 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (m == NULL)
729 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000730 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 Py_DECREF(m);
732 return NULL;
733 }
734 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737}
738
Victor Stinner27ee0892011-03-04 12:57:09 +0000739PyObject *
740PyImport_AddModule(const char *name)
741{
742 PyObject *nameobj, *module;
743 nameobj = PyUnicode_FromString(name);
744 if (nameobj == NULL)
745 return NULL;
746 module = PyImport_AddModuleObject(nameobj);
747 Py_DECREF(nameobj);
748 return module;
749}
750
751
Tim Peters1cd70172004-08-02 03:52:12 +0000752/* Remove name from sys.modules, if it's there. */
753static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000754remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000757 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000759 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 Py_FatalError("import: deleting existing key in"
761 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000762}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763
Christian Heimes3b06e532008-01-07 20:12:44 +0000764
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000765/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000766 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
767 * removed from sys.modules, to avoid leaving damaged module objects
768 * in sys.modules. The caller may wish to restore the original
769 * module object (if any) in this case; PyImport_ReloadModule is an
770 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000771 *
772 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
773 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000774 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000775PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300776PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 return PyImport_ExecCodeModuleWithPathnames(
779 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000780}
781
782PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300783PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return PyImport_ExecCodeModuleWithPathnames(
786 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000787}
788
789PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300790PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
791 const char *pathname,
792 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000793{
Victor Stinner27ee0892011-03-04 12:57:09 +0000794 PyObject *m = NULL;
795 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
796
797 nameobj = PyUnicode_FromString(name);
798 if (nameobj == NULL)
799 return NULL;
800
Victor Stinner27ee0892011-03-04 12:57:09 +0000801 if (cpathname != NULL) {
802 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
803 if (cpathobj == NULL)
804 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400805 }
806 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000807 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400808
809 if (pathname != NULL) {
810 pathobj = PyUnicode_DecodeFSDefault(pathname);
811 if (pathobj == NULL)
812 goto error;
813 }
814 else if (cpathobj != NULL) {
815 PyInterpreterState *interp = PyThreadState_GET()->interp;
816 _Py_IDENTIFIER(_get_sourcefile);
817
818 if (interp == NULL) {
819 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
820 "no interpreter!");
821 }
822
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -0700823 pathobj = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannona6473f92012-07-13 13:57:03 -0400824 &PyId__get_sourcefile, cpathobj,
825 NULL);
826 if (pathobj == NULL)
827 PyErr_Clear();
828 }
829 else
830 pathobj = NULL;
831
Victor Stinner27ee0892011-03-04 12:57:09 +0000832 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
833error:
834 Py_DECREF(nameobj);
835 Py_XDECREF(pathobj);
836 Py_XDECREF(cpathobj);
837 return m;
838}
839
Brett Cannon18fc4e72014-04-04 10:01:46 -0400840static PyObject *
841module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000842{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400843 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000844
Victor Stinner27ee0892011-03-04 12:57:09 +0000845 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (m == NULL)
847 return NULL;
848 /* If the module is being reloaded, we get the old module back
849 and re-use its dict to exec the new code. */
850 d = PyModule_GetDict(m);
851 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
852 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400853 PyEval_GetBuiltins()) != 0) {
854 remove_module(name);
855 return NULL;
856 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400858
Eric Snow08197a42014-05-12 17:54:55 -0600859 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400860}
861
862static PyObject *
863exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
864{
865 PyObject *modules = PyImport_GetModuleDict();
866 PyObject *v, *m;
867
868 v = PyEval_EvalCode(code_object, module_dict, module_dict);
869 if (v == NULL) {
870 remove_module(name);
871 return NULL;
872 }
873 Py_DECREF(v);
874
875 if ((m = PyDict_GetItem(modules, name)) == NULL) {
876 PyErr_Format(PyExc_ImportError,
877 "Loaded module %R not found in sys.modules",
878 name);
879 return NULL;
880 }
881
882 Py_INCREF(m);
883
884 return m;
885}
886
887PyObject*
888PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
889 PyObject *cpathname)
890{
Eric Snow08197a42014-05-12 17:54:55 -0600891 PyObject *d, *res;
892 PyInterpreterState *interp = PyThreadState_GET()->interp;
893 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400894
895 d = module_dict_for_exec(name);
896 if (d == NULL) {
897 return NULL;
898 }
899
Eric Snow08197a42014-05-12 17:54:55 -0600900 if (pathname == NULL) {
901 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 }
Eric Snow08197a42014-05-12 17:54:55 -0600903 res = _PyObject_CallMethodIdObjArgs(interp->importlib,
904 &PyId__fix_up_module,
905 d, name, pathname, cpathname, NULL);
906 if (res != NULL) {
907 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
Eric Snow08197a42014-05-12 17:54:55 -0600909 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000910}
911
912
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000913static void
914update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyObject *constants, *tmp;
917 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (PyUnicode_Compare(co->co_filename, oldname))
920 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 tmp = co->co_filename;
923 co->co_filename = newname;
924 Py_INCREF(co->co_filename);
925 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 constants = co->co_consts;
928 n = PyTuple_GET_SIZE(constants);
929 for (i = 0; i < n; i++) {
930 tmp = PyTuple_GET_ITEM(constants, i);
931 if (PyCode_Check(tmp))
932 update_code_filenames((PyCodeObject *)tmp,
933 oldname, newname);
934 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000935}
936
Victor Stinner2f42ae52011-03-20 00:41:24 +0100937static void
938update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000939{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100940 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000941
Victor Stinner2f42ae52011-03-20 00:41:24 +0100942 if (PyUnicode_Compare(co->co_filename, newname) == 0)
943 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 oldname = co->co_filename;
946 Py_INCREF(oldname);
947 update_code_filenames(co, oldname, newname);
948 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000949}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000950
Brett Cannon4caa61d2014-01-09 19:03:32 -0500951/*[clinic input]
952_imp._fix_co_filename
953
954 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
955 Code object to change.
956
957 path: unicode
958 File path to use.
959 /
960
961Changes code.co_filename to specify the passed-in file path.
962[clinic start generated code]*/
963
964PyDoc_STRVAR(_imp__fix_co_filename__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800965"_fix_co_filename($module, code, path, /)\n"
966"--\n"
967"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500968"Changes code.co_filename to specify the passed-in file path.\n"
969"\n"
970" code\n"
971" Code object to change.\n"
972" path\n"
973" File path to use.");
974
975#define _IMP__FIX_CO_FILENAME_METHODDEF \
976 {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_VARARGS, _imp__fix_co_filename__doc__},
977
Brett Cannon442c9b92011-03-23 16:14:42 -0700978static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500979_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path);
980
981static PyObject *
982_imp__fix_co_filename(PyModuleDef *module, PyObject *args)
Brett Cannon442c9b92011-03-23 16:14:42 -0700983{
Brett Cannon4caa61d2014-01-09 19:03:32 -0500984 PyObject *return_value = NULL;
985 PyCodeObject *code;
986 PyObject *path;
Brett Cannon442c9b92011-03-23 16:14:42 -0700987
Brett Cannon4caa61d2014-01-09 19:03:32 -0500988 if (!PyArg_ParseTuple(args,
989 "O!U:_fix_co_filename",
990 &PyCode_Type, &code, &path))
991 goto exit;
992 return_value = _imp__fix_co_filename_impl(module, code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700993
Brett Cannon4caa61d2014-01-09 19:03:32 -0500994exit:
995 return return_value;
996}
Brett Cannon442c9b92011-03-23 16:14:42 -0700997
Brett Cannon4caa61d2014-01-09 19:03:32 -0500998static PyObject *
999_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001000/*[clinic end generated code: output=6b4b1edeb0d55c5d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001001
Brett Cannon4caa61d2014-01-09 19:03:32 -05001002{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001003 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001004
1005 Py_RETURN_NONE;
1006}
1007
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001008
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001009/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001010static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001011
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001012
1013/* Helper to test for built-in module */
1014
1015static int
Victor Stinner95872862011-03-07 18:20:56 +01001016is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017{
Victor Stinner95872862011-03-07 18:20:56 +01001018 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001020 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1021 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (PyImport_Inittab[i].initfunc == NULL)
1023 return -1;
1024 else
1025 return 1;
1026 }
1027 }
1028 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001029}
1030
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001031
Just van Rossum52e14d62002-12-30 22:08:05 +00001032/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1033 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001034 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001035 that can handle the path item. Return None if no hook could;
1036 this tells our caller it should fall back to the builtin
1037 import mechanism. Cache the result in path_importer_cache.
1038 Returns a borrowed reference. */
1039
1040static PyObject *
1041get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyObject *importer;
1045 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 /* These conditions are the caller's responsibility: */
1048 assert(PyList_Check(path_hooks));
1049 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 nhooks = PyList_Size(path_hooks);
1052 if (nhooks < 0)
1053 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 importer = PyDict_GetItem(path_importer_cache, p);
1056 if (importer != NULL)
1057 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 /* set path_importer_cache[p] to None to avoid recursion */
1060 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1061 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 for (j = 0; j < nhooks; j++) {
1064 PyObject *hook = PyList_GetItem(path_hooks, j);
1065 if (hook == NULL)
1066 return NULL;
1067 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1068 if (importer != NULL)
1069 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1072 return NULL;
1073 }
1074 PyErr_Clear();
1075 }
1076 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001077 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 }
1079 if (importer != NULL) {
1080 int err = PyDict_SetItem(path_importer_cache, p, importer);
1081 Py_DECREF(importer);
1082 if (err != 0)
1083 return NULL;
1084 }
1085 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001086}
1087
Christian Heimes9cd17752007-11-18 19:35:23 +00001088PyAPI_FUNC(PyObject *)
1089PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001091
Victor Stinner1e53bba2013-07-16 22:26:05 +02001092 path_importer_cache = PySys_GetObject("path_importer_cache");
1093 path_hooks = PySys_GetObject("path_hooks");
1094 if (path_importer_cache != NULL && path_hooks != NULL) {
1095 importer = get_path_importer(path_importer_cache,
1096 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 }
1098 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1099 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001100}
1101
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001102
Victor Stinner95872862011-03-07 18:20:56 +01001103static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001104
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001105/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001106 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001107 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001108
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001109static int
Victor Stinner95872862011-03-07 18:20:56 +01001110init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001113 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001114
Victor Stinner5eb4f592013-11-14 22:38:52 +01001115 mod = _PyImport_FindExtensionObject(name, name);
1116 if (PyErr_Occurred())
1117 return -1;
1118 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 for (p = PyImport_Inittab; p->name != NULL; p++) {
1122 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001123 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001124 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (p->initfunc == NULL) {
1126 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001127 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 name);
1129 return -1;
1130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 mod = (*p->initfunc)();
1132 if (mod == 0)
1133 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001134 /* Remember pointer to module init function. */
1135 def = PyModule_GetDef(mod);
1136 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001137 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 return -1;
1139 /* FixupExtension has put the module into sys.modules,
1140 so we can release our own reference. */
1141 Py_DECREF(mod);
1142 return 1;
1143 }
1144 }
1145 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001146}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001147
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001148
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001149/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001150
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001151static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001152find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001153{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001154 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001155
Victor Stinner53dc7352011-03-20 01:50:21 +01001156 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 for (p = PyImport_FrozenModules; ; p++) {
1160 if (p->name == NULL)
1161 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001162 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 break;
1164 }
1165 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001166}
1167
Guido van Rossum79f25d91997-04-29 20:08:16 +00001168static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001169get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001170{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001171 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (p == NULL) {
1175 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001176 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 name);
1178 return NULL;
1179 }
1180 if (p->code == NULL) {
1181 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001182 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 name);
1184 return NULL;
1185 }
1186 size = p->size;
1187 if (size < 0)
1188 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001189 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001190}
1191
Brett Cannon8d110132009-03-15 02:20:16 +00001192static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001193is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001194{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001195 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (p == NULL) {
1199 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001200 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 name);
1202 return NULL;
1203 }
Brett Cannon8d110132009-03-15 02:20:16 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (size < 0)
1208 Py_RETURN_TRUE;
1209 else
1210 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001211}
1212
1213
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001214/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001215 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001216 an exception set if the initialization failed.
1217 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001218
1219int
Victor Stinner53dc7352011-03-20 01:50:21 +01001220PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001221{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001222 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001223 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 int ispackage;
1225 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001226
Victor Stinner53dc7352011-03-20 01:50:21 +01001227 p = find_frozen(name);
1228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (p == NULL)
1230 return 0;
1231 if (p->code == NULL) {
1232 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001233 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 name);
1235 return -1;
1236 }
1237 size = p->size;
1238 ispackage = (size < 0);
1239 if (ispackage)
1240 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001241 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (co == NULL)
1243 return -1;
1244 if (!PyCode_Check(co)) {
1245 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001246 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 name);
1248 goto err_return;
1249 }
1250 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001251 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001252 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001254 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (m == NULL)
1256 goto err_return;
1257 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001258 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 goto err_return;
1261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 err = PyDict_SetItemString(d, "__path__", l);
1263 Py_DECREF(l);
1264 if (err != 0)
1265 goto err_return;
1266 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001267 d = module_dict_for_exec(name);
1268 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001269 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001270 }
1271 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (m == NULL)
1273 goto err_return;
1274 Py_DECREF(co);
1275 Py_DECREF(m);
1276 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001277err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 Py_DECREF(co);
1279 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001280}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001281
Victor Stinner53dc7352011-03-20 01:50:21 +01001282int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001283PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001284{
1285 PyObject *nameobj;
1286 int ret;
1287 nameobj = PyUnicode_InternFromString(name);
1288 if (nameobj == NULL)
1289 return -1;
1290 ret = PyImport_ImportFrozenModuleObject(nameobj);
1291 Py_DECREF(nameobj);
1292 return ret;
1293}
1294
Guido van Rossum74e6a111994-08-29 12:54:38 +00001295
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001296/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001297 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001298
Guido van Rossum79f25d91997-04-29 20:08:16 +00001299PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001300PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 PyObject *pname;
1303 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 pname = PyUnicode_FromString(name);
1306 if (pname == NULL)
1307 return NULL;
1308 result = PyImport_Import(pname);
1309 Py_DECREF(pname);
1310 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001311}
1312
Christian Heimes072c0f12008-01-03 23:01:04 +00001313/* Import a module without blocking
1314 *
1315 * At first it tries to fetch the module from sys.modules. If the module was
1316 * never loaded before it loads it with PyImport_ImportModule() unless another
1317 * thread holds the import lock. In the latter case the function raises an
1318 * ImportError instead of blocking.
1319 *
1320 * Returns the module object with incremented ref count.
1321 */
1322PyObject *
1323PyImport_ImportModuleNoBlock(const char *name)
1324{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001325 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001326}
1327
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001328
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001329/* Remove importlib frames from the traceback,
1330 * except in Verbose mode. */
1331static void
1332remove_importlib_frames(void)
1333{
1334 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001335 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001336 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001337 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001338 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001339 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001340
1341 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001342 from the traceback. We always trim chunks
1343 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001344
1345 PyErr_Fetch(&exception, &value, &base_tb);
1346 if (!exception || Py_VerboseFlag)
1347 goto done;
1348 if (PyType_IsSubtype((PyTypeObject *) exception,
1349 (PyTypeObject *) PyExc_ImportError))
1350 always_trim = 1;
1351
1352 prev_link = &base_tb;
1353 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001354 while (tb != NULL) {
1355 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1356 PyObject *next = (PyObject *) traceback->tb_next;
1357 PyFrameObject *frame = traceback->tb_frame;
1358 PyCodeObject *code = frame->f_code;
1359 int now_in_importlib;
1360
1361 assert(PyTraceBack_Check(tb));
1362 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1363 code->co_filename,
1364 importlib_filename) == 0);
1365 if (now_in_importlib && !in_importlib) {
1366 /* This is the link to this chunk of importlib tracebacks */
1367 outer_link = prev_link;
1368 }
1369 in_importlib = now_in_importlib;
1370
1371 if (in_importlib &&
1372 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001373 PyUnicode_CompareWithASCIIString(code->co_name,
1374 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001375 PyObject *tmp = *outer_link;
1376 *outer_link = next;
1377 Py_XINCREF(next);
1378 Py_DECREF(tmp);
1379 prev_link = outer_link;
1380 }
1381 else {
1382 prev_link = (PyObject **) &traceback->tb_next;
1383 }
1384 tb = next;
1385 }
1386done:
1387 PyErr_Restore(exception, value, base_tb);
1388}
1389
1390
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001391PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001392PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1393 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001394 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001395{
Brett Cannonfd074152012-04-14 14:10:13 -04001396 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001397 _Py_IDENTIFIER(__spec__);
1398 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001399 _Py_IDENTIFIER(__package__);
1400 _Py_IDENTIFIER(__path__);
1401 _Py_IDENTIFIER(__name__);
1402 _Py_IDENTIFIER(_find_and_load);
1403 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001404 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001405 _Py_static_string(single_dot, ".");
1406 PyObject *abs_name = NULL;
1407 PyObject *builtins_import = NULL;
1408 PyObject *final_mod = NULL;
1409 PyObject *mod = NULL;
1410 PyObject *package = NULL;
1411 PyObject *globals = NULL;
1412 PyObject *fromlist = NULL;
1413 PyInterpreterState *interp = PyThreadState_GET()->interp;
1414
1415 /* Make sure to use default values so as to not have
1416 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1417 NULL argument. */
1418 if (given_globals == NULL) {
1419 globals = PyDict_New();
1420 if (globals == NULL) {
1421 goto error;
1422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 }
Brett Cannonfd074152012-04-14 14:10:13 -04001424 else {
1425 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001426 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001427 if (level > 0 && !PyDict_Check(given_globals)) {
1428 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1429 goto error;
1430 }
1431 globals = given_globals;
1432 Py_INCREF(globals);
1433 }
1434
1435 if (given_fromlist == NULL) {
1436 fromlist = PyList_New(0);
1437 if (fromlist == NULL) {
1438 goto error;
1439 }
1440 }
1441 else {
1442 fromlist = given_fromlist;
1443 Py_INCREF(fromlist);
1444 }
1445 if (name == NULL) {
1446 PyErr_SetString(PyExc_ValueError, "Empty module name");
1447 goto error;
1448 }
1449
1450 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1451 for added performance. */
1452
1453 if (!PyUnicode_Check(name)) {
1454 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1455 goto error;
1456 }
1457 else if (PyUnicode_READY(name) < 0) {
1458 goto error;
1459 }
1460 if (level < 0) {
1461 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1462 goto error;
1463 }
1464 else if (level > 0) {
1465 package = _PyDict_GetItemId(globals, &PyId___package__);
1466 if (package != NULL && package != Py_None) {
1467 Py_INCREF(package);
1468 if (!PyUnicode_Check(package)) {
1469 PyErr_SetString(PyExc_TypeError, "package must be a string");
1470 goto error;
1471 }
1472 }
1473 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001474 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001475 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001476 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001477 goto error;
1478 }
1479 else if (!PyUnicode_Check(package)) {
1480 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1481 }
1482 Py_INCREF(package);
1483
1484 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001485 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001486 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1487 if (borrowed_dot == NULL) {
1488 goto error;
1489 }
Brett Cannon740fce02012-04-14 14:23:49 -04001490 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001491 Py_DECREF(package);
1492 if (partition == NULL) {
1493 goto error;
1494 }
1495 package = PyTuple_GET_ITEM(partition, 0);
1496 Py_INCREF(package);
1497 Py_DECREF(partition);
1498 }
1499 }
1500
1501 if (PyDict_GetItem(interp->modules, package) == NULL) {
1502 PyErr_Format(PyExc_SystemError,
1503 "Parent module %R not loaded, cannot perform relative "
1504 "import", package);
1505 goto error;
1506 }
1507 }
1508 else { /* level == 0 */
1509 if (PyUnicode_GET_LENGTH(name) == 0) {
1510 PyErr_SetString(PyExc_ValueError, "Empty module name");
1511 goto error;
1512 }
1513 package = Py_None;
1514 Py_INCREF(package);
1515 }
1516
1517 if (level > 0) {
1518 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1519 PyObject *base = NULL;
1520 int level_up = 1;
1521
1522 for (level_up = 1; level_up < level; level_up += 1) {
1523 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1524 if (last_dot == -2) {
1525 goto error;
1526 }
1527 else if (last_dot == -1) {
1528 PyErr_SetString(PyExc_ValueError,
1529 "attempted relative import beyond top-level "
1530 "package");
1531 goto error;
1532 }
1533 }
Victor Stinner22af2592013-11-13 12:11:36 +01001534
Brett Cannonfd074152012-04-14 14:10:13 -04001535 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001536 if (base == NULL)
1537 goto error;
1538
Brett Cannonfd074152012-04-14 14:10:13 -04001539 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001540 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001541
1542 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001543 seq = PyTuple_Pack(2, base, name);
1544 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001545 if (borrowed_dot == NULL || seq == NULL) {
1546 goto error;
1547 }
1548
1549 abs_name = PyUnicode_Join(borrowed_dot, seq);
1550 Py_DECREF(seq);
1551 if (abs_name == NULL) {
1552 goto error;
1553 }
1554 }
1555 else {
1556 abs_name = base;
1557 }
1558 }
1559 else {
1560 abs_name = name;
1561 Py_INCREF(abs_name);
1562 }
1563
Brian Curtine6b299f2012-04-14 14:19:33 -05001564#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001565 _PyImport_AcquireLock();
1566#endif
1567 /* From this point forward, goto error_with_unlock! */
1568 if (PyDict_Check(globals)) {
1569 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1570 }
1571 if (builtins_import == NULL) {
1572 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1573 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001574 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1575 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001576 }
1577 }
1578 Py_INCREF(builtins_import);
1579
1580 mod = PyDict_GetItem(interp->modules, abs_name);
1581 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001582 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1583 "None in sys.modules", abs_name);
1584 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001585 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001586 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001587 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001588 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001589 goto error_with_unlock;
1590 }
1591 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001592 PyObject *value = NULL;
1593 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001594 int initializing = 0;
1595
Brett Cannonfd074152012-04-14 14:10:13 -04001596 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001597 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001598 __spec__._initializing is true.
1599 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001600 stuffing the new module in sys.modules.
1601 */
Eric Snowb523f842013-11-22 09:05:39 -07001602 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1603 if (spec != NULL) {
1604 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1605 Py_DECREF(spec);
1606 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001607 if (value == NULL)
1608 PyErr_Clear();
1609 else {
1610 initializing = PyObject_IsTrue(value);
1611 Py_DECREF(value);
1612 if (initializing == -1)
1613 PyErr_Clear();
1614 }
1615 if (initializing > 0) {
1616 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001617 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001618 &PyId__lock_unlock_module, abs_name,
1619 NULL);
1620 if (value == NULL)
1621 goto error;
1622 Py_DECREF(value);
1623 }
1624 else {
1625#ifdef WITH_THREAD
1626 if (_PyImport_ReleaseLock() < 0) {
1627 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1628 goto error;
1629 }
1630#endif
1631 }
Brett Cannonfd074152012-04-14 14:10:13 -04001632 }
1633 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001634 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001635 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001636 &PyId__find_and_load, abs_name,
1637 builtins_import, NULL);
1638 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001639 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001640 }
1641 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001642 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001643
1644 if (PyObject_Not(fromlist)) {
1645 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1646 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001647 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001648 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1649
1650 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001651 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001652 }
1653
Brian Curtine6b299f2012-04-14 14:19:33 -05001654 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001655 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001656 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001657 }
1658
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001659 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1660 /* No dot in module name, simple exit */
1661 Py_DECREF(partition);
1662 final_mod = mod;
1663 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001664 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001665 }
1666
Brett Cannonfd074152012-04-14 14:10:13 -04001667 front = PyTuple_GET_ITEM(partition, 0);
1668 Py_INCREF(front);
1669 Py_DECREF(partition);
1670
1671 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001672 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001673 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001674 }
1675 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001676 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1677 PyUnicode_GET_LENGTH(front);
1678 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001679 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001680 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001681 Py_DECREF(front);
1682 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001683 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001684 }
Brett Cannonfd074152012-04-14 14:10:13 -04001685
1686 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001687 if (final_mod == NULL) {
1688 PyErr_Format(PyExc_KeyError,
1689 "%R not in sys.modules as expected",
1690 to_return);
1691 }
1692 else {
1693 Py_INCREF(final_mod);
1694 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001695 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001696 }
1697 }
1698 else {
1699 final_mod = mod;
1700 Py_INCREF(mod);
1701 }
1702 }
1703 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001704 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001705 &PyId__handle_fromlist, mod,
1706 fromlist, builtins_import,
1707 NULL);
1708 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001709 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001710
Brett Cannonfd074152012-04-14 14:10:13 -04001711 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001712#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001713 if (_PyImport_ReleaseLock() < 0) {
1714 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1715 }
1716#endif
1717 error:
1718 Py_XDECREF(abs_name);
1719 Py_XDECREF(builtins_import);
1720 Py_XDECREF(mod);
1721 Py_XDECREF(package);
1722 Py_XDECREF(globals);
1723 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001724 if (final_mod == NULL)
1725 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001726 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001727}
1728
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001729PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001730PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001731 PyObject *fromlist, int level)
1732{
1733 PyObject *nameobj, *mod;
1734 nameobj = PyUnicode_FromString(name);
1735 if (nameobj == NULL)
1736 return NULL;
1737 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1738 fromlist, level);
1739 Py_DECREF(nameobj);
1740 return mod;
1741}
1742
1743
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001744/* Re-import a module of any kind and return its module object, WITH
1745 INCREMENTED REFERENCE COUNT */
1746
Guido van Rossum79f25d91997-04-29 20:08:16 +00001747PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001748PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001749{
Brett Cannon62228db2012-04-29 14:38:11 -04001750 _Py_IDENTIFIER(reload);
1751 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001753 PyObject *imp = PyDict_GetItemString(modules, "imp");
1754 if (imp == NULL) {
1755 imp = PyImport_ImportModule("imp");
1756 if (imp == NULL) {
1757 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
Brett Cannon62228db2012-04-29 14:38:11 -04001760 else {
1761 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001763
Brett Cannon62228db2012-04-29 14:38:11 -04001764 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1765 Py_DECREF(imp);
1766 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001767}
1768
1769
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001770/* Higher-level import emulator which emulates the "import" statement
1771 more accurately -- it invokes the __import__() function from the
1772 builtins of the current globals. This means that the import is
1773 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001774 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001775 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001776 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001777 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001778
1779PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001780PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 static PyObject *silly_list = NULL;
1783 static PyObject *builtins_str = NULL;
1784 static PyObject *import_str = NULL;
1785 PyObject *globals = NULL;
1786 PyObject *import = NULL;
1787 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001788 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 /* Initialize constant string objects */
1792 if (silly_list == NULL) {
1793 import_str = PyUnicode_InternFromString("__import__");
1794 if (import_str == NULL)
1795 return NULL;
1796 builtins_str = PyUnicode_InternFromString("__builtins__");
1797 if (builtins_str == NULL)
1798 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001799 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (silly_list == NULL)
1801 return NULL;
1802 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Get the builtins from current globals */
1805 globals = PyEval_GetGlobals();
1806 if (globals != NULL) {
1807 Py_INCREF(globals);
1808 builtins = PyObject_GetItem(globals, builtins_str);
1809 if (builtins == NULL)
1810 goto err;
1811 }
1812 else {
1813 /* No globals -- use standard builtins, and fake globals */
1814 builtins = PyImport_ImportModuleLevel("builtins",
1815 NULL, NULL, NULL, 0);
1816 if (builtins == NULL)
1817 return NULL;
1818 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1819 if (globals == NULL)
1820 goto err;
1821 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 /* Get the __import__ function from the builtins */
1824 if (PyDict_Check(builtins)) {
1825 import = PyObject_GetItem(builtins, import_str);
1826 if (import == NULL)
1827 PyErr_SetObject(PyExc_KeyError, import_str);
1828 }
1829 else
1830 import = PyObject_GetAttr(builtins, import_str);
1831 if (import == NULL)
1832 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001835 Always use absolute import here.
1836 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1838 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001839 if (r == NULL)
1840 goto err;
1841 Py_DECREF(r);
1842
1843 modules = PyImport_GetModuleDict();
1844 r = PyDict_GetItem(modules, module_name);
1845 if (r != NULL)
1846 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001847
1848 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 Py_XDECREF(globals);
1850 Py_XDECREF(builtins);
1851 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001854}
1855
Brett Cannon4caa61d2014-01-09 19:03:32 -05001856/*[clinic input]
1857_imp.extension_suffixes
1858
1859Returns the list of file suffixes used to identify extension modules.
1860[clinic start generated code]*/
1861
1862PyDoc_STRVAR(_imp_extension_suffixes__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001863"extension_suffixes($module, /)\n"
1864"--\n"
1865"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001866"Returns the list of file suffixes used to identify extension modules.");
1867
1868#define _IMP_EXTENSION_SUFFIXES_METHODDEF \
1869 {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
1870
Barry Warsaw28a691b2010-04-17 00:19:56 +00001871static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001872_imp_extension_suffixes_impl(PyModuleDef *module);
1873
1874static PyObject *
1875_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1876{
Larry Hastingsbebf7352014-01-17 17:47:17 -08001877 return _imp_extension_suffixes_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001878}
1879
1880static PyObject *
1881_imp_extension_suffixes_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001882/*[clinic end generated code: output=bb30a2438167798c input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001885 const char *suffix;
1886 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 list = PyList_New(0);
1889 if (list == NULL)
1890 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001891#ifdef HAVE_DYNAMIC_LOADING
1892 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1893 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (item == NULL) {
1895 Py_DECREF(list);
1896 return NULL;
1897 }
1898 if (PyList_Append(list, item) < 0) {
1899 Py_DECREF(list);
1900 Py_DECREF(item);
1901 return NULL;
1902 }
1903 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001904 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 }
Brett Cannon2657df42012-05-04 15:20:40 -04001906#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001908}
1909
Brett Cannon4caa61d2014-01-09 19:03:32 -05001910/*[clinic input]
1911_imp.init_builtin
1912
1913 name: unicode
1914 /
1915
1916Initializes a built-in module.
1917[clinic start generated code]*/
1918
1919PyDoc_STRVAR(_imp_init_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001920"init_builtin($module, name, /)\n"
1921"--\n"
1922"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001923"Initializes a built-in module.");
1924
1925#define _IMP_INIT_BUILTIN_METHODDEF \
1926 {"init_builtin", (PyCFunction)_imp_init_builtin, METH_VARARGS, _imp_init_builtin__doc__},
1927
Guido van Rossum79f25d91997-04-29 20:08:16 +00001928static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001929_imp_init_builtin_impl(PyModuleDef *module, PyObject *name);
1930
1931static PyObject *
1932_imp_init_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001933{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001934 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01001935 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001936
1937 if (!PyArg_ParseTuple(args,
1938 "U:init_builtin",
1939 &name))
1940 goto exit;
1941 return_value = _imp_init_builtin_impl(module, name);
1942
1943exit:
1944 return return_value;
1945}
1946
1947static PyObject *
1948_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001949/*[clinic end generated code: output=a0244948a43f8e26 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 int ret;
1952 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 ret = init_builtin(name);
1955 if (ret < 0)
1956 return NULL;
1957 if (ret == 0) {
1958 Py_INCREF(Py_None);
1959 return Py_None;
1960 }
Victor Stinner95872862011-03-07 18:20:56 +01001961 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 Py_XINCREF(m);
1963 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001964}
1965
Brett Cannon4caa61d2014-01-09 19:03:32 -05001966/*[clinic input]
1967_imp.init_frozen
1968
1969 name: unicode
1970 /
1971
1972Initializes a frozen module.
1973[clinic start generated code]*/
1974
1975PyDoc_STRVAR(_imp_init_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001976"init_frozen($module, name, /)\n"
1977"--\n"
1978"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001979"Initializes a frozen module.");
1980
1981#define _IMP_INIT_FROZEN_METHODDEF \
1982 {"init_frozen", (PyCFunction)_imp_init_frozen, METH_VARARGS, _imp_init_frozen__doc__},
1983
Guido van Rossum79f25d91997-04-29 20:08:16 +00001984static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001985_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
1986
1987static PyObject *
1988_imp_init_frozen(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001989{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001991 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001992
1993 if (!PyArg_ParseTuple(args,
1994 "U:init_frozen",
1995 &name))
1996 goto exit;
1997 return_value = _imp_init_frozen_impl(module, name);
1998
1999exit:
2000 return return_value;
2001}
2002
2003static PyObject *
2004_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002005/*[clinic end generated code: output=e4bc2bff296f8f22 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 int ret;
2008 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002009
Victor Stinner53dc7352011-03-20 01:50:21 +01002010 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (ret < 0)
2012 return NULL;
2013 if (ret == 0) {
2014 Py_INCREF(Py_None);
2015 return Py_None;
2016 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002017 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 Py_XINCREF(m);
2019 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002020}
2021
Brett Cannon4caa61d2014-01-09 19:03:32 -05002022/*[clinic input]
2023_imp.get_frozen_object
2024
2025 name: unicode
2026 /
2027
2028Create a code object for a frozen module.
2029[clinic start generated code]*/
2030
2031PyDoc_STRVAR(_imp_get_frozen_object__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002032"get_frozen_object($module, name, /)\n"
2033"--\n"
2034"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002035"Create a code object for a frozen module.");
2036
2037#define _IMP_GET_FROZEN_OBJECT_METHODDEF \
2038 {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_VARARGS, _imp_get_frozen_object__doc__},
2039
Guido van Rossum79f25d91997-04-29 20:08:16 +00002040static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002041_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
2042
2043static PyObject *
2044_imp_get_frozen_object(PyModuleDef *module, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002045{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002046 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002047 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002048
Brett Cannon4caa61d2014-01-09 19:03:32 -05002049 if (!PyArg_ParseTuple(args,
2050 "U:get_frozen_object",
2051 &name))
2052 goto exit;
2053 return_value = _imp_get_frozen_object_impl(module, name);
2054
2055exit:
2056 return return_value;
2057}
2058
2059static PyObject *
2060_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002061/*[clinic end generated code: output=4089ec702a9d70c5 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002064}
2065
Brett Cannon4caa61d2014-01-09 19:03:32 -05002066/*[clinic input]
2067_imp.is_frozen_package
2068
2069 name: unicode
2070 /
2071
2072Returns True if the module name is of a frozen package.
2073[clinic start generated code]*/
2074
2075PyDoc_STRVAR(_imp_is_frozen_package__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002076"is_frozen_package($module, name, /)\n"
2077"--\n"
2078"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002079"Returns True if the module name is of a frozen package.");
2080
2081#define _IMP_IS_FROZEN_PACKAGE_METHODDEF \
2082 {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_VARARGS, _imp_is_frozen_package__doc__},
2083
Guido van Rossum79f25d91997-04-29 20:08:16 +00002084static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002085_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
2086
2087static PyObject *
2088_imp_is_frozen_package(PyModuleDef *module, PyObject *args)
Brett Cannon8d110132009-03-15 02:20:16 +00002089{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002090 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002091 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002092
Brett Cannon4caa61d2014-01-09 19:03:32 -05002093 if (!PyArg_ParseTuple(args,
2094 "U:is_frozen_package",
2095 &name))
2096 goto exit;
2097 return_value = _imp_is_frozen_package_impl(module, name);
2098
2099exit:
2100 return return_value;
2101}
2102
2103static PyObject *
2104_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002105/*[clinic end generated code: output=86aab14dcd4b959b input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002108}
2109
Brett Cannon4caa61d2014-01-09 19:03:32 -05002110/*[clinic input]
2111_imp.is_builtin
2112
2113 name: unicode
2114 /
2115
2116Returns True if the module name corresponds to a built-in module.
2117[clinic start generated code]*/
2118
2119PyDoc_STRVAR(_imp_is_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002120"is_builtin($module, name, /)\n"
2121"--\n"
2122"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002123"Returns True if the module name corresponds to a built-in module.");
2124
2125#define _IMP_IS_BUILTIN_METHODDEF \
2126 {"is_builtin", (PyCFunction)_imp_is_builtin, METH_VARARGS, _imp_is_builtin__doc__},
2127
Brett Cannon8d110132009-03-15 02:20:16 +00002128static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002129_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
2130
2131static PyObject *
2132_imp_is_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002133{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002134 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01002135 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002136
2137 if (!PyArg_ParseTuple(args,
2138 "U:is_builtin",
2139 &name))
2140 goto exit;
2141 return_value = _imp_is_builtin_impl(module, name);
2142
2143exit:
2144 return return_value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002145}
2146
Guido van Rossum79f25d91997-04-29 20:08:16 +00002147static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002148_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002149/*[clinic end generated code: output=d5847f8cac50946e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002150{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002151 return PyLong_FromLong(is_builtin(name));
2152}
2153
2154/*[clinic input]
2155_imp.is_frozen
2156
2157 name: unicode
2158 /
2159
2160Returns True if the module name corresponds to a frozen module.
2161[clinic start generated code]*/
2162
2163PyDoc_STRVAR(_imp_is_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002164"is_frozen($module, name, /)\n"
2165"--\n"
2166"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002167"Returns True if the module name corresponds to a frozen module.");
2168
2169#define _IMP_IS_FROZEN_METHODDEF \
2170 {"is_frozen", (PyCFunction)_imp_is_frozen, METH_VARARGS, _imp_is_frozen__doc__},
2171
2172static PyObject *
2173_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
2174
2175static PyObject *
2176_imp_is_frozen(PyModuleDef *module, PyObject *args)
2177{
2178 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002179 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002180
2181 if (!PyArg_ParseTuple(args,
2182 "U:is_frozen",
2183 &name))
2184 goto exit;
2185 return_value = _imp_is_frozen_impl(module, name);
2186
2187exit:
2188 return return_value;
2189}
2190
2191static PyObject *
2192_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002193/*[clinic end generated code: output=6691af884ba4987d input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002194{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002195 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 p = find_frozen(name);
2198 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002199}
2200
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002201#ifdef HAVE_DYNAMIC_LOADING
2202
Brett Cannon4caa61d2014-01-09 19:03:32 -05002203/*[clinic input]
2204_imp.load_dynamic
2205
2206 name: unicode
2207 path: fs_unicode
2208 file: object = NULL
2209 /
2210
2211Loads an extension module.
2212[clinic start generated code]*/
2213
2214PyDoc_STRVAR(_imp_load_dynamic__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002215"load_dynamic($module, name, path, file=None, /)\n"
2216"--\n"
2217"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002218"Loads an extension module.");
2219
2220#define _IMP_LOAD_DYNAMIC_METHODDEF \
2221 {"load_dynamic", (PyCFunction)_imp_load_dynamic, METH_VARARGS, _imp_load_dynamic__doc__},
2222
Guido van Rossum79f25d91997-04-29 20:08:16 +00002223static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002224_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file);
2225
2226static PyObject *
2227_imp_load_dynamic(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002228{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002229 PyObject *return_value = NULL;
2230 PyObject *name;
2231 PyObject *path;
2232 PyObject *file = NULL;
2233
2234 if (!PyArg_ParseTuple(args,
2235 "UO&|O:load_dynamic",
2236 &name, PyUnicode_FSDecoder, &path, &file))
2237 goto exit;
2238 return_value = _imp_load_dynamic_impl(module, name, path, file);
2239
2240exit:
2241 return return_value;
2242}
2243
2244static PyObject *
2245_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002246/*[clinic end generated code: output=81d11a1fbd1ea0a8 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002247{
2248 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002249 FILE *fp;
2250
Brett Cannon4caa61d2014-01-09 19:03:32 -05002251 if (file != NULL) {
2252 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002253 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002254 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002255 if (!PyErr_Occurred())
2256 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002260 else
2261 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002262 mod = _PyImport_LoadDynamicModule(name, path, fp);
2263 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (fp)
2265 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002266 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002267}
2268
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002269#endif /* HAVE_DYNAMIC_LOADING */
2270
Larry Hastings7726ac92014-01-31 22:03:12 -08002271/*[clinic input]
2272dump buffer
2273[clinic start generated code]*/
2274
2275#ifndef _IMP_LOAD_DYNAMIC_METHODDEF
2276 #define _IMP_LOAD_DYNAMIC_METHODDEF
2277#endif /* !defined(_IMP_LOAD_DYNAMIC_METHODDEF) */
2278/*[clinic end generated code: output=d07c1d4a343a9579 input=524ce2e021e4eba6]*/
2279
Barry Warsaw28a691b2010-04-17 00:19:56 +00002280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002281PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002282"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002283
Guido van Rossum79f25d91997-04-29 20:08:16 +00002284static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002285 _IMP_EXTENSION_SUFFIXES_METHODDEF
2286 _IMP_LOCK_HELD_METHODDEF
2287 _IMP_ACQUIRE_LOCK_METHODDEF
2288 _IMP_RELEASE_LOCK_METHODDEF
2289 _IMP_GET_FROZEN_OBJECT_METHODDEF
2290 _IMP_IS_FROZEN_PACKAGE_METHODDEF
2291 _IMP_INIT_BUILTIN_METHODDEF
2292 _IMP_INIT_FROZEN_METHODDEF
2293 _IMP_IS_BUILTIN_METHODDEF
2294 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002295 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002296 _IMP__FIX_CO_FILENAME_METHODDEF
2297 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002298};
2299
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002300
Martin v. Löwis1a214512008-06-11 05:26:20 +00002301static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002303 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 doc_imp,
2305 0,
2306 imp_methods,
2307 NULL,
2308 NULL,
2309 NULL,
2310 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002311};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002312
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002313PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002314PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 m = PyModule_Create(&impmodule);
2319 if (m == NULL)
2320 goto failure;
2321 d = PyModule_GetDict(m);
2322 if (d == NULL)
2323 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002326 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 Py_XDECREF(m);
2328 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002329}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002330
2331
Guido van Rossumb18618d2000-05-03 23:44:39 +00002332/* API for embedding applications that want to add their own entries
2333 to the table of built-in modules. This should normally be called
2334 *before* Py_Initialize(). When the table resize fails, -1 is
2335 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002336
2337 After a similar function by Just van Rossum. */
2338
2339int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002340PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 static struct _inittab *our_copy = NULL;
2343 struct _inittab *p;
2344 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* Count the number of entries in both tables */
2347 for (n = 0; newtab[n].name != NULL; n++)
2348 ;
2349 if (n == 0)
2350 return 0; /* Nothing to do */
2351 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2352 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* Allocate new memory for the combined table */
2355 p = our_copy;
2356 PyMem_RESIZE(p, struct _inittab, i+n+1);
2357 if (p == NULL)
2358 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 /* Copy the tables into the new memory */
2361 if (our_copy != PyImport_Inittab)
2362 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2363 PyImport_Inittab = our_copy = p;
2364 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002367}
2368
2369/* Shorthand to add a single entry given a name and a function */
2370
2371int
Brett Cannona826f322009-04-02 03:41:46 +00002372PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 newtab[0].name = (char *)name;
2379 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002382}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002383
2384#ifdef __cplusplus
2385}
2386#endif
Larry Hastings7726ac92014-01-31 22:03:12 -08002387