blob: 0e26ffcd94b17af55256d23edec6cad3ba9bfa4a [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
859 return d;
860}
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{
891 PyObject *d, *v;
892
893 d = module_dict_for_exec(name);
894 if (d == NULL) {
895 return NULL;
896 }
897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (pathname != NULL) {
Brett Cannona6473f92012-07-13 13:57:03 -0400899 v = pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 }
Brett Cannona6473f92012-07-13 13:57:03 -0400901 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 v = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 }
Brett Cannona6473f92012-07-13 13:57:03 -0400904 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (PyDict_SetItemString(d, "__file__", v) != 0)
906 PyErr_Clear(); /* Not important enough to report */
907 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000910 if (cpathname != NULL)
911 v = cpathname;
912 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (PyDict_SetItemString(d, "__cached__", v) != 0)
915 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000916
Brett Cannon18fc4e72014-04-04 10:01:46 -0400917 return exec_code_in_module(name, d, co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000918}
919
920
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000921static void
922update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *constants, *tmp;
925 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (PyUnicode_Compare(co->co_filename, oldname))
928 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 tmp = co->co_filename;
931 co->co_filename = newname;
932 Py_INCREF(co->co_filename);
933 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 constants = co->co_consts;
936 n = PyTuple_GET_SIZE(constants);
937 for (i = 0; i < n; i++) {
938 tmp = PyTuple_GET_ITEM(constants, i);
939 if (PyCode_Check(tmp))
940 update_code_filenames((PyCodeObject *)tmp,
941 oldname, newname);
942 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000943}
944
Victor Stinner2f42ae52011-03-20 00:41:24 +0100945static void
946update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000947{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100948 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000949
Victor Stinner2f42ae52011-03-20 00:41:24 +0100950 if (PyUnicode_Compare(co->co_filename, newname) == 0)
951 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 oldname = co->co_filename;
954 Py_INCREF(oldname);
955 update_code_filenames(co, oldname, newname);
956 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000957}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000958
Brett Cannon4caa61d2014-01-09 19:03:32 -0500959/*[clinic input]
960_imp._fix_co_filename
961
962 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
963 Code object to change.
964
965 path: unicode
966 File path to use.
967 /
968
969Changes code.co_filename to specify the passed-in file path.
970[clinic start generated code]*/
971
972PyDoc_STRVAR(_imp__fix_co_filename__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800973"_fix_co_filename($module, code, path, /)\n"
974"--\n"
975"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500976"Changes code.co_filename to specify the passed-in file path.\n"
977"\n"
978" code\n"
979" Code object to change.\n"
980" path\n"
981" File path to use.");
982
983#define _IMP__FIX_CO_FILENAME_METHODDEF \
984 {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_VARARGS, _imp__fix_co_filename__doc__},
985
Brett Cannon442c9b92011-03-23 16:14:42 -0700986static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500987_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path);
988
989static PyObject *
990_imp__fix_co_filename(PyModuleDef *module, PyObject *args)
Brett Cannon442c9b92011-03-23 16:14:42 -0700991{
Brett Cannon4caa61d2014-01-09 19:03:32 -0500992 PyObject *return_value = NULL;
993 PyCodeObject *code;
994 PyObject *path;
Brett Cannon442c9b92011-03-23 16:14:42 -0700995
Brett Cannon4caa61d2014-01-09 19:03:32 -0500996 if (!PyArg_ParseTuple(args,
997 "O!U:_fix_co_filename",
998 &PyCode_Type, &code, &path))
999 goto exit;
1000 return_value = _imp__fix_co_filename_impl(module, code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001001
Brett Cannon4caa61d2014-01-09 19:03:32 -05001002exit:
1003 return return_value;
1004}
Brett Cannon442c9b92011-03-23 16:14:42 -07001005
Brett Cannon4caa61d2014-01-09 19:03:32 -05001006static PyObject *
1007_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001008/*[clinic end generated code: output=6b4b1edeb0d55c5d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001009
Brett Cannon4caa61d2014-01-09 19:03:32 -05001010{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001011 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001012
1013 Py_RETURN_NONE;
1014}
1015
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001016
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001018static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001019
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001020
1021/* Helper to test for built-in module */
1022
1023static int
Victor Stinner95872862011-03-07 18:20:56 +01001024is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001025{
Victor Stinner95872862011-03-07 18:20:56 +01001026 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001028 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1029 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (PyImport_Inittab[i].initfunc == NULL)
1031 return -1;
1032 else
1033 return 1;
1034 }
1035 }
1036 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001037}
1038
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001039
Just van Rossum52e14d62002-12-30 22:08:05 +00001040/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1041 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001042 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001043 that can handle the path item. Return None if no hook could;
1044 this tells our caller it should fall back to the builtin
1045 import mechanism. Cache the result in path_importer_cache.
1046 Returns a borrowed reference. */
1047
1048static PyObject *
1049get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyObject *importer;
1053 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 /* These conditions are the caller's responsibility: */
1056 assert(PyList_Check(path_hooks));
1057 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 nhooks = PyList_Size(path_hooks);
1060 if (nhooks < 0)
1061 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 importer = PyDict_GetItem(path_importer_cache, p);
1064 if (importer != NULL)
1065 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 /* set path_importer_cache[p] to None to avoid recursion */
1068 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1069 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 for (j = 0; j < nhooks; j++) {
1072 PyObject *hook = PyList_GetItem(path_hooks, j);
1073 if (hook == NULL)
1074 return NULL;
1075 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1076 if (importer != NULL)
1077 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1080 return NULL;
1081 }
1082 PyErr_Clear();
1083 }
1084 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001085 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
1087 if (importer != NULL) {
1088 int err = PyDict_SetItem(path_importer_cache, p, importer);
1089 Py_DECREF(importer);
1090 if (err != 0)
1091 return NULL;
1092 }
1093 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001094}
1095
Christian Heimes9cd17752007-11-18 19:35:23 +00001096PyAPI_FUNC(PyObject *)
1097PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001099
Victor Stinner1e53bba2013-07-16 22:26:05 +02001100 path_importer_cache = PySys_GetObject("path_importer_cache");
1101 path_hooks = PySys_GetObject("path_hooks");
1102 if (path_importer_cache != NULL && path_hooks != NULL) {
1103 importer = get_path_importer(path_importer_cache,
1104 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 }
1106 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1107 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001108}
1109
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001110
Victor Stinner95872862011-03-07 18:20:56 +01001111static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001112
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001113/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001114 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001115 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001116
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001117static int
Victor Stinner95872862011-03-07 18:20:56 +01001118init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001121 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001122
Victor Stinner5eb4f592013-11-14 22:38:52 +01001123 mod = _PyImport_FindExtensionObject(name, name);
1124 if (PyErr_Occurred())
1125 return -1;
1126 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 for (p = PyImport_Inittab; p->name != NULL; p++) {
1130 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001131 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001132 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (p->initfunc == NULL) {
1134 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001135 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 name);
1137 return -1;
1138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 mod = (*p->initfunc)();
1140 if (mod == 0)
1141 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001142 /* Remember pointer to module init function. */
1143 def = PyModule_GetDef(mod);
1144 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001145 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return -1;
1147 /* FixupExtension has put the module into sys.modules,
1148 so we can release our own reference. */
1149 Py_DECREF(mod);
1150 return 1;
1151 }
1152 }
1153 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001154}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001155
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001156
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001157/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001158
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001159static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001160find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001161{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001162 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001163
Victor Stinner53dc7352011-03-20 01:50:21 +01001164 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 for (p = PyImport_FrozenModules; ; p++) {
1168 if (p->name == NULL)
1169 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001170 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 break;
1172 }
1173 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001174}
1175
Guido van Rossum79f25d91997-04-29 20:08:16 +00001176static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001177get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001178{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001179 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (p == NULL) {
1183 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001184 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 name);
1186 return NULL;
1187 }
1188 if (p->code == NULL) {
1189 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001190 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 name);
1192 return NULL;
1193 }
1194 size = p->size;
1195 if (size < 0)
1196 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001197 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001198}
1199
Brett Cannon8d110132009-03-15 02:20:16 +00001200static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001201is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001202{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001203 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (p == NULL) {
1207 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001208 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 name);
1210 return NULL;
1211 }
Brett Cannon8d110132009-03-15 02:20:16 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (size < 0)
1216 Py_RETURN_TRUE;
1217 else
1218 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001219}
1220
1221
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001222/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001223 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001224 an exception set if the initialization failed.
1225 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001226
1227int
Victor Stinner53dc7352011-03-20 01:50:21 +01001228PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001229{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001230 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001231 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 int ispackage;
1233 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001234
Victor Stinner53dc7352011-03-20 01:50:21 +01001235 p = find_frozen(name);
1236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (p == NULL)
1238 return 0;
1239 if (p->code == NULL) {
1240 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001241 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 name);
1243 return -1;
1244 }
1245 size = p->size;
1246 ispackage = (size < 0);
1247 if (ispackage)
1248 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001249 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (co == NULL)
1251 return -1;
1252 if (!PyCode_Check(co)) {
1253 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001254 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 name);
1256 goto err_return;
1257 }
1258 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001259 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001260 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001262 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (m == NULL)
1264 goto err_return;
1265 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001266 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 goto err_return;
1269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 err = PyDict_SetItemString(d, "__path__", l);
1271 Py_DECREF(l);
1272 if (err != 0)
1273 goto err_return;
1274 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001275 d = module_dict_for_exec(name);
1276 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001277 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001278 }
1279 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (m == NULL)
1281 goto err_return;
1282 Py_DECREF(co);
1283 Py_DECREF(m);
1284 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001285err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 Py_DECREF(co);
1287 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001288}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001289
Victor Stinner53dc7352011-03-20 01:50:21 +01001290int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001291PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001292{
1293 PyObject *nameobj;
1294 int ret;
1295 nameobj = PyUnicode_InternFromString(name);
1296 if (nameobj == NULL)
1297 return -1;
1298 ret = PyImport_ImportFrozenModuleObject(nameobj);
1299 Py_DECREF(nameobj);
1300 return ret;
1301}
1302
Guido van Rossum74e6a111994-08-29 12:54:38 +00001303
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001304/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001305 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001306
Guido van Rossum79f25d91997-04-29 20:08:16 +00001307PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001308PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 PyObject *pname;
1311 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 pname = PyUnicode_FromString(name);
1314 if (pname == NULL)
1315 return NULL;
1316 result = PyImport_Import(pname);
1317 Py_DECREF(pname);
1318 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001319}
1320
Christian Heimes072c0f12008-01-03 23:01:04 +00001321/* Import a module without blocking
1322 *
1323 * At first it tries to fetch the module from sys.modules. If the module was
1324 * never loaded before it loads it with PyImport_ImportModule() unless another
1325 * thread holds the import lock. In the latter case the function raises an
1326 * ImportError instead of blocking.
1327 *
1328 * Returns the module object with incremented ref count.
1329 */
1330PyObject *
1331PyImport_ImportModuleNoBlock(const char *name)
1332{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001333 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001334}
1335
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001336
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001337/* Remove importlib frames from the traceback,
1338 * except in Verbose mode. */
1339static void
1340remove_importlib_frames(void)
1341{
1342 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001343 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001344 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001345 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001346 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001347 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001348
1349 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001350 from the traceback. We always trim chunks
1351 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001352
1353 PyErr_Fetch(&exception, &value, &base_tb);
1354 if (!exception || Py_VerboseFlag)
1355 goto done;
1356 if (PyType_IsSubtype((PyTypeObject *) exception,
1357 (PyTypeObject *) PyExc_ImportError))
1358 always_trim = 1;
1359
1360 prev_link = &base_tb;
1361 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001362 while (tb != NULL) {
1363 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1364 PyObject *next = (PyObject *) traceback->tb_next;
1365 PyFrameObject *frame = traceback->tb_frame;
1366 PyCodeObject *code = frame->f_code;
1367 int now_in_importlib;
1368
1369 assert(PyTraceBack_Check(tb));
1370 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1371 code->co_filename,
1372 importlib_filename) == 0);
1373 if (now_in_importlib && !in_importlib) {
1374 /* This is the link to this chunk of importlib tracebacks */
1375 outer_link = prev_link;
1376 }
1377 in_importlib = now_in_importlib;
1378
1379 if (in_importlib &&
1380 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001381 PyUnicode_CompareWithASCIIString(code->co_name,
1382 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001383 PyObject *tmp = *outer_link;
1384 *outer_link = next;
1385 Py_XINCREF(next);
1386 Py_DECREF(tmp);
1387 prev_link = outer_link;
1388 }
1389 else {
1390 prev_link = (PyObject **) &traceback->tb_next;
1391 }
1392 tb = next;
1393 }
1394done:
1395 PyErr_Restore(exception, value, base_tb);
1396}
1397
1398
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001399PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001400PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1401 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001402 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001403{
Brett Cannonfd074152012-04-14 14:10:13 -04001404 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001405 _Py_IDENTIFIER(__spec__);
1406 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001407 _Py_IDENTIFIER(__package__);
1408 _Py_IDENTIFIER(__path__);
1409 _Py_IDENTIFIER(__name__);
1410 _Py_IDENTIFIER(_find_and_load);
1411 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001412 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001413 _Py_static_string(single_dot, ".");
1414 PyObject *abs_name = NULL;
1415 PyObject *builtins_import = NULL;
1416 PyObject *final_mod = NULL;
1417 PyObject *mod = NULL;
1418 PyObject *package = NULL;
1419 PyObject *globals = NULL;
1420 PyObject *fromlist = NULL;
1421 PyInterpreterState *interp = PyThreadState_GET()->interp;
1422
1423 /* Make sure to use default values so as to not have
1424 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1425 NULL argument. */
1426 if (given_globals == NULL) {
1427 globals = PyDict_New();
1428 if (globals == NULL) {
1429 goto error;
1430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 }
Brett Cannonfd074152012-04-14 14:10:13 -04001432 else {
1433 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001434 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001435 if (level > 0 && !PyDict_Check(given_globals)) {
1436 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1437 goto error;
1438 }
1439 globals = given_globals;
1440 Py_INCREF(globals);
1441 }
1442
1443 if (given_fromlist == NULL) {
1444 fromlist = PyList_New(0);
1445 if (fromlist == NULL) {
1446 goto error;
1447 }
1448 }
1449 else {
1450 fromlist = given_fromlist;
1451 Py_INCREF(fromlist);
1452 }
1453 if (name == NULL) {
1454 PyErr_SetString(PyExc_ValueError, "Empty module name");
1455 goto error;
1456 }
1457
1458 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1459 for added performance. */
1460
1461 if (!PyUnicode_Check(name)) {
1462 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1463 goto error;
1464 }
1465 else if (PyUnicode_READY(name) < 0) {
1466 goto error;
1467 }
1468 if (level < 0) {
1469 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1470 goto error;
1471 }
1472 else if (level > 0) {
1473 package = _PyDict_GetItemId(globals, &PyId___package__);
1474 if (package != NULL && package != Py_None) {
1475 Py_INCREF(package);
1476 if (!PyUnicode_Check(package)) {
1477 PyErr_SetString(PyExc_TypeError, "package must be a string");
1478 goto error;
1479 }
1480 }
1481 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001482 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001483 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001484 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001485 goto error;
1486 }
1487 else if (!PyUnicode_Check(package)) {
1488 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1489 }
1490 Py_INCREF(package);
1491
1492 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001493 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001494 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1495 if (borrowed_dot == NULL) {
1496 goto error;
1497 }
Brett Cannon740fce02012-04-14 14:23:49 -04001498 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001499 Py_DECREF(package);
1500 if (partition == NULL) {
1501 goto error;
1502 }
1503 package = PyTuple_GET_ITEM(partition, 0);
1504 Py_INCREF(package);
1505 Py_DECREF(partition);
1506 }
1507 }
1508
1509 if (PyDict_GetItem(interp->modules, package) == NULL) {
1510 PyErr_Format(PyExc_SystemError,
1511 "Parent module %R not loaded, cannot perform relative "
1512 "import", package);
1513 goto error;
1514 }
1515 }
1516 else { /* level == 0 */
1517 if (PyUnicode_GET_LENGTH(name) == 0) {
1518 PyErr_SetString(PyExc_ValueError, "Empty module name");
1519 goto error;
1520 }
1521 package = Py_None;
1522 Py_INCREF(package);
1523 }
1524
1525 if (level > 0) {
1526 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1527 PyObject *base = NULL;
1528 int level_up = 1;
1529
1530 for (level_up = 1; level_up < level; level_up += 1) {
1531 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1532 if (last_dot == -2) {
1533 goto error;
1534 }
1535 else if (last_dot == -1) {
1536 PyErr_SetString(PyExc_ValueError,
1537 "attempted relative import beyond top-level "
1538 "package");
1539 goto error;
1540 }
1541 }
Victor Stinner22af2592013-11-13 12:11:36 +01001542
Brett Cannonfd074152012-04-14 14:10:13 -04001543 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001544 if (base == NULL)
1545 goto error;
1546
Brett Cannonfd074152012-04-14 14:10:13 -04001547 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001548 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001549
1550 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001551 seq = PyTuple_Pack(2, base, name);
1552 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001553 if (borrowed_dot == NULL || seq == NULL) {
1554 goto error;
1555 }
1556
1557 abs_name = PyUnicode_Join(borrowed_dot, seq);
1558 Py_DECREF(seq);
1559 if (abs_name == NULL) {
1560 goto error;
1561 }
1562 }
1563 else {
1564 abs_name = base;
1565 }
1566 }
1567 else {
1568 abs_name = name;
1569 Py_INCREF(abs_name);
1570 }
1571
Brian Curtine6b299f2012-04-14 14:19:33 -05001572#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001573 _PyImport_AcquireLock();
1574#endif
1575 /* From this point forward, goto error_with_unlock! */
1576 if (PyDict_Check(globals)) {
1577 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1578 }
1579 if (builtins_import == NULL) {
1580 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1581 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001582 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1583 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001584 }
1585 }
1586 Py_INCREF(builtins_import);
1587
1588 mod = PyDict_GetItem(interp->modules, abs_name);
1589 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001590 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1591 "None in sys.modules", abs_name);
1592 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001593 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001594 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001595 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001596 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001597 goto error_with_unlock;
1598 }
1599 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001600 PyObject *value = NULL;
1601 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001602 int initializing = 0;
1603
Brett Cannonfd074152012-04-14 14:10:13 -04001604 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001605 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001606 __spec__._initializing is true.
1607 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001608 stuffing the new module in sys.modules.
1609 */
Eric Snowb523f842013-11-22 09:05:39 -07001610 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1611 if (spec != NULL) {
1612 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1613 Py_DECREF(spec);
1614 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001615 if (value == NULL)
1616 PyErr_Clear();
1617 else {
1618 initializing = PyObject_IsTrue(value);
1619 Py_DECREF(value);
1620 if (initializing == -1)
1621 PyErr_Clear();
1622 }
1623 if (initializing > 0) {
1624 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001625 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001626 &PyId__lock_unlock_module, abs_name,
1627 NULL);
1628 if (value == NULL)
1629 goto error;
1630 Py_DECREF(value);
1631 }
1632 else {
1633#ifdef WITH_THREAD
1634 if (_PyImport_ReleaseLock() < 0) {
1635 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1636 goto error;
1637 }
1638#endif
1639 }
Brett Cannonfd074152012-04-14 14:10:13 -04001640 }
1641 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001642 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001643 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001644 &PyId__find_and_load, abs_name,
1645 builtins_import, NULL);
1646 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001647 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001648 }
1649 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001650 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001651
1652 if (PyObject_Not(fromlist)) {
1653 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1654 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001655 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001656 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1657
1658 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001659 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001660 }
1661
Brian Curtine6b299f2012-04-14 14:19:33 -05001662 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001663 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001664 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001665 }
1666
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001667 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1668 /* No dot in module name, simple exit */
1669 Py_DECREF(partition);
1670 final_mod = mod;
1671 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001672 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001673 }
1674
Brett Cannonfd074152012-04-14 14:10:13 -04001675 front = PyTuple_GET_ITEM(partition, 0);
1676 Py_INCREF(front);
1677 Py_DECREF(partition);
1678
1679 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001680 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001681 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001682 }
1683 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001684 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1685 PyUnicode_GET_LENGTH(front);
1686 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001687 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001688 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001689 Py_DECREF(front);
1690 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001691 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001692 }
Brett Cannonfd074152012-04-14 14:10:13 -04001693
1694 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001695 if (final_mod == NULL) {
1696 PyErr_Format(PyExc_KeyError,
1697 "%R not in sys.modules as expected",
1698 to_return);
1699 }
1700 else {
1701 Py_INCREF(final_mod);
1702 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001703 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001704 }
1705 }
1706 else {
1707 final_mod = mod;
1708 Py_INCREF(mod);
1709 }
1710 }
1711 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001712 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001713 &PyId__handle_fromlist, mod,
1714 fromlist, builtins_import,
1715 NULL);
1716 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001717 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001718
Brett Cannonfd074152012-04-14 14:10:13 -04001719 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001720#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001721 if (_PyImport_ReleaseLock() < 0) {
1722 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1723 }
1724#endif
1725 error:
1726 Py_XDECREF(abs_name);
1727 Py_XDECREF(builtins_import);
1728 Py_XDECREF(mod);
1729 Py_XDECREF(package);
1730 Py_XDECREF(globals);
1731 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001732 if (final_mod == NULL)
1733 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001734 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001735}
1736
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001737PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001738PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001739 PyObject *fromlist, int level)
1740{
1741 PyObject *nameobj, *mod;
1742 nameobj = PyUnicode_FromString(name);
1743 if (nameobj == NULL)
1744 return NULL;
1745 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1746 fromlist, level);
1747 Py_DECREF(nameobj);
1748 return mod;
1749}
1750
1751
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001752/* Re-import a module of any kind and return its module object, WITH
1753 INCREMENTED REFERENCE COUNT */
1754
Guido van Rossum79f25d91997-04-29 20:08:16 +00001755PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001756PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001757{
Brett Cannon62228db2012-04-29 14:38:11 -04001758 _Py_IDENTIFIER(reload);
1759 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001761 PyObject *imp = PyDict_GetItemString(modules, "imp");
1762 if (imp == NULL) {
1763 imp = PyImport_ImportModule("imp");
1764 if (imp == NULL) {
1765 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Brett Cannon62228db2012-04-29 14:38:11 -04001768 else {
1769 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001771
Brett Cannon62228db2012-04-29 14:38:11 -04001772 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1773 Py_DECREF(imp);
1774 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001775}
1776
1777
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001778/* Higher-level import emulator which emulates the "import" statement
1779 more accurately -- it invokes the __import__() function from the
1780 builtins of the current globals. This means that the import is
1781 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001782 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001783 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001784 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001785 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001786
1787PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001788PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 static PyObject *silly_list = NULL;
1791 static PyObject *builtins_str = NULL;
1792 static PyObject *import_str = NULL;
1793 PyObject *globals = NULL;
1794 PyObject *import = NULL;
1795 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001796 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 /* Initialize constant string objects */
1800 if (silly_list == NULL) {
1801 import_str = PyUnicode_InternFromString("__import__");
1802 if (import_str == NULL)
1803 return NULL;
1804 builtins_str = PyUnicode_InternFromString("__builtins__");
1805 if (builtins_str == NULL)
1806 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001807 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (silly_list == NULL)
1809 return NULL;
1810 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* Get the builtins from current globals */
1813 globals = PyEval_GetGlobals();
1814 if (globals != NULL) {
1815 Py_INCREF(globals);
1816 builtins = PyObject_GetItem(globals, builtins_str);
1817 if (builtins == NULL)
1818 goto err;
1819 }
1820 else {
1821 /* No globals -- use standard builtins, and fake globals */
1822 builtins = PyImport_ImportModuleLevel("builtins",
1823 NULL, NULL, NULL, 0);
1824 if (builtins == NULL)
1825 return NULL;
1826 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1827 if (globals == NULL)
1828 goto err;
1829 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 /* Get the __import__ function from the builtins */
1832 if (PyDict_Check(builtins)) {
1833 import = PyObject_GetItem(builtins, import_str);
1834 if (import == NULL)
1835 PyErr_SetObject(PyExc_KeyError, import_str);
1836 }
1837 else
1838 import = PyObject_GetAttr(builtins, import_str);
1839 if (import == NULL)
1840 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001843 Always use absolute import here.
1844 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1846 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001847 if (r == NULL)
1848 goto err;
1849 Py_DECREF(r);
1850
1851 modules = PyImport_GetModuleDict();
1852 r = PyDict_GetItem(modules, module_name);
1853 if (r != NULL)
1854 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001855
1856 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 Py_XDECREF(globals);
1858 Py_XDECREF(builtins);
1859 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001862}
1863
Brett Cannon4caa61d2014-01-09 19:03:32 -05001864/*[clinic input]
1865_imp.extension_suffixes
1866
1867Returns the list of file suffixes used to identify extension modules.
1868[clinic start generated code]*/
1869
1870PyDoc_STRVAR(_imp_extension_suffixes__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001871"extension_suffixes($module, /)\n"
1872"--\n"
1873"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001874"Returns the list of file suffixes used to identify extension modules.");
1875
1876#define _IMP_EXTENSION_SUFFIXES_METHODDEF \
1877 {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
1878
Barry Warsaw28a691b2010-04-17 00:19:56 +00001879static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001880_imp_extension_suffixes_impl(PyModuleDef *module);
1881
1882static PyObject *
1883_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1884{
Larry Hastingsbebf7352014-01-17 17:47:17 -08001885 return _imp_extension_suffixes_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001886}
1887
1888static PyObject *
1889_imp_extension_suffixes_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001890/*[clinic end generated code: output=bb30a2438167798c input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001893 const char *suffix;
1894 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 list = PyList_New(0);
1897 if (list == NULL)
1898 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001899#ifdef HAVE_DYNAMIC_LOADING
1900 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1901 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 if (item == NULL) {
1903 Py_DECREF(list);
1904 return NULL;
1905 }
1906 if (PyList_Append(list, item) < 0) {
1907 Py_DECREF(list);
1908 Py_DECREF(item);
1909 return NULL;
1910 }
1911 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001912 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 }
Brett Cannon2657df42012-05-04 15:20:40 -04001914#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001916}
1917
Brett Cannon4caa61d2014-01-09 19:03:32 -05001918/*[clinic input]
1919_imp.init_builtin
1920
1921 name: unicode
1922 /
1923
1924Initializes a built-in module.
1925[clinic start generated code]*/
1926
1927PyDoc_STRVAR(_imp_init_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001928"init_builtin($module, name, /)\n"
1929"--\n"
1930"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001931"Initializes a built-in module.");
1932
1933#define _IMP_INIT_BUILTIN_METHODDEF \
1934 {"init_builtin", (PyCFunction)_imp_init_builtin, METH_VARARGS, _imp_init_builtin__doc__},
1935
Guido van Rossum79f25d91997-04-29 20:08:16 +00001936static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001937_imp_init_builtin_impl(PyModuleDef *module, PyObject *name);
1938
1939static PyObject *
1940_imp_init_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001941{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001942 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01001943 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001944
1945 if (!PyArg_ParseTuple(args,
1946 "U:init_builtin",
1947 &name))
1948 goto exit;
1949 return_value = _imp_init_builtin_impl(module, name);
1950
1951exit:
1952 return return_value;
1953}
1954
1955static PyObject *
1956_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001957/*[clinic end generated code: output=a0244948a43f8e26 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 int ret;
1960 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 ret = init_builtin(name);
1963 if (ret < 0)
1964 return NULL;
1965 if (ret == 0) {
1966 Py_INCREF(Py_None);
1967 return Py_None;
1968 }
Victor Stinner95872862011-03-07 18:20:56 +01001969 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 Py_XINCREF(m);
1971 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001972}
1973
Brett Cannon4caa61d2014-01-09 19:03:32 -05001974/*[clinic input]
1975_imp.init_frozen
1976
1977 name: unicode
1978 /
1979
1980Initializes a frozen module.
1981[clinic start generated code]*/
1982
1983PyDoc_STRVAR(_imp_init_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001984"init_frozen($module, name, /)\n"
1985"--\n"
1986"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001987"Initializes a frozen module.");
1988
1989#define _IMP_INIT_FROZEN_METHODDEF \
1990 {"init_frozen", (PyCFunction)_imp_init_frozen, METH_VARARGS, _imp_init_frozen__doc__},
1991
Guido van Rossum79f25d91997-04-29 20:08:16 +00001992static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001993_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
1994
1995static PyObject *
1996_imp_init_frozen(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001997{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001998 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001999 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002000
2001 if (!PyArg_ParseTuple(args,
2002 "U:init_frozen",
2003 &name))
2004 goto exit;
2005 return_value = _imp_init_frozen_impl(module, name);
2006
2007exit:
2008 return return_value;
2009}
2010
2011static PyObject *
2012_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002013/*[clinic end generated code: output=e4bc2bff296f8f22 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 int ret;
2016 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002017
Victor Stinner53dc7352011-03-20 01:50:21 +01002018 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 if (ret < 0)
2020 return NULL;
2021 if (ret == 0) {
2022 Py_INCREF(Py_None);
2023 return Py_None;
2024 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002025 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 Py_XINCREF(m);
2027 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002028}
2029
Brett Cannon4caa61d2014-01-09 19:03:32 -05002030/*[clinic input]
2031_imp.get_frozen_object
2032
2033 name: unicode
2034 /
2035
2036Create a code object for a frozen module.
2037[clinic start generated code]*/
2038
2039PyDoc_STRVAR(_imp_get_frozen_object__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002040"get_frozen_object($module, name, /)\n"
2041"--\n"
2042"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002043"Create a code object for a frozen module.");
2044
2045#define _IMP_GET_FROZEN_OBJECT_METHODDEF \
2046 {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_VARARGS, _imp_get_frozen_object__doc__},
2047
Guido van Rossum79f25d91997-04-29 20:08:16 +00002048static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002049_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
2050
2051static PyObject *
2052_imp_get_frozen_object(PyModuleDef *module, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002053{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002054 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002055 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002056
Brett Cannon4caa61d2014-01-09 19:03:32 -05002057 if (!PyArg_ParseTuple(args,
2058 "U:get_frozen_object",
2059 &name))
2060 goto exit;
2061 return_value = _imp_get_frozen_object_impl(module, name);
2062
2063exit:
2064 return return_value;
2065}
2066
2067static PyObject *
2068_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002069/*[clinic end generated code: output=4089ec702a9d70c5 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002072}
2073
Brett Cannon4caa61d2014-01-09 19:03:32 -05002074/*[clinic input]
2075_imp.is_frozen_package
2076
2077 name: unicode
2078 /
2079
2080Returns True if the module name is of a frozen package.
2081[clinic start generated code]*/
2082
2083PyDoc_STRVAR(_imp_is_frozen_package__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002084"is_frozen_package($module, name, /)\n"
2085"--\n"
2086"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002087"Returns True if the module name is of a frozen package.");
2088
2089#define _IMP_IS_FROZEN_PACKAGE_METHODDEF \
2090 {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_VARARGS, _imp_is_frozen_package__doc__},
2091
Guido van Rossum79f25d91997-04-29 20:08:16 +00002092static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002093_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
2094
2095static PyObject *
2096_imp_is_frozen_package(PyModuleDef *module, PyObject *args)
Brett Cannon8d110132009-03-15 02:20:16 +00002097{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002098 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002099 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002100
Brett Cannon4caa61d2014-01-09 19:03:32 -05002101 if (!PyArg_ParseTuple(args,
2102 "U:is_frozen_package",
2103 &name))
2104 goto exit;
2105 return_value = _imp_is_frozen_package_impl(module, name);
2106
2107exit:
2108 return return_value;
2109}
2110
2111static PyObject *
2112_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002113/*[clinic end generated code: output=86aab14dcd4b959b input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002116}
2117
Brett Cannon4caa61d2014-01-09 19:03:32 -05002118/*[clinic input]
2119_imp.is_builtin
2120
2121 name: unicode
2122 /
2123
2124Returns True if the module name corresponds to a built-in module.
2125[clinic start generated code]*/
2126
2127PyDoc_STRVAR(_imp_is_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002128"is_builtin($module, name, /)\n"
2129"--\n"
2130"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002131"Returns True if the module name corresponds to a built-in module.");
2132
2133#define _IMP_IS_BUILTIN_METHODDEF \
2134 {"is_builtin", (PyCFunction)_imp_is_builtin, METH_VARARGS, _imp_is_builtin__doc__},
2135
Brett Cannon8d110132009-03-15 02:20:16 +00002136static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002137_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
2138
2139static PyObject *
2140_imp_is_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002141{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002142 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01002143 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002144
2145 if (!PyArg_ParseTuple(args,
2146 "U:is_builtin",
2147 &name))
2148 goto exit;
2149 return_value = _imp_is_builtin_impl(module, name);
2150
2151exit:
2152 return return_value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002153}
2154
Guido van Rossum79f25d91997-04-29 20:08:16 +00002155static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002156_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002157/*[clinic end generated code: output=d5847f8cac50946e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002158{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002159 return PyLong_FromLong(is_builtin(name));
2160}
2161
2162/*[clinic input]
2163_imp.is_frozen
2164
2165 name: unicode
2166 /
2167
2168Returns True if the module name corresponds to a frozen module.
2169[clinic start generated code]*/
2170
2171PyDoc_STRVAR(_imp_is_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002172"is_frozen($module, name, /)\n"
2173"--\n"
2174"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002175"Returns True if the module name corresponds to a frozen module.");
2176
2177#define _IMP_IS_FROZEN_METHODDEF \
2178 {"is_frozen", (PyCFunction)_imp_is_frozen, METH_VARARGS, _imp_is_frozen__doc__},
2179
2180static PyObject *
2181_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
2182
2183static PyObject *
2184_imp_is_frozen(PyModuleDef *module, PyObject *args)
2185{
2186 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002187 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002188
2189 if (!PyArg_ParseTuple(args,
2190 "U:is_frozen",
2191 &name))
2192 goto exit;
2193 return_value = _imp_is_frozen_impl(module, name);
2194
2195exit:
2196 return return_value;
2197}
2198
2199static PyObject *
2200_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002201/*[clinic end generated code: output=6691af884ba4987d input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002202{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002203 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 p = find_frozen(name);
2206 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002207}
2208
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002209#ifdef HAVE_DYNAMIC_LOADING
2210
Brett Cannon4caa61d2014-01-09 19:03:32 -05002211/*[clinic input]
2212_imp.load_dynamic
2213
2214 name: unicode
2215 path: fs_unicode
2216 file: object = NULL
2217 /
2218
2219Loads an extension module.
2220[clinic start generated code]*/
2221
2222PyDoc_STRVAR(_imp_load_dynamic__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002223"load_dynamic($module, name, path, file=None, /)\n"
2224"--\n"
2225"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002226"Loads an extension module.");
2227
2228#define _IMP_LOAD_DYNAMIC_METHODDEF \
2229 {"load_dynamic", (PyCFunction)_imp_load_dynamic, METH_VARARGS, _imp_load_dynamic__doc__},
2230
Guido van Rossum79f25d91997-04-29 20:08:16 +00002231static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002232_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file);
2233
2234static PyObject *
2235_imp_load_dynamic(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002236{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002237 PyObject *return_value = NULL;
2238 PyObject *name;
2239 PyObject *path;
2240 PyObject *file = NULL;
2241
2242 if (!PyArg_ParseTuple(args,
2243 "UO&|O:load_dynamic",
2244 &name, PyUnicode_FSDecoder, &path, &file))
2245 goto exit;
2246 return_value = _imp_load_dynamic_impl(module, name, path, file);
2247
2248exit:
2249 return return_value;
2250}
2251
2252static PyObject *
2253_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002254/*[clinic end generated code: output=81d11a1fbd1ea0a8 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002255{
2256 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002257 FILE *fp;
2258
Brett Cannon4caa61d2014-01-09 19:03:32 -05002259 if (file != NULL) {
2260 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002261 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002262 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002263 if (!PyErr_Occurred())
2264 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002268 else
2269 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002270 mod = _PyImport_LoadDynamicModule(name, path, fp);
2271 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (fp)
2273 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002274 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002275}
2276
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002277#endif /* HAVE_DYNAMIC_LOADING */
2278
Larry Hastings7726ac92014-01-31 22:03:12 -08002279/*[clinic input]
2280dump buffer
2281[clinic start generated code]*/
2282
2283#ifndef _IMP_LOAD_DYNAMIC_METHODDEF
2284 #define _IMP_LOAD_DYNAMIC_METHODDEF
2285#endif /* !defined(_IMP_LOAD_DYNAMIC_METHODDEF) */
2286/*[clinic end generated code: output=d07c1d4a343a9579 input=524ce2e021e4eba6]*/
2287
Barry Warsaw28a691b2010-04-17 00:19:56 +00002288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002289PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002290"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002291
Guido van Rossum79f25d91997-04-29 20:08:16 +00002292static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002293 _IMP_EXTENSION_SUFFIXES_METHODDEF
2294 _IMP_LOCK_HELD_METHODDEF
2295 _IMP_ACQUIRE_LOCK_METHODDEF
2296 _IMP_RELEASE_LOCK_METHODDEF
2297 _IMP_GET_FROZEN_OBJECT_METHODDEF
2298 _IMP_IS_FROZEN_PACKAGE_METHODDEF
2299 _IMP_INIT_BUILTIN_METHODDEF
2300 _IMP_INIT_FROZEN_METHODDEF
2301 _IMP_IS_BUILTIN_METHODDEF
2302 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002303 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002304 _IMP__FIX_CO_FILENAME_METHODDEF
2305 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002306};
2307
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002308
Martin v. Löwis1a214512008-06-11 05:26:20 +00002309static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002311 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 doc_imp,
2313 0,
2314 imp_methods,
2315 NULL,
2316 NULL,
2317 NULL,
2318 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002319};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002320
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002321PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002322PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 m = PyModule_Create(&impmodule);
2327 if (m == NULL)
2328 goto failure;
2329 d = PyModule_GetDict(m);
2330 if (d == NULL)
2331 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002334 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 Py_XDECREF(m);
2336 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002337}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002338
2339
Guido van Rossumb18618d2000-05-03 23:44:39 +00002340/* API for embedding applications that want to add their own entries
2341 to the table of built-in modules. This should normally be called
2342 *before* Py_Initialize(). When the table resize fails, -1 is
2343 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002344
2345 After a similar function by Just van Rossum. */
2346
2347int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002348PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 static struct _inittab *our_copy = NULL;
2351 struct _inittab *p;
2352 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* Count the number of entries in both tables */
2355 for (n = 0; newtab[n].name != NULL; n++)
2356 ;
2357 if (n == 0)
2358 return 0; /* Nothing to do */
2359 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2360 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 /* Allocate new memory for the combined table */
2363 p = our_copy;
2364 PyMem_RESIZE(p, struct _inittab, i+n+1);
2365 if (p == NULL)
2366 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* Copy the tables into the new memory */
2369 if (our_copy != PyImport_Inittab)
2370 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2371 PyImport_Inittab = our_copy = p;
2372 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002375}
2376
2377/* Shorthand to add a single entry given a name and a function */
2378
2379int
Brett Cannona826f322009-04-02 03:41:46 +00002380PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 newtab[0].name = (char *)name;
2387 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002390}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002391
2392#ifdef __cplusplus
2393}
2394#endif
Larry Hastings7726ac92014-01-31 22:03:12 -08002395