blob: 7972f8612f7e2b5ff03d40729768a4ce6f8146f0 [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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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 Storchaka87a5c512014-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
840PyObject*
841PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
842 PyObject *cpathname)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 PyObject *modules = PyImport_GetModuleDict();
845 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000846
Victor Stinner27ee0892011-03-04 12:57:09 +0000847 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (m == NULL)
849 return NULL;
850 /* If the module is being reloaded, we get the old module back
851 and re-use its dict to exec the new code. */
852 d = PyModule_GetDict(m);
853 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
854 if (PyDict_SetItemString(d, "__builtins__",
855 PyEval_GetBuiltins()) != 0)
856 goto error;
857 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (pathname != NULL) {
Brett Cannona6473f92012-07-13 13:57:03 -0400859 v = pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 }
Brett Cannona6473f92012-07-13 13:57:03 -0400861 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 v = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 }
Brett Cannona6473f92012-07-13 13:57:03 -0400864 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (PyDict_SetItemString(d, "__file__", v) != 0)
866 PyErr_Clear(); /* Not important enough to report */
867 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000870 if (cpathname != NULL)
871 v = cpathname;
872 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (PyDict_SetItemString(d, "__cached__", v) != 0)
875 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000876
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000877 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (v == NULL)
879 goto error;
880 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000881
Victor Stinner27ee0892011-03-04 12:57:09 +0000882 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000884 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 name);
886 return NULL;
887 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000892
893 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 remove_module(name);
895 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000896}
897
898
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000899static void
900update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyObject *constants, *tmp;
903 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (PyUnicode_Compare(co->co_filename, oldname))
906 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 tmp = co->co_filename;
909 co->co_filename = newname;
910 Py_INCREF(co->co_filename);
911 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 constants = co->co_consts;
914 n = PyTuple_GET_SIZE(constants);
915 for (i = 0; i < n; i++) {
916 tmp = PyTuple_GET_ITEM(constants, i);
917 if (PyCode_Check(tmp))
918 update_code_filenames((PyCodeObject *)tmp,
919 oldname, newname);
920 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000921}
922
Victor Stinner2f42ae52011-03-20 00:41:24 +0100923static void
924update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000925{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100926 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000927
Victor Stinner2f42ae52011-03-20 00:41:24 +0100928 if (PyUnicode_Compare(co->co_filename, newname) == 0)
929 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 oldname = co->co_filename;
932 Py_INCREF(oldname);
933 update_code_filenames(co, oldname, newname);
934 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000935}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000936
Brett Cannon4caa61d2014-01-09 19:03:32 -0500937/*[clinic input]
938_imp._fix_co_filename
939
940 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
941 Code object to change.
942
943 path: unicode
944 File path to use.
945 /
946
947Changes code.co_filename to specify the passed-in file path.
948[clinic start generated code]*/
949
950PyDoc_STRVAR(_imp__fix_co_filename__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800951"_fix_co_filename($module, code, path, /)\n"
952"--\n"
953"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500954"Changes code.co_filename to specify the passed-in file path.\n"
955"\n"
956" code\n"
957" Code object to change.\n"
958" path\n"
959" File path to use.");
960
961#define _IMP__FIX_CO_FILENAME_METHODDEF \
962 {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_VARARGS, _imp__fix_co_filename__doc__},
963
Brett Cannon442c9b92011-03-23 16:14:42 -0700964static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500965_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path);
966
967static PyObject *
968_imp__fix_co_filename(PyModuleDef *module, PyObject *args)
Brett Cannon442c9b92011-03-23 16:14:42 -0700969{
Brett Cannon4caa61d2014-01-09 19:03:32 -0500970 PyObject *return_value = NULL;
971 PyCodeObject *code;
972 PyObject *path;
Brett Cannon442c9b92011-03-23 16:14:42 -0700973
Brett Cannon4caa61d2014-01-09 19:03:32 -0500974 if (!PyArg_ParseTuple(args,
975 "O!U:_fix_co_filename",
976 &PyCode_Type, &code, &path))
977 goto exit;
978 return_value = _imp__fix_co_filename_impl(module, code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700979
Brett Cannon4caa61d2014-01-09 19:03:32 -0500980exit:
981 return return_value;
982}
Brett Cannon442c9b92011-03-23 16:14:42 -0700983
Brett Cannon4caa61d2014-01-09 19:03:32 -0500984static PyObject *
985_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800986/*[clinic end generated code: output=6b4b1edeb0d55c5d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -0700987
Brett Cannon4caa61d2014-01-09 19:03:32 -0500988{
Brett Cannona6dec2e2014-01-10 07:43:55 -0500989 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700990
991 Py_RETURN_NONE;
992}
993
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000994
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000995/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -0700996static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000997
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000998
999/* Helper to test for built-in module */
1000
1001static int
Victor Stinner95872862011-03-07 18:20:56 +01001002is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001003{
Victor Stinner95872862011-03-07 18:20:56 +01001004 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001006 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1007 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (PyImport_Inittab[i].initfunc == NULL)
1009 return -1;
1010 else
1011 return 1;
1012 }
1013 }
1014 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001015}
1016
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017
Just van Rossum52e14d62002-12-30 22:08:05 +00001018/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1019 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001020 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001021 that can handle the path item. Return None if no hook could;
1022 this tells our caller it should fall back to the builtin
1023 import mechanism. Cache the result in path_importer_cache.
1024 Returns a borrowed reference. */
1025
1026static PyObject *
1027get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 PyObject *importer;
1031 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 /* These conditions are the caller's responsibility: */
1034 assert(PyList_Check(path_hooks));
1035 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 nhooks = PyList_Size(path_hooks);
1038 if (nhooks < 0)
1039 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 importer = PyDict_GetItem(path_importer_cache, p);
1042 if (importer != NULL)
1043 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* set path_importer_cache[p] to None to avoid recursion */
1046 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1047 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 for (j = 0; j < nhooks; j++) {
1050 PyObject *hook = PyList_GetItem(path_hooks, j);
1051 if (hook == NULL)
1052 return NULL;
1053 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1054 if (importer != NULL)
1055 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1058 return NULL;
1059 }
1060 PyErr_Clear();
1061 }
1062 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001063 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 }
1065 if (importer != NULL) {
1066 int err = PyDict_SetItem(path_importer_cache, p, importer);
1067 Py_DECREF(importer);
1068 if (err != 0)
1069 return NULL;
1070 }
1071 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001072}
1073
Christian Heimes9cd17752007-11-18 19:35:23 +00001074PyAPI_FUNC(PyObject *)
1075PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001077
Victor Stinner1e53bba2013-07-16 22:26:05 +02001078 path_importer_cache = PySys_GetObject("path_importer_cache");
1079 path_hooks = PySys_GetObject("path_hooks");
1080 if (path_importer_cache != NULL && path_hooks != NULL) {
1081 importer = get_path_importer(path_importer_cache,
1082 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
1084 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1085 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001086}
1087
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001088
Victor Stinner95872862011-03-07 18:20:56 +01001089static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001090
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001091/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001092 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001093 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001094
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001095static int
Victor Stinner95872862011-03-07 18:20:56 +01001096init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001099 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001100
Victor Stinner5eb4f592013-11-14 22:38:52 +01001101 mod = _PyImport_FindExtensionObject(name, name);
1102 if (PyErr_Occurred())
1103 return -1;
1104 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 for (p = PyImport_Inittab; p->name != NULL; p++) {
1108 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001109 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001110 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (p->initfunc == NULL) {
1112 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001113 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 name);
1115 return -1;
1116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 mod = (*p->initfunc)();
1118 if (mod == 0)
1119 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001120 /* Remember pointer to module init function. */
1121 def = PyModule_GetDef(mod);
1122 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001123 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 return -1;
1125 /* FixupExtension has put the module into sys.modules,
1126 so we can release our own reference. */
1127 Py_DECREF(mod);
1128 return 1;
1129 }
1130 }
1131 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001132}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001133
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001134
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001135/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001136
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001137static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001138find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001139{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001140 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001141
Victor Stinner53dc7352011-03-20 01:50:21 +01001142 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 for (p = PyImport_FrozenModules; ; p++) {
1146 if (p->name == NULL)
1147 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001148 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 break;
1150 }
1151 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001152}
1153
Guido van Rossum79f25d91997-04-29 20:08:16 +00001154static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001155get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001156{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001157 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (p == NULL) {
1161 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001162 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 name);
1164 return NULL;
1165 }
1166 if (p->code == NULL) {
1167 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001168 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 name);
1170 return NULL;
1171 }
1172 size = p->size;
1173 if (size < 0)
1174 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001175 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001176}
1177
Brett Cannon8d110132009-03-15 02:20:16 +00001178static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001179is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001180{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001181 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (p == NULL) {
1185 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001186 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 name);
1188 return NULL;
1189 }
Brett Cannon8d110132009-03-15 02:20:16 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (size < 0)
1194 Py_RETURN_TRUE;
1195 else
1196 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001197}
1198
1199
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001200/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001201 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001202 an exception set if the initialization failed.
1203 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001204
1205int
Victor Stinner53dc7352011-03-20 01:50:21 +01001206PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001207{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001208 const struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01001209 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 int ispackage;
1211 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001212
Victor Stinner53dc7352011-03-20 01:50:21 +01001213 p = find_frozen(name);
1214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (p == NULL)
1216 return 0;
1217 if (p->code == NULL) {
1218 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001219 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 name);
1221 return -1;
1222 }
1223 size = p->size;
1224 ispackage = (size < 0);
1225 if (ispackage)
1226 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001227 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (co == NULL)
1229 return -1;
1230 if (!PyCode_Check(co)) {
1231 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001232 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 name);
1234 goto err_return;
1235 }
1236 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001237 /* Set __path__ to the empty list */
Victor Stinner53dc7352011-03-20 01:50:21 +01001238 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001240 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (m == NULL)
1242 goto err_return;
1243 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001244 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 goto err_return;
1247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 err = PyDict_SetItemString(d, "__path__", l);
1249 Py_DECREF(l);
1250 if (err != 0)
1251 goto err_return;
1252 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001253 path = PyUnicode_FromString("<frozen>");
1254 if (path == NULL)
1255 goto err_return;
1256 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1257 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (m == NULL)
1259 goto err_return;
1260 Py_DECREF(co);
1261 Py_DECREF(m);
1262 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001263err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 Py_DECREF(co);
1265 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001266}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001267
Victor Stinner53dc7352011-03-20 01:50:21 +01001268int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001269PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001270{
1271 PyObject *nameobj;
1272 int ret;
1273 nameobj = PyUnicode_InternFromString(name);
1274 if (nameobj == NULL)
1275 return -1;
1276 ret = PyImport_ImportFrozenModuleObject(nameobj);
1277 Py_DECREF(nameobj);
1278 return ret;
1279}
1280
Guido van Rossum74e6a111994-08-29 12:54:38 +00001281
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001282/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001283 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001284
Guido van Rossum79f25d91997-04-29 20:08:16 +00001285PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001286PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 PyObject *pname;
1289 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 pname = PyUnicode_FromString(name);
1292 if (pname == NULL)
1293 return NULL;
1294 result = PyImport_Import(pname);
1295 Py_DECREF(pname);
1296 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001297}
1298
Christian Heimes072c0f12008-01-03 23:01:04 +00001299/* Import a module without blocking
1300 *
1301 * At first it tries to fetch the module from sys.modules. If the module was
1302 * never loaded before it loads it with PyImport_ImportModule() unless another
1303 * thread holds the import lock. In the latter case the function raises an
1304 * ImportError instead of blocking.
1305 *
1306 * Returns the module object with incremented ref count.
1307 */
1308PyObject *
1309PyImport_ImportModuleNoBlock(const char *name)
1310{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001311 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001312}
1313
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001314
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001315/* Remove importlib frames from the traceback,
1316 * except in Verbose mode. */
1317static void
1318remove_importlib_frames(void)
1319{
1320 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001321 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001322 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001323 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001324 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001325 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001326
1327 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001328 from the traceback. We always trim chunks
1329 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001330
1331 PyErr_Fetch(&exception, &value, &base_tb);
1332 if (!exception || Py_VerboseFlag)
1333 goto done;
1334 if (PyType_IsSubtype((PyTypeObject *) exception,
1335 (PyTypeObject *) PyExc_ImportError))
1336 always_trim = 1;
1337
1338 prev_link = &base_tb;
1339 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001340 while (tb != NULL) {
1341 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1342 PyObject *next = (PyObject *) traceback->tb_next;
1343 PyFrameObject *frame = traceback->tb_frame;
1344 PyCodeObject *code = frame->f_code;
1345 int now_in_importlib;
1346
1347 assert(PyTraceBack_Check(tb));
1348 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1349 code->co_filename,
1350 importlib_filename) == 0);
1351 if (now_in_importlib && !in_importlib) {
1352 /* This is the link to this chunk of importlib tracebacks */
1353 outer_link = prev_link;
1354 }
1355 in_importlib = now_in_importlib;
1356
1357 if (in_importlib &&
1358 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001359 PyUnicode_CompareWithASCIIString(code->co_name,
1360 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001361 PyObject *tmp = *outer_link;
1362 *outer_link = next;
1363 Py_XINCREF(next);
1364 Py_DECREF(tmp);
1365 prev_link = outer_link;
1366 }
1367 else {
1368 prev_link = (PyObject **) &traceback->tb_next;
1369 }
1370 tb = next;
1371 }
1372done:
1373 PyErr_Restore(exception, value, base_tb);
1374}
1375
1376
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001377PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001378PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1379 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001380 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001381{
Brett Cannonfd074152012-04-14 14:10:13 -04001382 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001383 _Py_IDENTIFIER(__spec__);
1384 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001385 _Py_IDENTIFIER(__package__);
1386 _Py_IDENTIFIER(__path__);
1387 _Py_IDENTIFIER(__name__);
1388 _Py_IDENTIFIER(_find_and_load);
1389 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001390 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001391 _Py_static_string(single_dot, ".");
1392 PyObject *abs_name = NULL;
1393 PyObject *builtins_import = NULL;
1394 PyObject *final_mod = NULL;
1395 PyObject *mod = NULL;
1396 PyObject *package = NULL;
1397 PyObject *globals = NULL;
1398 PyObject *fromlist = NULL;
1399 PyInterpreterState *interp = PyThreadState_GET()->interp;
1400
1401 /* Make sure to use default values so as to not have
1402 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1403 NULL argument. */
1404 if (given_globals == NULL) {
1405 globals = PyDict_New();
1406 if (globals == NULL) {
1407 goto error;
1408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
Brett Cannonfd074152012-04-14 14:10:13 -04001410 else {
1411 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001412 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001413 if (level > 0 && !PyDict_Check(given_globals)) {
1414 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1415 goto error;
1416 }
1417 globals = given_globals;
1418 Py_INCREF(globals);
1419 }
1420
1421 if (given_fromlist == NULL) {
1422 fromlist = PyList_New(0);
1423 if (fromlist == NULL) {
1424 goto error;
1425 }
1426 }
1427 else {
1428 fromlist = given_fromlist;
1429 Py_INCREF(fromlist);
1430 }
1431 if (name == NULL) {
1432 PyErr_SetString(PyExc_ValueError, "Empty module name");
1433 goto error;
1434 }
1435
1436 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1437 for added performance. */
1438
1439 if (!PyUnicode_Check(name)) {
1440 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1441 goto error;
1442 }
1443 else if (PyUnicode_READY(name) < 0) {
1444 goto error;
1445 }
1446 if (level < 0) {
1447 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1448 goto error;
1449 }
1450 else if (level > 0) {
1451 package = _PyDict_GetItemId(globals, &PyId___package__);
1452 if (package != NULL && package != Py_None) {
1453 Py_INCREF(package);
1454 if (!PyUnicode_Check(package)) {
1455 PyErr_SetString(PyExc_TypeError, "package must be a string");
1456 goto error;
1457 }
1458 }
1459 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001460 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001461 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001462 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001463 goto error;
1464 }
1465 else if (!PyUnicode_Check(package)) {
1466 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1467 }
1468 Py_INCREF(package);
1469
1470 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001471 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001472 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1473 if (borrowed_dot == NULL) {
1474 goto error;
1475 }
Brett Cannon740fce02012-04-14 14:23:49 -04001476 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001477 Py_DECREF(package);
1478 if (partition == NULL) {
1479 goto error;
1480 }
1481 package = PyTuple_GET_ITEM(partition, 0);
1482 Py_INCREF(package);
1483 Py_DECREF(partition);
1484 }
1485 }
1486
1487 if (PyDict_GetItem(interp->modules, package) == NULL) {
1488 PyErr_Format(PyExc_SystemError,
1489 "Parent module %R not loaded, cannot perform relative "
1490 "import", package);
1491 goto error;
1492 }
1493 }
1494 else { /* level == 0 */
1495 if (PyUnicode_GET_LENGTH(name) == 0) {
1496 PyErr_SetString(PyExc_ValueError, "Empty module name");
1497 goto error;
1498 }
1499 package = Py_None;
1500 Py_INCREF(package);
1501 }
1502
1503 if (level > 0) {
1504 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1505 PyObject *base = NULL;
1506 int level_up = 1;
1507
1508 for (level_up = 1; level_up < level; level_up += 1) {
1509 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1510 if (last_dot == -2) {
1511 goto error;
1512 }
1513 else if (last_dot == -1) {
1514 PyErr_SetString(PyExc_ValueError,
1515 "attempted relative import beyond top-level "
1516 "package");
1517 goto error;
1518 }
1519 }
Victor Stinner22af2592013-11-13 12:11:36 +01001520
Brett Cannonfd074152012-04-14 14:10:13 -04001521 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001522 if (base == NULL)
1523 goto error;
1524
Brett Cannonfd074152012-04-14 14:10:13 -04001525 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001526 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001527
1528 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001529 seq = PyTuple_Pack(2, base, name);
1530 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001531 if (borrowed_dot == NULL || seq == NULL) {
1532 goto error;
1533 }
1534
1535 abs_name = PyUnicode_Join(borrowed_dot, seq);
1536 Py_DECREF(seq);
1537 if (abs_name == NULL) {
1538 goto error;
1539 }
1540 }
1541 else {
1542 abs_name = base;
1543 }
1544 }
1545 else {
1546 abs_name = name;
1547 Py_INCREF(abs_name);
1548 }
1549
Brian Curtine6b299f2012-04-14 14:19:33 -05001550#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001551 _PyImport_AcquireLock();
1552#endif
1553 /* From this point forward, goto error_with_unlock! */
1554 if (PyDict_Check(globals)) {
1555 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1556 }
1557 if (builtins_import == NULL) {
1558 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1559 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001560 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1561 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001562 }
1563 }
1564 Py_INCREF(builtins_import);
1565
1566 mod = PyDict_GetItem(interp->modules, abs_name);
1567 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001568 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1569 "None in sys.modules", abs_name);
1570 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001571 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001572 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001573 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001574 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001575 goto error_with_unlock;
1576 }
1577 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001578 PyObject *value = NULL;
1579 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001580 int initializing = 0;
1581
Brett Cannonfd074152012-04-14 14:10:13 -04001582 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001583 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001584 __spec__._initializing is true.
1585 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001586 stuffing the new module in sys.modules.
1587 */
Eric Snowb523f842013-11-22 09:05:39 -07001588 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1589 if (spec != NULL) {
1590 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1591 Py_DECREF(spec);
1592 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001593 if (value == NULL)
1594 PyErr_Clear();
1595 else {
1596 initializing = PyObject_IsTrue(value);
1597 Py_DECREF(value);
1598 if (initializing == -1)
1599 PyErr_Clear();
1600 }
1601 if (initializing > 0) {
1602 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001603 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001604 &PyId__lock_unlock_module, abs_name,
1605 NULL);
1606 if (value == NULL)
1607 goto error;
1608 Py_DECREF(value);
1609 }
1610 else {
1611#ifdef WITH_THREAD
1612 if (_PyImport_ReleaseLock() < 0) {
1613 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1614 goto error;
1615 }
1616#endif
1617 }
Brett Cannonfd074152012-04-14 14:10:13 -04001618 }
1619 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001620 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001621 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001622 &PyId__find_and_load, abs_name,
1623 builtins_import, NULL);
1624 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001625 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001626 }
1627 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001628 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001629
1630 if (PyObject_Not(fromlist)) {
1631 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1632 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001633 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001634 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1635
1636 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001637 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001638 }
1639
Brian Curtine6b299f2012-04-14 14:19:33 -05001640 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001641 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001642 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001643 }
1644
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001645 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1646 /* No dot in module name, simple exit */
1647 Py_DECREF(partition);
1648 final_mod = mod;
1649 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001650 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001651 }
1652
Brett Cannonfd074152012-04-14 14:10:13 -04001653 front = PyTuple_GET_ITEM(partition, 0);
1654 Py_INCREF(front);
1655 Py_DECREF(partition);
1656
1657 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001658 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001659 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001660 }
1661 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001662 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1663 PyUnicode_GET_LENGTH(front);
1664 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001665 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001666 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001667 Py_DECREF(front);
1668 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001669 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001670 }
Brett Cannonfd074152012-04-14 14:10:13 -04001671
1672 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001673 if (final_mod == NULL) {
1674 PyErr_Format(PyExc_KeyError,
1675 "%R not in sys.modules as expected",
1676 to_return);
1677 }
1678 else {
1679 Py_INCREF(final_mod);
1680 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001681 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001682 }
1683 }
1684 else {
1685 final_mod = mod;
1686 Py_INCREF(mod);
1687 }
1688 }
1689 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001690 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001691 &PyId__handle_fromlist, mod,
1692 fromlist, builtins_import,
1693 NULL);
1694 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001695 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001696
Brett Cannonfd074152012-04-14 14:10:13 -04001697 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001698#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001699 if (_PyImport_ReleaseLock() < 0) {
1700 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1701 }
1702#endif
1703 error:
1704 Py_XDECREF(abs_name);
1705 Py_XDECREF(builtins_import);
1706 Py_XDECREF(mod);
1707 Py_XDECREF(package);
1708 Py_XDECREF(globals);
1709 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001710 if (final_mod == NULL)
1711 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001712 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001713}
1714
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001715PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001716PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001717 PyObject *fromlist, int level)
1718{
1719 PyObject *nameobj, *mod;
1720 nameobj = PyUnicode_FromString(name);
1721 if (nameobj == NULL)
1722 return NULL;
1723 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1724 fromlist, level);
1725 Py_DECREF(nameobj);
1726 return mod;
1727}
1728
1729
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001730/* Re-import a module of any kind and return its module object, WITH
1731 INCREMENTED REFERENCE COUNT */
1732
Guido van Rossum79f25d91997-04-29 20:08:16 +00001733PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001734PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001735{
Brett Cannon62228db2012-04-29 14:38:11 -04001736 _Py_IDENTIFIER(reload);
1737 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001739 PyObject *imp = PyDict_GetItemString(modules, "imp");
1740 if (imp == NULL) {
1741 imp = PyImport_ImportModule("imp");
1742 if (imp == NULL) {
1743 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 }
Brett Cannon62228db2012-04-29 14:38:11 -04001746 else {
1747 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001749
Brett Cannon62228db2012-04-29 14:38:11 -04001750 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1751 Py_DECREF(imp);
1752 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001753}
1754
1755
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001756/* Higher-level import emulator which emulates the "import" statement
1757 more accurately -- it invokes the __import__() function from the
1758 builtins of the current globals. This means that the import is
1759 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001760 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001761 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001762 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001763 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001764
1765PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001766PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 static PyObject *silly_list = NULL;
1769 static PyObject *builtins_str = NULL;
1770 static PyObject *import_str = NULL;
1771 PyObject *globals = NULL;
1772 PyObject *import = NULL;
1773 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001774 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 /* Initialize constant string objects */
1778 if (silly_list == NULL) {
1779 import_str = PyUnicode_InternFromString("__import__");
1780 if (import_str == NULL)
1781 return NULL;
1782 builtins_str = PyUnicode_InternFromString("__builtins__");
1783 if (builtins_str == NULL)
1784 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001785 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (silly_list == NULL)
1787 return NULL;
1788 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* Get the builtins from current globals */
1791 globals = PyEval_GetGlobals();
1792 if (globals != NULL) {
1793 Py_INCREF(globals);
1794 builtins = PyObject_GetItem(globals, builtins_str);
1795 if (builtins == NULL)
1796 goto err;
1797 }
1798 else {
1799 /* No globals -- use standard builtins, and fake globals */
1800 builtins = PyImport_ImportModuleLevel("builtins",
1801 NULL, NULL, NULL, 0);
1802 if (builtins == NULL)
1803 return NULL;
1804 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1805 if (globals == NULL)
1806 goto err;
1807 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* Get the __import__ function from the builtins */
1810 if (PyDict_Check(builtins)) {
1811 import = PyObject_GetItem(builtins, import_str);
1812 if (import == NULL)
1813 PyErr_SetObject(PyExc_KeyError, import_str);
1814 }
1815 else
1816 import = PyObject_GetAttr(builtins, import_str);
1817 if (import == NULL)
1818 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001821 Always use absolute import here.
1822 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1824 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001825 if (r == NULL)
1826 goto err;
1827 Py_DECREF(r);
1828
1829 modules = PyImport_GetModuleDict();
1830 r = PyDict_GetItem(modules, module_name);
1831 if (r != NULL)
1832 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001833
1834 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 Py_XDECREF(globals);
1836 Py_XDECREF(builtins);
1837 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001840}
1841
Brett Cannon4caa61d2014-01-09 19:03:32 -05001842/*[clinic input]
1843_imp.extension_suffixes
1844
1845Returns the list of file suffixes used to identify extension modules.
1846[clinic start generated code]*/
1847
1848PyDoc_STRVAR(_imp_extension_suffixes__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001849"extension_suffixes($module, /)\n"
1850"--\n"
1851"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001852"Returns the list of file suffixes used to identify extension modules.");
1853
1854#define _IMP_EXTENSION_SUFFIXES_METHODDEF \
1855 {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
1856
Barry Warsaw28a691b2010-04-17 00:19:56 +00001857static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001858_imp_extension_suffixes_impl(PyModuleDef *module);
1859
1860static PyObject *
1861_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1862{
Larry Hastingsbebf7352014-01-17 17:47:17 -08001863 return _imp_extension_suffixes_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001864}
1865
1866static PyObject *
1867_imp_extension_suffixes_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001868/*[clinic end generated code: output=bb30a2438167798c input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001871 const char *suffix;
1872 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 list = PyList_New(0);
1875 if (list == NULL)
1876 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001877#ifdef HAVE_DYNAMIC_LOADING
1878 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1879 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (item == NULL) {
1881 Py_DECREF(list);
1882 return NULL;
1883 }
1884 if (PyList_Append(list, item) < 0) {
1885 Py_DECREF(list);
1886 Py_DECREF(item);
1887 return NULL;
1888 }
1889 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001890 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 }
Brett Cannon2657df42012-05-04 15:20:40 -04001892#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001894}
1895
Brett Cannon4caa61d2014-01-09 19:03:32 -05001896/*[clinic input]
1897_imp.init_builtin
1898
1899 name: unicode
1900 /
1901
1902Initializes a built-in module.
1903[clinic start generated code]*/
1904
1905PyDoc_STRVAR(_imp_init_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001906"init_builtin($module, name, /)\n"
1907"--\n"
1908"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001909"Initializes a built-in module.");
1910
1911#define _IMP_INIT_BUILTIN_METHODDEF \
1912 {"init_builtin", (PyCFunction)_imp_init_builtin, METH_VARARGS, _imp_init_builtin__doc__},
1913
Guido van Rossum79f25d91997-04-29 20:08:16 +00001914static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001915_imp_init_builtin_impl(PyModuleDef *module, PyObject *name);
1916
1917static PyObject *
1918_imp_init_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001919{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001920 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01001921 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001922
1923 if (!PyArg_ParseTuple(args,
1924 "U:init_builtin",
1925 &name))
1926 goto exit;
1927 return_value = _imp_init_builtin_impl(module, name);
1928
1929exit:
1930 return return_value;
1931}
1932
1933static PyObject *
1934_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001935/*[clinic end generated code: output=a0244948a43f8e26 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 int ret;
1938 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 ret = init_builtin(name);
1941 if (ret < 0)
1942 return NULL;
1943 if (ret == 0) {
1944 Py_INCREF(Py_None);
1945 return Py_None;
1946 }
Victor Stinner95872862011-03-07 18:20:56 +01001947 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 Py_XINCREF(m);
1949 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001950}
1951
Brett Cannon4caa61d2014-01-09 19:03:32 -05001952/*[clinic input]
1953_imp.init_frozen
1954
1955 name: unicode
1956 /
1957
1958Initializes a frozen module.
1959[clinic start generated code]*/
1960
1961PyDoc_STRVAR(_imp_init_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001962"init_frozen($module, name, /)\n"
1963"--\n"
1964"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001965"Initializes a frozen module.");
1966
1967#define _IMP_INIT_FROZEN_METHODDEF \
1968 {"init_frozen", (PyCFunction)_imp_init_frozen, METH_VARARGS, _imp_init_frozen__doc__},
1969
Guido van Rossum79f25d91997-04-29 20:08:16 +00001970static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001971_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
1972
1973static PyObject *
1974_imp_init_frozen(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001975{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001976 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001977 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001978
1979 if (!PyArg_ParseTuple(args,
1980 "U:init_frozen",
1981 &name))
1982 goto exit;
1983 return_value = _imp_init_frozen_impl(module, name);
1984
1985exit:
1986 return return_value;
1987}
1988
1989static PyObject *
1990_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001991/*[clinic end generated code: output=e4bc2bff296f8f22 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 int ret;
1994 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001995
Victor Stinner53dc7352011-03-20 01:50:21 +01001996 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (ret < 0)
1998 return NULL;
1999 if (ret == 0) {
2000 Py_INCREF(Py_None);
2001 return Py_None;
2002 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002003 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 Py_XINCREF(m);
2005 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002006}
2007
Brett Cannon4caa61d2014-01-09 19:03:32 -05002008/*[clinic input]
2009_imp.get_frozen_object
2010
2011 name: unicode
2012 /
2013
2014Create a code object for a frozen module.
2015[clinic start generated code]*/
2016
2017PyDoc_STRVAR(_imp_get_frozen_object__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002018"get_frozen_object($module, name, /)\n"
2019"--\n"
2020"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002021"Create a code object for a frozen module.");
2022
2023#define _IMP_GET_FROZEN_OBJECT_METHODDEF \
2024 {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_VARARGS, _imp_get_frozen_object__doc__},
2025
Guido van Rossum79f25d91997-04-29 20:08:16 +00002026static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002027_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
2028
2029static PyObject *
2030_imp_get_frozen_object(PyModuleDef *module, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002031{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002032 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002033 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002034
Brett Cannon4caa61d2014-01-09 19:03:32 -05002035 if (!PyArg_ParseTuple(args,
2036 "U:get_frozen_object",
2037 &name))
2038 goto exit;
2039 return_value = _imp_get_frozen_object_impl(module, name);
2040
2041exit:
2042 return return_value;
2043}
2044
2045static PyObject *
2046_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002047/*[clinic end generated code: output=4089ec702a9d70c5 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002050}
2051
Brett Cannon4caa61d2014-01-09 19:03:32 -05002052/*[clinic input]
2053_imp.is_frozen_package
2054
2055 name: unicode
2056 /
2057
2058Returns True if the module name is of a frozen package.
2059[clinic start generated code]*/
2060
2061PyDoc_STRVAR(_imp_is_frozen_package__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002062"is_frozen_package($module, name, /)\n"
2063"--\n"
2064"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002065"Returns True if the module name is of a frozen package.");
2066
2067#define _IMP_IS_FROZEN_PACKAGE_METHODDEF \
2068 {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_VARARGS, _imp_is_frozen_package__doc__},
2069
Guido van Rossum79f25d91997-04-29 20:08:16 +00002070static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002071_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
2072
2073static PyObject *
2074_imp_is_frozen_package(PyModuleDef *module, PyObject *args)
Brett Cannon8d110132009-03-15 02:20:16 +00002075{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002076 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002077 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002078
Brett Cannon4caa61d2014-01-09 19:03:32 -05002079 if (!PyArg_ParseTuple(args,
2080 "U:is_frozen_package",
2081 &name))
2082 goto exit;
2083 return_value = _imp_is_frozen_package_impl(module, name);
2084
2085exit:
2086 return return_value;
2087}
2088
2089static PyObject *
2090_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002091/*[clinic end generated code: output=86aab14dcd4b959b input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002094}
2095
Brett Cannon4caa61d2014-01-09 19:03:32 -05002096/*[clinic input]
2097_imp.is_builtin
2098
2099 name: unicode
2100 /
2101
2102Returns True if the module name corresponds to a built-in module.
2103[clinic start generated code]*/
2104
2105PyDoc_STRVAR(_imp_is_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002106"is_builtin($module, name, /)\n"
2107"--\n"
2108"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002109"Returns True if the module name corresponds to a built-in module.");
2110
2111#define _IMP_IS_BUILTIN_METHODDEF \
2112 {"is_builtin", (PyCFunction)_imp_is_builtin, METH_VARARGS, _imp_is_builtin__doc__},
2113
Brett Cannon8d110132009-03-15 02:20:16 +00002114static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002115_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
2116
2117static PyObject *
2118_imp_is_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002119{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002120 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01002121 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002122
2123 if (!PyArg_ParseTuple(args,
2124 "U:is_builtin",
2125 &name))
2126 goto exit;
2127 return_value = _imp_is_builtin_impl(module, name);
2128
2129exit:
2130 return return_value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002131}
2132
Guido van Rossum79f25d91997-04-29 20:08:16 +00002133static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002134_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002135/*[clinic end generated code: output=d5847f8cac50946e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002136{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002137 return PyLong_FromLong(is_builtin(name));
2138}
2139
2140/*[clinic input]
2141_imp.is_frozen
2142
2143 name: unicode
2144 /
2145
2146Returns True if the module name corresponds to a frozen module.
2147[clinic start generated code]*/
2148
2149PyDoc_STRVAR(_imp_is_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002150"is_frozen($module, name, /)\n"
2151"--\n"
2152"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002153"Returns True if the module name corresponds to a frozen module.");
2154
2155#define _IMP_IS_FROZEN_METHODDEF \
2156 {"is_frozen", (PyCFunction)_imp_is_frozen, METH_VARARGS, _imp_is_frozen__doc__},
2157
2158static PyObject *
2159_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
2160
2161static PyObject *
2162_imp_is_frozen(PyModuleDef *module, PyObject *args)
2163{
2164 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002165 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002166
2167 if (!PyArg_ParseTuple(args,
2168 "U:is_frozen",
2169 &name))
2170 goto exit;
2171 return_value = _imp_is_frozen_impl(module, name);
2172
2173exit:
2174 return return_value;
2175}
2176
2177static PyObject *
2178_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002179/*[clinic end generated code: output=6691af884ba4987d input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002180{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002181 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 p = find_frozen(name);
2184 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002185}
2186
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002187#ifdef HAVE_DYNAMIC_LOADING
2188
Brett Cannon4caa61d2014-01-09 19:03:32 -05002189/*[clinic input]
2190_imp.load_dynamic
2191
2192 name: unicode
2193 path: fs_unicode
2194 file: object = NULL
2195 /
2196
2197Loads an extension module.
2198[clinic start generated code]*/
2199
2200PyDoc_STRVAR(_imp_load_dynamic__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002201"load_dynamic($module, name, path, file=None, /)\n"
2202"--\n"
2203"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002204"Loads an extension module.");
2205
2206#define _IMP_LOAD_DYNAMIC_METHODDEF \
2207 {"load_dynamic", (PyCFunction)_imp_load_dynamic, METH_VARARGS, _imp_load_dynamic__doc__},
2208
Guido van Rossum79f25d91997-04-29 20:08:16 +00002209static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002210_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file);
2211
2212static PyObject *
2213_imp_load_dynamic(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002214{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002215 PyObject *return_value = NULL;
2216 PyObject *name;
2217 PyObject *path;
2218 PyObject *file = NULL;
2219
2220 if (!PyArg_ParseTuple(args,
2221 "UO&|O:load_dynamic",
2222 &name, PyUnicode_FSDecoder, &path, &file))
2223 goto exit;
2224 return_value = _imp_load_dynamic_impl(module, name, path, file);
2225
2226exit:
2227 return return_value;
2228}
2229
2230static PyObject *
2231_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002232/*[clinic end generated code: output=81d11a1fbd1ea0a8 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002233{
2234 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002235 FILE *fp;
2236
Brett Cannon4caa61d2014-01-09 19:03:32 -05002237 if (file != NULL) {
2238 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002239 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002240 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002241 if (!PyErr_Occurred())
2242 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002244 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002246 else
2247 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002248 mod = _PyImport_LoadDynamicModule(name, path, fp);
2249 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 if (fp)
2251 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002252 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002253}
2254
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002255#endif /* HAVE_DYNAMIC_LOADING */
2256
Larry Hastings7726ac92014-01-31 22:03:12 -08002257/*[clinic input]
2258dump buffer
2259[clinic start generated code]*/
2260
2261#ifndef _IMP_LOAD_DYNAMIC_METHODDEF
2262 #define _IMP_LOAD_DYNAMIC_METHODDEF
2263#endif /* !defined(_IMP_LOAD_DYNAMIC_METHODDEF) */
2264/*[clinic end generated code: output=d07c1d4a343a9579 input=524ce2e021e4eba6]*/
2265
Barry Warsaw28a691b2010-04-17 00:19:56 +00002266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002267PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002268"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002269
Guido van Rossum79f25d91997-04-29 20:08:16 +00002270static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002271 _IMP_EXTENSION_SUFFIXES_METHODDEF
2272 _IMP_LOCK_HELD_METHODDEF
2273 _IMP_ACQUIRE_LOCK_METHODDEF
2274 _IMP_RELEASE_LOCK_METHODDEF
2275 _IMP_GET_FROZEN_OBJECT_METHODDEF
2276 _IMP_IS_FROZEN_PACKAGE_METHODDEF
2277 _IMP_INIT_BUILTIN_METHODDEF
2278 _IMP_INIT_FROZEN_METHODDEF
2279 _IMP_IS_BUILTIN_METHODDEF
2280 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002281 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002282 _IMP__FIX_CO_FILENAME_METHODDEF
2283 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002284};
2285
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002286
Martin v. Löwis1a214512008-06-11 05:26:20 +00002287static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002289 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 doc_imp,
2291 0,
2292 imp_methods,
2293 NULL,
2294 NULL,
2295 NULL,
2296 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002297};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002298
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002299PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002300PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 m = PyModule_Create(&impmodule);
2305 if (m == NULL)
2306 goto failure;
2307 d = PyModule_GetDict(m);
2308 if (d == NULL)
2309 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002312 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 Py_XDECREF(m);
2314 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002315}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002316
2317
Guido van Rossumb18618d2000-05-03 23:44:39 +00002318/* API for embedding applications that want to add their own entries
2319 to the table of built-in modules. This should normally be called
2320 *before* Py_Initialize(). When the table resize fails, -1 is
2321 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002322
2323 After a similar function by Just van Rossum. */
2324
2325int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002326PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 static struct _inittab *our_copy = NULL;
2329 struct _inittab *p;
2330 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Count the number of entries in both tables */
2333 for (n = 0; newtab[n].name != NULL; n++)
2334 ;
2335 if (n == 0)
2336 return 0; /* Nothing to do */
2337 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2338 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* Allocate new memory for the combined table */
2341 p = our_copy;
2342 PyMem_RESIZE(p, struct _inittab, i+n+1);
2343 if (p == NULL)
2344 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* Copy the tables into the new memory */
2347 if (our_copy != PyImport_Inittab)
2348 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2349 PyImport_Inittab = our_copy = p;
2350 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002353}
2354
2355/* Shorthand to add a single entry given a name and a function */
2356
2357int
Brett Cannona826f322009-04-02 03:41:46 +00002358PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 newtab[0].name = (char *)name;
2365 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002368}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002369
2370#ifdef __cplusplus
2371}
2372#endif
Larry Hastings7726ac92014-01-31 22:03:12 -08002373