blob: 7ee7ed9bf1561115700ef30e8e89fb86bc6f0bf5 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020011#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000014
Guido van Rossum55a83382000-09-20 20:31:38 +000015#ifdef HAVE_FCNTL_H
16#include <fcntl.h>
17#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000019extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000021
Barry Warsaw28a691b2010-04-17 00:19:56 +000022#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000023
Victor Stinner95872862011-03-07 18:20:56 +010024/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000025static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Guido van Rossum771c6c81997-10-31 18:37:24 +000027/* This table is defined in config.c: */
28extern struct _inittab _PyImport_Inittab[];
29
30struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000031
Victor Stinnerd0296212011-03-14 14:04:10 -040032static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033
Brett Cannon4caa61d2014-01-09 19:03:32 -050034/*[clinic input]
35module _imp
36[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080037/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050038
39/*[python input]
40class fs_unicode_converter(CConverter):
41 type = 'PyObject *'
42 converter = 'PyUnicode_FSDecoder'
43
44[python start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080045/*[python end generated code: output=da39a3ee5e6b4b0d input=9d6786230166006e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -050046
Guido van Rossum1ae940a1995-01-02 19:04:15 +000047/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000048
49void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000050_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020052 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040053 initstr = PyUnicode_InternFromString("__init__");
54 if (initstr == NULL)
55 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020056 interp->builtins_copy = PyDict_Copy(interp->builtins);
57 if (interp->builtins_copy == NULL)
58 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059}
60
Guido van Rossum25ce5661997-08-02 03:10:38 +000061void
Just van Rossum52e14d62002-12-30 22:08:05 +000062_PyImportHooks_Init(void)
63{
Brett Cannonfd074152012-04-14 14:10:13 -040064 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000066
Brett Cannonfd074152012-04-14 14:10:13 -040067 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 v = PyList_New(0);
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("meta_path", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 v = PyDict_New();
76 if (v == NULL)
77 goto error;
78 err = PySys_SetObject("path_importer_cache", v);
79 Py_DECREF(v);
80 if (err)
81 goto error;
82 path_hooks = PyList_New(0);
83 if (path_hooks == NULL)
84 goto error;
85 err = PySys_SetObject("path_hooks", path_hooks);
86 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000087 error:
Brett Cannonfd074152012-04-14 14:10:13 -040088 PyErr_Print();
89 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020090 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
Brett Cannonfd074152012-04-14 14:10:13 -040092 Py_DECREF(path_hooks);
93}
94
95void
96_PyImportZip_Init(void)
97{
98 PyObject *path_hooks, *zimpimport;
99 int err = 0;
100
101 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200102 if (path_hooks == NULL) {
103 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400104 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200105 }
Brett Cannonfd074152012-04-14 14:10:13 -0400106
107 if (Py_VerboseFlag)
108 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 zimpimport = PyImport_ImportModule("zipimport");
111 if (zimpimport == NULL) {
112 PyErr_Clear(); /* No zip import module -- okay */
113 if (Py_VerboseFlag)
114 PySys_WriteStderr("# can't import zipimport\n");
115 }
116 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200117 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200118 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
119 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 Py_DECREF(zimpimport);
121 if (zipimporter == NULL) {
122 PyErr_Clear(); /* No zipimporter object -- okay */
123 if (Py_VerboseFlag)
124 PySys_WriteStderr(
125 "# can't import zipimport.zipimporter\n");
126 }
127 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400128 /* sys.path_hooks.insert(0, zipimporter) */
129 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400131 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (Py_VerboseFlag)
135 PySys_WriteStderr(
136 "# installed zipimport hook\n");
137 }
138 }
Brett Cannonfd074152012-04-14 14:10:13 -0400139
140 return;
141
142 error:
143 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400144 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000145}
146
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147/* Locking primitives to prevent parallel imports of the same module
148 in different threads to return with a partially loaded module.
149 These calls are serialized by the global interpreter lock. */
150
151#ifdef WITH_THREAD
152
Guido van Rossum49b56061998-10-01 20:42:43 +0000153#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154
Guido van Rossum65d5b571998-12-21 19:32:43 +0000155static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156static long import_lock_thread = -1;
157static int import_lock_level = 0;
158
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000159void
160_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 long me = PyThread_get_thread_ident();
163 if (me == -1)
164 return; /* Too bad */
165 if (import_lock == NULL) {
166 import_lock = PyThread_allocate_lock();
167 if (import_lock == NULL)
168 return; /* Nothing much we can do. */
169 }
170 if (import_lock_thread == me) {
171 import_lock_level++;
172 return;
173 }
174 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
175 {
176 PyThreadState *tstate = PyEval_SaveThread();
177 PyThread_acquire_lock(import_lock, 1);
178 PyEval_RestoreThread(tstate);
179 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100180 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 import_lock_thread = me;
182 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000183}
184
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000185int
186_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 long me = PyThread_get_thread_ident();
189 if (me == -1 || import_lock == NULL)
190 return 0; /* Too bad */
191 if (import_lock_thread != me)
192 return -1;
193 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100194 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (import_lock_level == 0) {
196 import_lock_thread = -1;
197 PyThread_release_lock(import_lock);
198 }
199 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000200}
201
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000202/* This function is called from PyOS_AfterFork to ensure that newly
203 created child processes do not share locks with the parent.
204 We now acquire the import lock around fork() calls but on some platforms
205 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000206
207void
208_PyImport_ReInitLock(void)
209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (import_lock != NULL)
211 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000212 if (import_lock_level > 1) {
213 /* Forked as a side effect of import */
214 long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500215 /* The following could fail if the lock is already held, but forking as
216 a side-effect of an import is a) rare, b) nuts, and c) difficult to
217 do thanks to the lock only being held when doing individual module
218 locks per import. */
219 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000220 import_lock_thread = me;
221 import_lock_level--;
222 } else {
223 import_lock_thread = -1;
224 import_lock_level = 0;
225 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000226}
227
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000228#endif
229
Brett Cannon4caa61d2014-01-09 19:03:32 -0500230/*[clinic input]
231_imp.lock_held
232
233Return True if the import lock is currently held, else False.
234
235On platforms without threads, return False.
236[clinic start generated code]*/
237
238PyDoc_STRVAR(_imp_lock_held__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800239"lock_held($module, /)\n"
240"--\n"
241"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500242"Return True if the import lock is currently held, else False.\n"
243"\n"
244"On platforms without threads, return False.");
245
246#define _IMP_LOCK_HELD_METHODDEF \
247 {"lock_held", (PyCFunction)_imp_lock_held, METH_NOARGS, _imp_lock_held__doc__},
248
Tim Peters69232342001-08-30 05:16:13 +0000249static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500250_imp_lock_held_impl(PyModuleDef *module);
251
252static PyObject *
253_imp_lock_held(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
254{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800255 return _imp_lock_held_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500256}
257
258static PyObject *
259_imp_lock_held_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800260/*[clinic end generated code: output=dae65674966baa65 input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000261{
Tim Peters69232342001-08-30 05:16:13 +0000262#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000264#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000266#endif
267}
268
Brett Cannon4caa61d2014-01-09 19:03:32 -0500269/*[clinic input]
270_imp.acquire_lock
271
272Acquires the interpreter's import lock for the current thread.
273
274This lock should be used by import hooks to ensure thread-safety when importing
275modules. On platforms without threads, this function does nothing.
276[clinic start generated code]*/
277
278PyDoc_STRVAR(_imp_acquire_lock__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800279"acquire_lock($module, /)\n"
280"--\n"
281"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500282"Acquires the interpreter\'s import lock for the current thread.\n"
283"\n"
284"This lock should be used by import hooks to ensure thread-safety when importing\n"
285"modules. On platforms without threads, this function does nothing.");
286
287#define _IMP_ACQUIRE_LOCK_METHODDEF \
288 {"acquire_lock", (PyCFunction)_imp_acquire_lock, METH_NOARGS, _imp_acquire_lock__doc__},
289
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000290static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500291_imp_acquire_lock_impl(PyModuleDef *module);
292
293static PyObject *
294_imp_acquire_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
295{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800296 return _imp_acquire_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500297}
298
299static PyObject *
300_imp_acquire_lock_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800301/*[clinic end generated code: output=478f1fa089fdb9a4 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000302{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000303#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000305#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 Py_INCREF(Py_None);
307 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000308}
309
Brett Cannon4caa61d2014-01-09 19:03:32 -0500310/*[clinic input]
311_imp.release_lock
312
313Release the interpreter's import lock.
314
315On platforms without threads, this function does nothing.
316[clinic start generated code]*/
317
318PyDoc_STRVAR(_imp_release_lock__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800319"release_lock($module, /)\n"
320"--\n"
321"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500322"Release the interpreter\'s import lock.\n"
323"\n"
324"On platforms without threads, this function does nothing.");
325
326#define _IMP_RELEASE_LOCK_METHODDEF \
327 {"release_lock", (PyCFunction)_imp_release_lock, METH_NOARGS, _imp_release_lock__doc__},
328
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000329static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500330_imp_release_lock_impl(PyModuleDef *module);
331
332static PyObject *
333_imp_release_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
334{
Larry Hastingsbebf7352014-01-17 17:47:17 -0800335 return _imp_release_lock_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -0500336}
337
338static PyObject *
339_imp_release_lock_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -0800340/*[clinic end generated code: output=36c77a6832fdafd4 input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000341{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000342#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (_PyImport_ReleaseLock() < 0) {
344 PyErr_SetString(PyExc_RuntimeError,
345 "not holding the import lock");
346 return NULL;
347 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Py_INCREF(Py_None);
350 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000351}
352
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100353void
354_PyImport_Fini(void)
355{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200356 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100357#ifdef WITH_THREAD
358 if (import_lock != NULL) {
359 PyThread_free_lock(import_lock);
360 import_lock = NULL;
361 }
362#endif
363}
364
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365/* Helper for sys */
366
367PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000368PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyInterpreterState *interp = PyThreadState_GET()->interp;
371 if (interp->modules == NULL)
372 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
373 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374}
375
Guido van Rossum3f5da241990-12-20 15:06:42 +0000376
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000377/* List of names to clear in sys */
378static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 "path", "argv", "ps1", "ps2",
380 "last_type", "last_value", "last_traceback",
381 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200382 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 /* misc stuff */
384 "flags", "float_info",
385 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000386};
387
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000388static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 "stdin", "__stdin__",
390 "stdout", "__stdout__",
391 "stderr", "__stderr__",
392 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000393};
394
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000395/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000398PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000399{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200400 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject *key, *value, *dict;
402 PyInterpreterState *interp = PyThreadState_GET()->interp;
403 PyObject *modules = interp->modules;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200404 PyObject *weaklist = NULL;
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200405 char **p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (modules == NULL)
408 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* Delete some special variables first. These are common
411 places where user values hide and people complain when their
412 destructors fail. Since the modules containing them are
413 deleted *last* of all, they would come too late in the normal
414 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000415
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200416 /* XXX Perhaps these precautions are obsolete. Who knows? */
417
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200418 if (Py_VerboseFlag)
419 PySys_WriteStderr("# clear builtins._\n");
420 PyDict_SetItemString(interp->builtins, "_", Py_None);
421
422 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200424 PySys_WriteStderr("# clear sys.%s\n", *p);
425 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200427 for (p = sys_files; *p != NULL; p+=2) {
428 if (Py_VerboseFlag)
429 PySys_WriteStderr("# restore sys.%s\n", *p);
430 value = PyDict_GetItemString(interp->sysdict, *(p+1));
431 if (value == NULL)
432 value = Py_None;
433 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200436 /* We prepare a list which will receive (name, weakref) tuples of
437 modules when they are removed from sys.modules. The name is used
438 for diagnosis messages (in verbose mode), while the weakref helps
439 detect those modules which have been held alive. */
440 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200441 if (weaklist == NULL)
442 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200443
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200444#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200445 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200446 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
447 if (name && wr) { \
448 PyObject *tup = PyTuple_Pack(2, name, wr); \
449 PyList_Append(weaklist, tup); \
450 Py_XDECREF(tup); \
451 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200452 Py_XDECREF(wr); \
453 if (PyErr_Occurred()) \
454 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000456
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457 /* Remove all modules from sys.modules, hoping that garbage collection
458 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 pos = 0;
460 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200461 if (PyModule_Check(value)) {
462 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200463 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200464 STORE_MODULE_WEAKREF(key, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PyDict_SetItem(modules, key, Py_None);
466 }
467 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000468
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200469 /* Clear the modules dict. */
470 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200471 /* Restore the original builtins dict, to ensure that any
472 user data gets cleared. */
473 dict = PyDict_Copy(interp->builtins);
474 if (dict == NULL)
475 PyErr_Clear();
476 PyDict_Clear(interp->builtins);
477 if (PyDict_Update(interp->builtins, interp->builtins_copy))
478 PyErr_Clear();
479 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200480 /* Clear module dict copies stored in the interpreter state */
481 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200482 /* Collect references */
483 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200484 /* Dump GC stats before it's too late, since it uses the warnings
485 machinery. */
486 _PyGC_DumpShutdownStats();
487
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200488 /* Now, if there are any modules left alive, clear their globals to
489 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200490 up here, since they are kept alive in the interpreter state.
491
492 The special treatment of "builtins" here is because even
493 when it's not referenced as a module, its dictionary is
494 referenced by almost every module's __builtins__. Since
495 deleting a module clears its dictionary (even if there are
496 references left to it), we need to delete the "builtins"
497 module last. Likewise, we don't delete sys until the very
498 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200499 if (weaklist != NULL) {
500 Py_ssize_t i, n;
501 n = PyList_GET_SIZE(weaklist);
502 for (i = 0; i < n; i++) {
503 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200504 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200505 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
506 if (mod == Py_None)
507 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200508 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200509 dict = PyModule_GetDict(mod);
510 if (dict == interp->builtins || dict == interp->sysdict)
511 continue;
512 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200513 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200514 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200515 _PyModule_Clear(mod);
516 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200517 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200518 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000520
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200521 /* Next, delete sys and builtins (in that order) */
522 if (Py_VerboseFlag)
523 PySys_FormatStderr("# cleanup[3] wiping sys\n");
524 _PyModule_ClearDict(interp->sysdict);
525 if (Py_VerboseFlag)
526 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
527 _PyModule_ClearDict(interp->builtins);
528
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200529 /* Clear and delete the modules directory. Actual modules will
530 still be there only if imported during the execution of some
531 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 interp->modules = NULL;
533 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200534
535 /* Once more */
536 _PyGC_CollectNoFail();
537
538#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000539}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000540
541
Barry Warsaw28a691b2010-04-17 00:19:56 +0000542/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000543
544long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000545PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000546{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200547 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400548 PyInterpreterState *interp = PyThreadState_Get()->interp;
549 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
550 "_RAW_MAGIC_NUMBER");
551 if (pyc_magic == NULL)
552 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200553 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700554 Py_DECREF(pyc_magic);
555 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000556}
557
558
Brett Cannon3adc7b72012-07-09 14:22:12 -0400559extern const char * _PySys_ImplCacheTag;
560
Barry Warsaw28a691b2010-04-17 00:19:56 +0000561const char *
562PyImport_GetMagicTag(void)
563{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400564 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000565}
566
Brett Cannon98979b82012-07-02 15:13:11 -0400567
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568/* Magic for extension modules (built-in as well as dynamically
569 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200570 once, we keep a static dictionary 'extensions' keyed by the tuple
571 (module name, module name) (for built-in modules) or by
572 (filename, module name) (for dynamically loaded modules), containing these
573 modules. A copy of the module's dictionary is stored by calling
574 _PyImport_FixupExtensionObject() immediately after the module initialization
575 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100576 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000577
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000578 Modules which do support multiple initialization set their m_size
579 field to a non-negative number (indicating the size of the
580 module-specific state). They are still recorded in the extensions
581 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000582*/
583
584int
Victor Stinner95872862011-03-07 18:20:56 +0100585_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
586 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500588 PyObject *modules, *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500590 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (extensions == NULL) {
592 extensions = PyDict_New();
593 if (extensions == NULL)
594 return -1;
595 }
596 if (mod == NULL || !PyModule_Check(mod)) {
597 PyErr_BadInternalCall();
598 return -1;
599 }
600 def = PyModule_GetDef(mod);
601 if (!def) {
602 PyErr_BadInternalCall();
603 return -1;
604 }
605 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100606 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 return -1;
608 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100609 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return -1;
611 }
612 if (def->m_size == -1) {
613 if (def->m_base.m_copy) {
614 /* Somebody already imported the module,
615 likely under a different name.
616 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200617 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 }
619 dict = PyModule_GetDict(mod);
620 if (dict == NULL)
621 return -1;
622 def->m_base.m_copy = PyDict_Copy(dict);
623 if (def->m_base.m_copy == NULL)
624 return -1;
625 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500626 key = PyTuple_Pack(2, filename, name);
627 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200628 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500629 res = PyDict_SetItem(extensions, key, (PyObject *)def);
630 Py_DECREF(key);
631 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200632 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634}
635
Victor Stinner49d3f252010-10-17 01:24:53 +0000636int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300637_PyImport_FixupBuiltin(PyObject *mod, const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000638{
639 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100640 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100641 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100642 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000643 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100644 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
645 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000646 return res;
647}
648
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100650_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000651{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500652 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyModuleDef* def;
654 if (extensions == NULL)
655 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500656 key = PyTuple_Pack(2, filename, name);
657 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200658 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500659 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
660 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (def == NULL)
662 return NULL;
663 if (def->m_size == -1) {
664 /* Module does not support repeated initialization */
665 if (def->m_base.m_copy == NULL)
666 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100667 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (mod == NULL)
669 return NULL;
670 mdict = PyModule_GetDict(mod);
671 if (mdict == NULL)
672 return NULL;
673 if (PyDict_Update(mdict, def->m_base.m_copy))
674 return NULL;
675 }
676 else {
677 if (def->m_base.m_init == NULL)
678 return NULL;
679 mod = def->m_base.m_init();
680 if (mod == NULL)
681 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200682 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
683 Py_DECREF(mod);
684 return NULL;
685 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 Py_DECREF(mod);
687 }
688 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100689 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 Py_DECREF(mod);
691 return NULL;
692 }
693 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100694 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 name, filename);
696 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000697
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000698}
699
Victor Stinner49d3f252010-10-17 01:24:53 +0000700PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000701_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000702{
Victor Stinner95872862011-03-07 18:20:56 +0100703 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100704 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100705 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000706 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100707 res = _PyImport_FindExtensionObject(nameobj, nameobj);
708 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000709 return res;
710}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000711
712/* Get the module object corresponding to a module name.
713 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000714 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000715 Because the former action is most common, THIS DOES NOT RETURN A
716 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717
Guido van Rossum79f25d91997-04-29 20:08:16 +0000718PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000719PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 PyObject *modules = PyImport_GetModuleDict();
722 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000723
Victor Stinner27ee0892011-03-04 12:57:09 +0000724 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyModule_Check(m))
726 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000727 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (m == NULL)
729 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000730 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 Py_DECREF(m);
732 return NULL;
733 }
734 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737}
738
Victor Stinner27ee0892011-03-04 12:57:09 +0000739PyObject *
740PyImport_AddModule(const char *name)
741{
742 PyObject *nameobj, *module;
743 nameobj = PyUnicode_FromString(name);
744 if (nameobj == NULL)
745 return NULL;
746 module = PyImport_AddModuleObject(nameobj);
747 Py_DECREF(nameobj);
748 return module;
749}
750
751
Tim Peters1cd70172004-08-02 03:52:12 +0000752/* Remove name from sys.modules, if it's there. */
753static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000754remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000757 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000759 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 Py_FatalError("import: deleting existing key in"
761 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000762}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763
Christian Heimes3b06e532008-01-07 20:12:44 +0000764
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000765/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000766 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
767 * removed from sys.modules, to avoid leaving damaged module objects
768 * in sys.modules. The caller may wish to restore the original
769 * module object (if any) in this case; PyImport_ReloadModule is an
770 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000771 *
772 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
773 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000774 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000775PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300776PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 return PyImport_ExecCodeModuleWithPathnames(
779 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000780}
781
782PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300783PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return PyImport_ExecCodeModuleWithPathnames(
786 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000787}
788
789PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300790PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
791 const char *pathname,
792 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000793{
Victor Stinner27ee0892011-03-04 12:57:09 +0000794 PyObject *m = NULL;
795 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
796
797 nameobj = PyUnicode_FromString(name);
798 if (nameobj == NULL)
799 return NULL;
800
Victor Stinner27ee0892011-03-04 12:57:09 +0000801 if (cpathname != NULL) {
802 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
803 if (cpathobj == NULL)
804 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400805 }
806 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000807 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400808
809 if (pathname != NULL) {
810 pathobj = PyUnicode_DecodeFSDefault(pathname);
811 if (pathobj == NULL)
812 goto error;
813 }
814 else if (cpathobj != NULL) {
815 PyInterpreterState *interp = PyThreadState_GET()->interp;
816 _Py_IDENTIFIER(_get_sourcefile);
817
818 if (interp == NULL) {
819 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
820 "no interpreter!");
821 }
822
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -0700823 pathobj = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannona6473f92012-07-13 13:57:03 -0400824 &PyId__get_sourcefile, cpathobj,
825 NULL);
826 if (pathobj == NULL)
827 PyErr_Clear();
828 }
829 else
830 pathobj = NULL;
831
Victor Stinner27ee0892011-03-04 12:57:09 +0000832 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
833error:
834 Py_DECREF(nameobj);
835 Py_XDECREF(pathobj);
836 Py_XDECREF(cpathobj);
837 return m;
838}
839
Brett Cannon18fc4e72014-04-04 10:01:46 -0400840static PyObject *
841module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000842{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400843 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000844
Victor Stinner27ee0892011-03-04 12:57:09 +0000845 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (m == NULL)
847 return NULL;
848 /* If the module is being reloaded, we get the old module back
849 and re-use its dict to exec the new code. */
850 d = PyModule_GetDict(m);
851 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
852 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400853 PyEval_GetBuiltins()) != 0) {
854 remove_module(name);
855 return NULL;
856 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400858
Eric Snow08197a42014-05-12 17:54:55 -0600859 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400860}
861
862static PyObject *
863exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
864{
865 PyObject *modules = PyImport_GetModuleDict();
866 PyObject *v, *m;
867
868 v = PyEval_EvalCode(code_object, module_dict, module_dict);
869 if (v == NULL) {
870 remove_module(name);
871 return NULL;
872 }
873 Py_DECREF(v);
874
875 if ((m = PyDict_GetItem(modules, name)) == NULL) {
876 PyErr_Format(PyExc_ImportError,
877 "Loaded module %R not found in sys.modules",
878 name);
879 return NULL;
880 }
881
882 Py_INCREF(m);
883
884 return m;
885}
886
887PyObject*
888PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
889 PyObject *cpathname)
890{
Eric Snow08197a42014-05-12 17:54:55 -0600891 PyObject *d, *res;
892 PyInterpreterState *interp = PyThreadState_GET()->interp;
893 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400894
895 d = module_dict_for_exec(name);
896 if (d == NULL) {
897 return NULL;
898 }
899
Eric Snow08197a42014-05-12 17:54:55 -0600900 if (pathname == NULL) {
901 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 }
Eric Snow08197a42014-05-12 17:54:55 -0600903 res = _PyObject_CallMethodIdObjArgs(interp->importlib,
904 &PyId__fix_up_module,
905 d, name, pathname, cpathname, NULL);
906 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600907 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600908 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 }
Eric Snow08197a42014-05-12 17:54:55 -0600910 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000911}
912
913
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000914static void
915update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 PyObject *constants, *tmp;
918 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (PyUnicode_Compare(co->co_filename, oldname))
921 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 tmp = co->co_filename;
924 co->co_filename = newname;
925 Py_INCREF(co->co_filename);
926 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 constants = co->co_consts;
929 n = PyTuple_GET_SIZE(constants);
930 for (i = 0; i < n; i++) {
931 tmp = PyTuple_GET_ITEM(constants, i);
932 if (PyCode_Check(tmp))
933 update_code_filenames((PyCodeObject *)tmp,
934 oldname, newname);
935 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000936}
937
Victor Stinner2f42ae52011-03-20 00:41:24 +0100938static void
939update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000940{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100941 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000942
Victor Stinner2f42ae52011-03-20 00:41:24 +0100943 if (PyUnicode_Compare(co->co_filename, newname) == 0)
944 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 oldname = co->co_filename;
947 Py_INCREF(oldname);
948 update_code_filenames(co, oldname, newname);
949 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000950}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000951
Brett Cannon4caa61d2014-01-09 19:03:32 -0500952/*[clinic input]
953_imp._fix_co_filename
954
955 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
956 Code object to change.
957
958 path: unicode
959 File path to use.
960 /
961
962Changes code.co_filename to specify the passed-in file path.
963[clinic start generated code]*/
964
965PyDoc_STRVAR(_imp__fix_co_filename__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -0800966"_fix_co_filename($module, code, path, /)\n"
967"--\n"
968"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -0500969"Changes code.co_filename to specify the passed-in file path.\n"
970"\n"
971" code\n"
972" Code object to change.\n"
973" path\n"
974" File path to use.");
975
976#define _IMP__FIX_CO_FILENAME_METHODDEF \
977 {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_VARARGS, _imp__fix_co_filename__doc__},
978
Brett Cannon442c9b92011-03-23 16:14:42 -0700979static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -0500980_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path);
981
982static PyObject *
983_imp__fix_co_filename(PyModuleDef *module, PyObject *args)
Brett Cannon442c9b92011-03-23 16:14:42 -0700984{
Brett Cannon4caa61d2014-01-09 19:03:32 -0500985 PyObject *return_value = NULL;
986 PyCodeObject *code;
987 PyObject *path;
Brett Cannon442c9b92011-03-23 16:14:42 -0700988
Brett Cannon4caa61d2014-01-09 19:03:32 -0500989 if (!PyArg_ParseTuple(args,
990 "O!U:_fix_co_filename",
991 &PyCode_Type, &code, &path))
992 goto exit;
993 return_value = _imp__fix_co_filename_impl(module, code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -0700994
Brett Cannon4caa61d2014-01-09 19:03:32 -0500995exit:
996 return return_value;
997}
Brett Cannon442c9b92011-03-23 16:14:42 -0700998
Brett Cannon4caa61d2014-01-09 19:03:32 -0500999static PyObject *
1000_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code, PyObject *path)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001001/*[clinic end generated code: output=6b4b1edeb0d55c5d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001002
Brett Cannon4caa61d2014-01-09 19:03:32 -05001003{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001004 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001005
1006 Py_RETURN_NONE;
1007}
1008
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001009
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001010/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001011static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001012
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001013
1014/* Helper to test for built-in module */
1015
1016static int
Victor Stinner95872862011-03-07 18:20:56 +01001017is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001018{
Victor Stinner95872862011-03-07 18:20:56 +01001019 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001021 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1022 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (PyImport_Inittab[i].initfunc == NULL)
1024 return -1;
1025 else
1026 return 1;
1027 }
1028 }
1029 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001030}
1031
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001032
Just van Rossum52e14d62002-12-30 22:08:05 +00001033/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1034 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001035 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001036 that can handle the path item. Return None if no hook could;
1037 this tells our caller it should fall back to the builtin
1038 import mechanism. Cache the result in path_importer_cache.
1039 Returns a borrowed reference. */
1040
1041static PyObject *
1042get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyObject *importer;
1046 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* These conditions are the caller's responsibility: */
1049 assert(PyList_Check(path_hooks));
1050 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 nhooks = PyList_Size(path_hooks);
1053 if (nhooks < 0)
1054 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 importer = PyDict_GetItem(path_importer_cache, p);
1057 if (importer != NULL)
1058 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 /* set path_importer_cache[p] to None to avoid recursion */
1061 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1062 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 for (j = 0; j < nhooks; j++) {
1065 PyObject *hook = PyList_GetItem(path_hooks, j);
1066 if (hook == NULL)
1067 return NULL;
1068 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1069 if (importer != NULL)
1070 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1073 return NULL;
1074 }
1075 PyErr_Clear();
1076 }
1077 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001078 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 }
1080 if (importer != NULL) {
1081 int err = PyDict_SetItem(path_importer_cache, p, importer);
1082 Py_DECREF(importer);
1083 if (err != 0)
1084 return NULL;
1085 }
1086 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001087}
1088
Christian Heimes9cd17752007-11-18 19:35:23 +00001089PyAPI_FUNC(PyObject *)
1090PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001092
Victor Stinner1e53bba2013-07-16 22:26:05 +02001093 path_importer_cache = PySys_GetObject("path_importer_cache");
1094 path_hooks = PySys_GetObject("path_hooks");
1095 if (path_importer_cache != NULL && path_hooks != NULL) {
1096 importer = get_path_importer(path_importer_cache,
1097 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 }
1099 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1100 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001101}
1102
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001103
Victor Stinner95872862011-03-07 18:20:56 +01001104static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001105
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001106/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001107 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001108 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001109
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001110static int
Victor Stinner95872862011-03-07 18:20:56 +01001111init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 struct _inittab *p;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001114 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001115
Victor Stinner5eb4f592013-11-14 22:38:52 +01001116 mod = _PyImport_FindExtensionObject(name, name);
1117 if (PyErr_Occurred())
1118 return -1;
1119 if (mod != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 for (p = PyImport_Inittab; p->name != NULL; p++) {
1123 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001124 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001125 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (p->initfunc == NULL) {
1127 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001128 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 name);
1130 return -1;
1131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 mod = (*p->initfunc)();
1133 if (mod == 0)
1134 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001135 /* Remember pointer to module init function. */
1136 def = PyModule_GetDef(mod);
1137 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001138 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 return -1;
1140 /* FixupExtension has put the module into sys.modules,
1141 so we can release our own reference. */
1142 Py_DECREF(mod);
1143 return 1;
1144 }
1145 }
1146 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001147}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001148
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001149
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001150/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001151
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001152static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001153find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001154{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001155 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001156
Victor Stinner53dc7352011-03-20 01:50:21 +01001157 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 for (p = PyImport_FrozenModules; ; p++) {
1161 if (p->name == NULL)
1162 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001163 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 break;
1165 }
1166 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001167}
1168
Guido van Rossum79f25d91997-04-29 20:08:16 +00001169static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001170get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001171{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001172 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (p == NULL) {
1176 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001177 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 name);
1179 return NULL;
1180 }
1181 if (p->code == NULL) {
1182 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001183 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 name);
1185 return NULL;
1186 }
1187 size = p->size;
1188 if (size < 0)
1189 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001190 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001191}
1192
Brett Cannon8d110132009-03-15 02:20:16 +00001193static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001194is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001195{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001196 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 if (p == NULL) {
1200 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001201 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 name);
1203 return NULL;
1204 }
Brett Cannon8d110132009-03-15 02:20:16 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (size < 0)
1209 Py_RETURN_TRUE;
1210 else
1211 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001212}
1213
1214
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001215/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001216 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001217 an exception set if the initialization failed.
1218 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001219
1220int
Victor Stinner53dc7352011-03-20 01:50:21 +01001221PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001222{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001223 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001224 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 int ispackage;
1226 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001227
Victor Stinner53dc7352011-03-20 01:50:21 +01001228 p = find_frozen(name);
1229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (p == NULL)
1231 return 0;
1232 if (p->code == NULL) {
1233 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001234 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 name);
1236 return -1;
1237 }
1238 size = p->size;
1239 ispackage = (size < 0);
1240 if (ispackage)
1241 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001242 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (co == NULL)
1244 return -1;
1245 if (!PyCode_Check(co)) {
1246 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001247 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 name);
1249 goto err_return;
1250 }
1251 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001252 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001253 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001255 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (m == NULL)
1257 goto err_return;
1258 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001259 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 goto err_return;
1262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 err = PyDict_SetItemString(d, "__path__", l);
1264 Py_DECREF(l);
1265 if (err != 0)
1266 goto err_return;
1267 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001268 d = module_dict_for_exec(name);
1269 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001270 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001271 }
1272 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (m == NULL)
1274 goto err_return;
1275 Py_DECREF(co);
1276 Py_DECREF(m);
1277 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001278err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 Py_DECREF(co);
1280 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001281}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001282
Victor Stinner53dc7352011-03-20 01:50:21 +01001283int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001284PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001285{
1286 PyObject *nameobj;
1287 int ret;
1288 nameobj = PyUnicode_InternFromString(name);
1289 if (nameobj == NULL)
1290 return -1;
1291 ret = PyImport_ImportFrozenModuleObject(nameobj);
1292 Py_DECREF(nameobj);
1293 return ret;
1294}
1295
Guido van Rossum74e6a111994-08-29 12:54:38 +00001296
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001297/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001298 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001299
Guido van Rossum79f25d91997-04-29 20:08:16 +00001300PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001301PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyObject *pname;
1304 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 pname = PyUnicode_FromString(name);
1307 if (pname == NULL)
1308 return NULL;
1309 result = PyImport_Import(pname);
1310 Py_DECREF(pname);
1311 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001312}
1313
Christian Heimes072c0f12008-01-03 23:01:04 +00001314/* Import a module without blocking
1315 *
1316 * At first it tries to fetch the module from sys.modules. If the module was
1317 * never loaded before it loads it with PyImport_ImportModule() unless another
1318 * thread holds the import lock. In the latter case the function raises an
1319 * ImportError instead of blocking.
1320 *
1321 * Returns the module object with incremented ref count.
1322 */
1323PyObject *
1324PyImport_ImportModuleNoBlock(const char *name)
1325{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001326 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001327}
1328
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001329
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001330/* Remove importlib frames from the traceback,
1331 * except in Verbose mode. */
1332static void
1333remove_importlib_frames(void)
1334{
1335 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001336 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001337 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001338 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001339 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001340 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001341
1342 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001343 from the traceback. We always trim chunks
1344 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001345
1346 PyErr_Fetch(&exception, &value, &base_tb);
1347 if (!exception || Py_VerboseFlag)
1348 goto done;
1349 if (PyType_IsSubtype((PyTypeObject *) exception,
1350 (PyTypeObject *) PyExc_ImportError))
1351 always_trim = 1;
1352
1353 prev_link = &base_tb;
1354 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001355 while (tb != NULL) {
1356 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1357 PyObject *next = (PyObject *) traceback->tb_next;
1358 PyFrameObject *frame = traceback->tb_frame;
1359 PyCodeObject *code = frame->f_code;
1360 int now_in_importlib;
1361
1362 assert(PyTraceBack_Check(tb));
1363 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1364 code->co_filename,
1365 importlib_filename) == 0);
1366 if (now_in_importlib && !in_importlib) {
1367 /* This is the link to this chunk of importlib tracebacks */
1368 outer_link = prev_link;
1369 }
1370 in_importlib = now_in_importlib;
1371
1372 if (in_importlib &&
1373 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001374 PyUnicode_CompareWithASCIIString(code->co_name,
1375 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001376 PyObject *tmp = *outer_link;
1377 *outer_link = next;
1378 Py_XINCREF(next);
1379 Py_DECREF(tmp);
1380 prev_link = outer_link;
1381 }
1382 else {
1383 prev_link = (PyObject **) &traceback->tb_next;
1384 }
1385 tb = next;
1386 }
1387done:
1388 PyErr_Restore(exception, value, base_tb);
1389}
1390
1391
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001392PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001393PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1394 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001395 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001396{
Brett Cannonfd074152012-04-14 14:10:13 -04001397 _Py_IDENTIFIER(__import__);
Eric Snowb523f842013-11-22 09:05:39 -07001398 _Py_IDENTIFIER(__spec__);
1399 _Py_IDENTIFIER(_initializing);
Brett Cannonfd074152012-04-14 14:10:13 -04001400 _Py_IDENTIFIER(__package__);
1401 _Py_IDENTIFIER(__path__);
1402 _Py_IDENTIFIER(__name__);
1403 _Py_IDENTIFIER(_find_and_load);
1404 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001405 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001406 _Py_static_string(single_dot, ".");
1407 PyObject *abs_name = NULL;
1408 PyObject *builtins_import = NULL;
1409 PyObject *final_mod = NULL;
1410 PyObject *mod = NULL;
1411 PyObject *package = NULL;
1412 PyObject *globals = NULL;
1413 PyObject *fromlist = NULL;
1414 PyInterpreterState *interp = PyThreadState_GET()->interp;
1415
1416 /* Make sure to use default values so as to not have
1417 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1418 NULL argument. */
1419 if (given_globals == NULL) {
1420 globals = PyDict_New();
1421 if (globals == NULL) {
1422 goto error;
1423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 }
Brett Cannonfd074152012-04-14 14:10:13 -04001425 else {
1426 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001427 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001428 if (level > 0 && !PyDict_Check(given_globals)) {
1429 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1430 goto error;
1431 }
1432 globals = given_globals;
1433 Py_INCREF(globals);
1434 }
1435
1436 if (given_fromlist == NULL) {
1437 fromlist = PyList_New(0);
1438 if (fromlist == NULL) {
1439 goto error;
1440 }
1441 }
1442 else {
1443 fromlist = given_fromlist;
1444 Py_INCREF(fromlist);
1445 }
1446 if (name == NULL) {
1447 PyErr_SetString(PyExc_ValueError, "Empty module name");
1448 goto error;
1449 }
1450
1451 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1452 for added performance. */
1453
1454 if (!PyUnicode_Check(name)) {
1455 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1456 goto error;
1457 }
1458 else if (PyUnicode_READY(name) < 0) {
1459 goto error;
1460 }
1461 if (level < 0) {
1462 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1463 goto error;
1464 }
1465 else if (level > 0) {
1466 package = _PyDict_GetItemId(globals, &PyId___package__);
1467 if (package != NULL && package != Py_None) {
1468 Py_INCREF(package);
1469 if (!PyUnicode_Check(package)) {
1470 PyErr_SetString(PyExc_TypeError, "package must be a string");
1471 goto error;
1472 }
1473 }
1474 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001475 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001476 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001477 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001478 goto error;
1479 }
1480 else if (!PyUnicode_Check(package)) {
1481 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1482 }
1483 Py_INCREF(package);
1484
1485 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001486 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001487 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1488 if (borrowed_dot == NULL) {
1489 goto error;
1490 }
Brett Cannon740fce02012-04-14 14:23:49 -04001491 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001492 Py_DECREF(package);
1493 if (partition == NULL) {
1494 goto error;
1495 }
1496 package = PyTuple_GET_ITEM(partition, 0);
1497 Py_INCREF(package);
1498 Py_DECREF(partition);
1499 }
1500 }
1501
1502 if (PyDict_GetItem(interp->modules, package) == NULL) {
1503 PyErr_Format(PyExc_SystemError,
1504 "Parent module %R not loaded, cannot perform relative "
1505 "import", package);
1506 goto error;
1507 }
1508 }
1509 else { /* level == 0 */
1510 if (PyUnicode_GET_LENGTH(name) == 0) {
1511 PyErr_SetString(PyExc_ValueError, "Empty module name");
1512 goto error;
1513 }
1514 package = Py_None;
1515 Py_INCREF(package);
1516 }
1517
1518 if (level > 0) {
1519 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1520 PyObject *base = NULL;
1521 int level_up = 1;
1522
1523 for (level_up = 1; level_up < level; level_up += 1) {
1524 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1525 if (last_dot == -2) {
1526 goto error;
1527 }
1528 else if (last_dot == -1) {
1529 PyErr_SetString(PyExc_ValueError,
1530 "attempted relative import beyond top-level "
1531 "package");
1532 goto error;
1533 }
1534 }
Victor Stinner22af2592013-11-13 12:11:36 +01001535
Brett Cannonfd074152012-04-14 14:10:13 -04001536 base = PyUnicode_Substring(package, 0, last_dot);
Victor Stinner22af2592013-11-13 12:11:36 +01001537 if (base == NULL)
1538 goto error;
1539
Brett Cannonfd074152012-04-14 14:10:13 -04001540 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001541 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001542
1543 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001544 seq = PyTuple_Pack(2, base, name);
1545 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001546 if (borrowed_dot == NULL || seq == NULL) {
1547 goto error;
1548 }
1549
1550 abs_name = PyUnicode_Join(borrowed_dot, seq);
1551 Py_DECREF(seq);
1552 if (abs_name == NULL) {
1553 goto error;
1554 }
1555 }
1556 else {
1557 abs_name = base;
1558 }
1559 }
1560 else {
1561 abs_name = name;
1562 Py_INCREF(abs_name);
1563 }
1564
Brian Curtine6b299f2012-04-14 14:19:33 -05001565#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001566 _PyImport_AcquireLock();
1567#endif
1568 /* From this point forward, goto error_with_unlock! */
1569 if (PyDict_Check(globals)) {
1570 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1571 }
1572 if (builtins_import == NULL) {
1573 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1574 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001575 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1576 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001577 }
1578 }
1579 Py_INCREF(builtins_import);
1580
1581 mod = PyDict_GetItem(interp->modules, abs_name);
1582 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001583 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1584 "None in sys.modules", abs_name);
1585 if (msg != NULL) {
Brett Cannon82da8882013-07-04 17:48:16 -04001586 PyErr_SetImportError(msg, abs_name, NULL);
Brian Curtin09b86d12012-04-17 16:57:09 -05001587 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001588 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001589 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001590 goto error_with_unlock;
1591 }
1592 else if (mod != NULL) {
Eric Snowb523f842013-11-22 09:05:39 -07001593 PyObject *value = NULL;
1594 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001595 int initializing = 0;
1596
Brett Cannonfd074152012-04-14 14:10:13 -04001597 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001598 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001599 __spec__._initializing is true.
1600 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001601 stuffing the new module in sys.modules.
1602 */
Eric Snowb523f842013-11-22 09:05:39 -07001603 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1604 if (spec != NULL) {
1605 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1606 Py_DECREF(spec);
1607 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001608 if (value == NULL)
1609 PyErr_Clear();
1610 else {
1611 initializing = PyObject_IsTrue(value);
1612 Py_DECREF(value);
1613 if (initializing == -1)
1614 PyErr_Clear();
1615 }
1616 if (initializing > 0) {
1617 /* _bootstrap._lock_unlock_module() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001618 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001619 &PyId__lock_unlock_module, abs_name,
1620 NULL);
1621 if (value == NULL)
1622 goto error;
1623 Py_DECREF(value);
1624 }
1625 else {
1626#ifdef WITH_THREAD
1627 if (_PyImport_ReleaseLock() < 0) {
1628 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1629 goto error;
1630 }
1631#endif
1632 }
Brett Cannonfd074152012-04-14 14:10:13 -04001633 }
1634 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001635 /* _bootstrap._find_and_load() releases the import lock */
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001636 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001637 &PyId__find_and_load, abs_name,
1638 builtins_import, NULL);
1639 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001640 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001641 }
1642 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001643 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001644
1645 if (PyObject_Not(fromlist)) {
1646 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1647 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001648 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001649 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1650
1651 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001652 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001653 }
1654
Brian Curtine6b299f2012-04-14 14:19:33 -05001655 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001656 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001657 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001658 }
1659
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001660 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1661 /* No dot in module name, simple exit */
1662 Py_DECREF(partition);
1663 final_mod = mod;
1664 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001665 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001666 }
1667
Brett Cannonfd074152012-04-14 14:10:13 -04001668 front = PyTuple_GET_ITEM(partition, 0);
1669 Py_INCREF(front);
1670 Py_DECREF(partition);
1671
1672 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001673 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001674 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001675 }
1676 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001677 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1678 PyUnicode_GET_LENGTH(front);
1679 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001680 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001681 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001682 Py_DECREF(front);
1683 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001684 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001685 }
Brett Cannonfd074152012-04-14 14:10:13 -04001686
1687 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001688 if (final_mod == NULL) {
1689 PyErr_Format(PyExc_KeyError,
1690 "%R not in sys.modules as expected",
1691 to_return);
1692 }
1693 else {
1694 Py_INCREF(final_mod);
1695 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001696 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001697 }
1698 }
1699 else {
1700 final_mod = mod;
1701 Py_INCREF(mod);
1702 }
1703 }
1704 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001705 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001706 &PyId__handle_fromlist, mod,
1707 fromlist, builtins_import,
1708 NULL);
1709 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001710 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001711
Brett Cannonfd074152012-04-14 14:10:13 -04001712 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001713#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001714 if (_PyImport_ReleaseLock() < 0) {
1715 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1716 }
1717#endif
1718 error:
1719 Py_XDECREF(abs_name);
1720 Py_XDECREF(builtins_import);
1721 Py_XDECREF(mod);
1722 Py_XDECREF(package);
1723 Py_XDECREF(globals);
1724 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001725 if (final_mod == NULL)
1726 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001727 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001728}
1729
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001730PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001731PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001732 PyObject *fromlist, int level)
1733{
1734 PyObject *nameobj, *mod;
1735 nameobj = PyUnicode_FromString(name);
1736 if (nameobj == NULL)
1737 return NULL;
1738 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1739 fromlist, level);
1740 Py_DECREF(nameobj);
1741 return mod;
1742}
1743
1744
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001745/* Re-import a module of any kind and return its module object, WITH
1746 INCREMENTED REFERENCE COUNT */
1747
Guido van Rossum79f25d91997-04-29 20:08:16 +00001748PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001749PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001750{
Brett Cannon62228db2012-04-29 14:38:11 -04001751 _Py_IDENTIFIER(reload);
1752 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001754 PyObject *imp = PyDict_GetItemString(modules, "imp");
1755 if (imp == NULL) {
1756 imp = PyImport_ImportModule("imp");
1757 if (imp == NULL) {
1758 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 }
Brett Cannon62228db2012-04-29 14:38:11 -04001761 else {
1762 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001764
Brett Cannon62228db2012-04-29 14:38:11 -04001765 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1766 Py_DECREF(imp);
1767 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001768}
1769
1770
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001771/* Higher-level import emulator which emulates the "import" statement
1772 more accurately -- it invokes the __import__() function from the
1773 builtins of the current globals. This means that the import is
1774 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001775 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001776 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001777 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001778 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001779
1780PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001781PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 static PyObject *silly_list = NULL;
1784 static PyObject *builtins_str = NULL;
1785 static PyObject *import_str = NULL;
1786 PyObject *globals = NULL;
1787 PyObject *import = NULL;
1788 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001789 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* Initialize constant string objects */
1793 if (silly_list == NULL) {
1794 import_str = PyUnicode_InternFromString("__import__");
1795 if (import_str == NULL)
1796 return NULL;
1797 builtins_str = PyUnicode_InternFromString("__builtins__");
1798 if (builtins_str == NULL)
1799 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001800 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (silly_list == NULL)
1802 return NULL;
1803 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /* Get the builtins from current globals */
1806 globals = PyEval_GetGlobals();
1807 if (globals != NULL) {
1808 Py_INCREF(globals);
1809 builtins = PyObject_GetItem(globals, builtins_str);
1810 if (builtins == NULL)
1811 goto err;
1812 }
1813 else {
1814 /* No globals -- use standard builtins, and fake globals */
1815 builtins = PyImport_ImportModuleLevel("builtins",
1816 NULL, NULL, NULL, 0);
1817 if (builtins == NULL)
1818 return NULL;
1819 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1820 if (globals == NULL)
1821 goto err;
1822 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 /* Get the __import__ function from the builtins */
1825 if (PyDict_Check(builtins)) {
1826 import = PyObject_GetItem(builtins, import_str);
1827 if (import == NULL)
1828 PyErr_SetObject(PyExc_KeyError, import_str);
1829 }
1830 else
1831 import = PyObject_GetAttr(builtins, import_str);
1832 if (import == NULL)
1833 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001836 Always use absolute import here.
1837 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1839 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001840 if (r == NULL)
1841 goto err;
1842 Py_DECREF(r);
1843
1844 modules = PyImport_GetModuleDict();
1845 r = PyDict_GetItem(modules, module_name);
1846 if (r != NULL)
1847 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001848
1849 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 Py_XDECREF(globals);
1851 Py_XDECREF(builtins);
1852 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001855}
1856
Brett Cannon4caa61d2014-01-09 19:03:32 -05001857/*[clinic input]
1858_imp.extension_suffixes
1859
1860Returns the list of file suffixes used to identify extension modules.
1861[clinic start generated code]*/
1862
1863PyDoc_STRVAR(_imp_extension_suffixes__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001864"extension_suffixes($module, /)\n"
1865"--\n"
1866"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001867"Returns the list of file suffixes used to identify extension modules.");
1868
1869#define _IMP_EXTENSION_SUFFIXES_METHODDEF \
1870 {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
1871
Barry Warsaw28a691b2010-04-17 00:19:56 +00001872static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001873_imp_extension_suffixes_impl(PyModuleDef *module);
1874
1875static PyObject *
1876_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
1877{
Larry Hastingsbebf7352014-01-17 17:47:17 -08001878 return _imp_extension_suffixes_impl(module);
Brett Cannon4caa61d2014-01-09 19:03:32 -05001879}
1880
1881static PyObject *
1882_imp_extension_suffixes_impl(PyModuleDef *module)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001883/*[clinic end generated code: output=bb30a2438167798c input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001886 const char *suffix;
1887 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 list = PyList_New(0);
1890 if (list == NULL)
1891 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001892#ifdef HAVE_DYNAMIC_LOADING
1893 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1894 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 if (item == NULL) {
1896 Py_DECREF(list);
1897 return NULL;
1898 }
1899 if (PyList_Append(list, item) < 0) {
1900 Py_DECREF(list);
1901 Py_DECREF(item);
1902 return NULL;
1903 }
1904 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001905 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 }
Brett Cannon2657df42012-05-04 15:20:40 -04001907#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001909}
1910
Brett Cannon4caa61d2014-01-09 19:03:32 -05001911/*[clinic input]
1912_imp.init_builtin
1913
1914 name: unicode
1915 /
1916
1917Initializes a built-in module.
1918[clinic start generated code]*/
1919
1920PyDoc_STRVAR(_imp_init_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001921"init_builtin($module, name, /)\n"
1922"--\n"
1923"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001924"Initializes a built-in module.");
1925
1926#define _IMP_INIT_BUILTIN_METHODDEF \
1927 {"init_builtin", (PyCFunction)_imp_init_builtin, METH_VARARGS, _imp_init_builtin__doc__},
1928
Guido van Rossum79f25d91997-04-29 20:08:16 +00001929static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001930_imp_init_builtin_impl(PyModuleDef *module, PyObject *name);
1931
1932static PyObject *
1933_imp_init_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001934{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001935 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01001936 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001937
1938 if (!PyArg_ParseTuple(args,
1939 "U:init_builtin",
1940 &name))
1941 goto exit;
1942 return_value = _imp_init_builtin_impl(module, name);
1943
1944exit:
1945 return return_value;
1946}
1947
1948static PyObject *
1949_imp_init_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08001950/*[clinic end generated code: output=a0244948a43f8e26 input=f934d2231ec52a2e]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 int ret;
1953 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 ret = init_builtin(name);
1956 if (ret < 0)
1957 return NULL;
1958 if (ret == 0) {
1959 Py_INCREF(Py_None);
1960 return Py_None;
1961 }
Victor Stinner95872862011-03-07 18:20:56 +01001962 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 Py_XINCREF(m);
1964 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001965}
1966
Brett Cannon4caa61d2014-01-09 19:03:32 -05001967/*[clinic input]
1968_imp.init_frozen
1969
1970 name: unicode
1971 /
1972
1973Initializes a frozen module.
1974[clinic start generated code]*/
1975
1976PyDoc_STRVAR(_imp_init_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08001977"init_frozen($module, name, /)\n"
1978"--\n"
1979"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05001980"Initializes a frozen module.");
1981
1982#define _IMP_INIT_FROZEN_METHODDEF \
1983 {"init_frozen", (PyCFunction)_imp_init_frozen, METH_VARARGS, _imp_init_frozen__doc__},
1984
Guido van Rossum79f25d91997-04-29 20:08:16 +00001985static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05001986_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
1987
1988static PyObject *
1989_imp_init_frozen(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001990{
Brett Cannon4caa61d2014-01-09 19:03:32 -05001991 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001992 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001993
1994 if (!PyArg_ParseTuple(args,
1995 "U:init_frozen",
1996 &name))
1997 goto exit;
1998 return_value = _imp_init_frozen_impl(module, name);
1999
2000exit:
2001 return return_value;
2002}
2003
2004static PyObject *
2005_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002006/*[clinic end generated code: output=e4bc2bff296f8f22 input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 int ret;
2009 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002010
Victor Stinner53dc7352011-03-20 01:50:21 +01002011 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (ret < 0)
2013 return NULL;
2014 if (ret == 0) {
2015 Py_INCREF(Py_None);
2016 return Py_None;
2017 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002018 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_XINCREF(m);
2020 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002021}
2022
Brett Cannon4caa61d2014-01-09 19:03:32 -05002023/*[clinic input]
2024_imp.get_frozen_object
2025
2026 name: unicode
2027 /
2028
2029Create a code object for a frozen module.
2030[clinic start generated code]*/
2031
2032PyDoc_STRVAR(_imp_get_frozen_object__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002033"get_frozen_object($module, name, /)\n"
2034"--\n"
2035"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002036"Create a code object for a frozen module.");
2037
2038#define _IMP_GET_FROZEN_OBJECT_METHODDEF \
2039 {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_VARARGS, _imp_get_frozen_object__doc__},
2040
Guido van Rossum79f25d91997-04-29 20:08:16 +00002041static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002042_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
2043
2044static PyObject *
2045_imp_get_frozen_object(PyModuleDef *module, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002046{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002047 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002048 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002049
Brett Cannon4caa61d2014-01-09 19:03:32 -05002050 if (!PyArg_ParseTuple(args,
2051 "U:get_frozen_object",
2052 &name))
2053 goto exit;
2054 return_value = _imp_get_frozen_object_impl(module, name);
2055
2056exit:
2057 return return_value;
2058}
2059
2060static PyObject *
2061_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002062/*[clinic end generated code: output=4089ec702a9d70c5 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002065}
2066
Brett Cannon4caa61d2014-01-09 19:03:32 -05002067/*[clinic input]
2068_imp.is_frozen_package
2069
2070 name: unicode
2071 /
2072
2073Returns True if the module name is of a frozen package.
2074[clinic start generated code]*/
2075
2076PyDoc_STRVAR(_imp_is_frozen_package__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002077"is_frozen_package($module, name, /)\n"
2078"--\n"
2079"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002080"Returns True if the module name is of a frozen package.");
2081
2082#define _IMP_IS_FROZEN_PACKAGE_METHODDEF \
2083 {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_VARARGS, _imp_is_frozen_package__doc__},
2084
Guido van Rossum79f25d91997-04-29 20:08:16 +00002085static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002086_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
2087
2088static PyObject *
2089_imp_is_frozen_package(PyModuleDef *module, PyObject *args)
Brett Cannon8d110132009-03-15 02:20:16 +00002090{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002091 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002092 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002093
Brett Cannon4caa61d2014-01-09 19:03:32 -05002094 if (!PyArg_ParseTuple(args,
2095 "U:is_frozen_package",
2096 &name))
2097 goto exit;
2098 return_value = _imp_is_frozen_package_impl(module, name);
2099
2100exit:
2101 return return_value;
2102}
2103
2104static PyObject *
2105_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002106/*[clinic end generated code: output=86aab14dcd4b959b input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002109}
2110
Brett Cannon4caa61d2014-01-09 19:03:32 -05002111/*[clinic input]
2112_imp.is_builtin
2113
2114 name: unicode
2115 /
2116
2117Returns True if the module name corresponds to a built-in module.
2118[clinic start generated code]*/
2119
2120PyDoc_STRVAR(_imp_is_builtin__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002121"is_builtin($module, name, /)\n"
2122"--\n"
2123"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002124"Returns True if the module name corresponds to a built-in module.");
2125
2126#define _IMP_IS_BUILTIN_METHODDEF \
2127 {"is_builtin", (PyCFunction)_imp_is_builtin, METH_VARARGS, _imp_is_builtin__doc__},
2128
Brett Cannon8d110132009-03-15 02:20:16 +00002129static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002130_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
2131
2132static PyObject *
2133_imp_is_builtin(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002134{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002135 PyObject *return_value = NULL;
Victor Stinner95872862011-03-07 18:20:56 +01002136 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002137
2138 if (!PyArg_ParseTuple(args,
2139 "U:is_builtin",
2140 &name))
2141 goto exit;
2142 return_value = _imp_is_builtin_impl(module, name);
2143
2144exit:
2145 return return_value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002146}
2147
Guido van Rossum79f25d91997-04-29 20:08:16 +00002148static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002149_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002150/*[clinic end generated code: output=d5847f8cac50946e input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002151{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002152 return PyLong_FromLong(is_builtin(name));
2153}
2154
2155/*[clinic input]
2156_imp.is_frozen
2157
2158 name: unicode
2159 /
2160
2161Returns True if the module name corresponds to a frozen module.
2162[clinic start generated code]*/
2163
2164PyDoc_STRVAR(_imp_is_frozen__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002165"is_frozen($module, name, /)\n"
2166"--\n"
2167"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002168"Returns True if the module name corresponds to a frozen module.");
2169
2170#define _IMP_IS_FROZEN_METHODDEF \
2171 {"is_frozen", (PyCFunction)_imp_is_frozen, METH_VARARGS, _imp_is_frozen__doc__},
2172
2173static PyObject *
2174_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
2175
2176static PyObject *
2177_imp_is_frozen(PyModuleDef *module, PyObject *args)
2178{
2179 PyObject *return_value = NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002180 PyObject *name;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002181
2182 if (!PyArg_ParseTuple(args,
2183 "U:is_frozen",
2184 &name))
2185 goto exit;
2186 return_value = _imp_is_frozen_impl(module, name);
2187
2188exit:
2189 return return_value;
2190}
2191
2192static PyObject *
2193_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002194/*[clinic end generated code: output=6691af884ba4987d input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002195{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002196 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 p = find_frozen(name);
2199 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002200}
2201
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002202#ifdef HAVE_DYNAMIC_LOADING
2203
Brett Cannon4caa61d2014-01-09 19:03:32 -05002204/*[clinic input]
2205_imp.load_dynamic
2206
2207 name: unicode
2208 path: fs_unicode
2209 file: object = NULL
2210 /
2211
2212Loads an extension module.
2213[clinic start generated code]*/
2214
2215PyDoc_STRVAR(_imp_load_dynamic__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08002216"load_dynamic($module, name, path, file=None, /)\n"
2217"--\n"
2218"\n"
Brett Cannon4caa61d2014-01-09 19:03:32 -05002219"Loads an extension module.");
2220
2221#define _IMP_LOAD_DYNAMIC_METHODDEF \
2222 {"load_dynamic", (PyCFunction)_imp_load_dynamic, METH_VARARGS, _imp_load_dynamic__doc__},
2223
Guido van Rossum79f25d91997-04-29 20:08:16 +00002224static PyObject *
Brett Cannon4caa61d2014-01-09 19:03:32 -05002225_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file);
2226
2227static PyObject *
2228_imp_load_dynamic(PyModuleDef *module, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002229{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002230 PyObject *return_value = NULL;
2231 PyObject *name;
2232 PyObject *path;
2233 PyObject *file = NULL;
2234
2235 if (!PyArg_ParseTuple(args,
2236 "UO&|O:load_dynamic",
2237 &name, PyUnicode_FSDecoder, &path, &file))
2238 goto exit;
2239 return_value = _imp_load_dynamic_impl(module, name, path, file);
2240
2241exit:
2242 return return_value;
2243}
2244
2245static PyObject *
2246_imp_load_dynamic_impl(PyModuleDef *module, PyObject *name, PyObject *path, PyObject *file)
Larry Hastings2623c8c2014-02-08 22:15:29 -08002247/*[clinic end generated code: output=81d11a1fbd1ea0a8 input=af64f06e4bad3526]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002248{
2249 PyObject *mod;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002250 FILE *fp;
2251
Brett Cannon4caa61d2014-01-09 19:03:32 -05002252 if (file != NULL) {
2253 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002254 if (fp == NULL) {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002255 Py_DECREF(path);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002256 if (!PyErr_Occurred())
2257 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002261 else
2262 fp = NULL;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002263 mod = _PyImport_LoadDynamicModule(name, path, fp);
2264 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (fp)
2266 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002267 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002268}
2269
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002270#endif /* HAVE_DYNAMIC_LOADING */
2271
Larry Hastings7726ac92014-01-31 22:03:12 -08002272/*[clinic input]
2273dump buffer
2274[clinic start generated code]*/
2275
2276#ifndef _IMP_LOAD_DYNAMIC_METHODDEF
2277 #define _IMP_LOAD_DYNAMIC_METHODDEF
2278#endif /* !defined(_IMP_LOAD_DYNAMIC_METHODDEF) */
2279/*[clinic end generated code: output=d07c1d4a343a9579 input=524ce2e021e4eba6]*/
2280
Barry Warsaw28a691b2010-04-17 00:19:56 +00002281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002282PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002283"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002284
Guido van Rossum79f25d91997-04-29 20:08:16 +00002285static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002286 _IMP_EXTENSION_SUFFIXES_METHODDEF
2287 _IMP_LOCK_HELD_METHODDEF
2288 _IMP_ACQUIRE_LOCK_METHODDEF
2289 _IMP_RELEASE_LOCK_METHODDEF
2290 _IMP_GET_FROZEN_OBJECT_METHODDEF
2291 _IMP_IS_FROZEN_PACKAGE_METHODDEF
2292 _IMP_INIT_BUILTIN_METHODDEF
2293 _IMP_INIT_FROZEN_METHODDEF
2294 _IMP_IS_BUILTIN_METHODDEF
2295 _IMP_IS_FROZEN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002296 _IMP_LOAD_DYNAMIC_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002297 _IMP__FIX_CO_FILENAME_METHODDEF
2298 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002299};
2300
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002301
Martin v. Löwis1a214512008-06-11 05:26:20 +00002302static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002304 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 doc_imp,
2306 0,
2307 imp_methods,
2308 NULL,
2309 NULL,
2310 NULL,
2311 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002312};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002313
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002314PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002315PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 m = PyModule_Create(&impmodule);
2320 if (m == NULL)
2321 goto failure;
2322 d = PyModule_GetDict(m);
2323 if (d == NULL)
2324 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002327 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 Py_XDECREF(m);
2329 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002330}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002331
2332
Guido van Rossumb18618d2000-05-03 23:44:39 +00002333/* API for embedding applications that want to add their own entries
2334 to the table of built-in modules. This should normally be called
2335 *before* Py_Initialize(). When the table resize fails, -1 is
2336 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002337
2338 After a similar function by Just van Rossum. */
2339
2340int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002341PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 static struct _inittab *our_copy = NULL;
2344 struct _inittab *p;
2345 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 /* Count the number of entries in both tables */
2348 for (n = 0; newtab[n].name != NULL; n++)
2349 ;
2350 if (n == 0)
2351 return 0; /* Nothing to do */
2352 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2353 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* Allocate new memory for the combined table */
2356 p = our_copy;
2357 PyMem_RESIZE(p, struct _inittab, i+n+1);
2358 if (p == NULL)
2359 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* Copy the tables into the new memory */
2362 if (our_copy != PyImport_Inittab)
2363 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2364 PyImport_Inittab = our_copy = p;
2365 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002368}
2369
2370/* Shorthand to add a single entry given a name and a function */
2371
2372int
Brett Cannona826f322009-04-02 03:41:46 +00002373PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 newtab[0].name = (char *)name;
2380 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002383}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002384
2385#ifdef __cplusplus
2386}
2387#endif
Larry Hastings7726ac92014-01-31 22:03:12 -08002388