blob: e91cef83ff175aa410a60ba85a9a8df0232dd7a7 [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
Christian Heimesd3eb5a152008-02-24 00:38:49 +000022#ifdef MS_WINDOWS
23/* for stat.st_mode */
24typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000025/* for _mkdir */
26#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000027#endif
28
Guido van Rossum21d335e1993-10-15 13:01:11 +000029
Barry Warsaw28a691b2010-04-17 00:19:56 +000030#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000031
Victor Stinner95872862011-03-07 18:20:56 +010032/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000033static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000034
Victor Stinnerfe7c5b52011-04-05 01:48:03 +020035/* Function from Parser/tokenizer.c */
36extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
37
Guido van Rossum771c6c81997-10-31 18:37:24 +000038/* This table is defined in config.c: */
39extern struct _inittab _PyImport_Inittab[];
40
41struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000042
Victor Stinnerd0296212011-03-14 14:04:10 -040043static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044
Guido van Rossum1ae940a1995-01-02 19:04:15 +000045/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046
47void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000048_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049{
Victor Stinnerd0296212011-03-14 14:04:10 -040050 initstr = PyUnicode_InternFromString("__init__");
51 if (initstr == NULL)
52 Py_FatalError("Can't initialize import variables");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053}
54
Guido van Rossum25ce5661997-08-02 03:10:38 +000055void
Just van Rossum52e14d62002-12-30 22:08:05 +000056_PyImportHooks_Init(void)
57{
Brett Cannonfd074152012-04-14 14:10:13 -040058 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000060
Brett Cannonfd074152012-04-14 14:10:13 -040061 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 v = PyList_New(0);
63 if (v == NULL)
64 goto error;
65 err = PySys_SetObject("meta_path", v);
66 Py_DECREF(v);
67 if (err)
68 goto error;
69 v = PyDict_New();
70 if (v == NULL)
71 goto error;
72 err = PySys_SetObject("path_importer_cache", v);
73 Py_DECREF(v);
74 if (err)
75 goto error;
76 path_hooks = PyList_New(0);
77 if (path_hooks == NULL)
78 goto error;
79 err = PySys_SetObject("path_hooks", path_hooks);
80 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000081 error:
Brett Cannonfd074152012-04-14 14:10:13 -040082 PyErr_Print();
83 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020084 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 }
Brett Cannonfd074152012-04-14 14:10:13 -040086 Py_DECREF(path_hooks);
87}
88
89void
90_PyImportZip_Init(void)
91{
92 PyObject *path_hooks, *zimpimport;
93 int err = 0;
94
95 path_hooks = PySys_GetObject("path_hooks");
96 if (path_hooks == NULL)
97 goto error;
98
99 if (Py_VerboseFlag)
100 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 zimpimport = PyImport_ImportModule("zipimport");
103 if (zimpimport == NULL) {
104 PyErr_Clear(); /* No zip import module -- okay */
105 if (Py_VerboseFlag)
106 PySys_WriteStderr("# can't import zipimport\n");
107 }
108 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200109 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200110 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
111 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 Py_DECREF(zimpimport);
113 if (zipimporter == NULL) {
114 PyErr_Clear(); /* No zipimporter object -- okay */
115 if (Py_VerboseFlag)
116 PySys_WriteStderr(
117 "# can't import zipimport.zipimporter\n");
118 }
119 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400120 /* sys.path_hooks.insert(0, zipimporter) */
121 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400123 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 if (Py_VerboseFlag)
127 PySys_WriteStderr(
128 "# installed zipimport hook\n");
129 }
130 }
Brett Cannonfd074152012-04-14 14:10:13 -0400131
132 return;
133
134 error:
135 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400136 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000137}
138
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000139/* Locking primitives to prevent parallel imports of the same module
140 in different threads to return with a partially loaded module.
141 These calls are serialized by the global interpreter lock. */
142
143#ifdef WITH_THREAD
144
Guido van Rossum49b56061998-10-01 20:42:43 +0000145#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000146
Guido van Rossum65d5b571998-12-21 19:32:43 +0000147static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148static long import_lock_thread = -1;
149static int import_lock_level = 0;
150
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000151void
152_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 long me = PyThread_get_thread_ident();
155 if (me == -1)
156 return; /* Too bad */
157 if (import_lock == NULL) {
158 import_lock = PyThread_allocate_lock();
159 if (import_lock == NULL)
160 return; /* Nothing much we can do. */
161 }
162 if (import_lock_thread == me) {
163 import_lock_level++;
164 return;
165 }
166 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
167 {
168 PyThreadState *tstate = PyEval_SaveThread();
169 PyThread_acquire_lock(import_lock, 1);
170 PyEval_RestoreThread(tstate);
171 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100172 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 import_lock_thread = me;
174 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000175}
176
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000177int
178_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 long me = PyThread_get_thread_ident();
181 if (me == -1 || import_lock == NULL)
182 return 0; /* Too bad */
183 if (import_lock_thread != me)
184 return -1;
185 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100186 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (import_lock_level == 0) {
188 import_lock_thread = -1;
189 PyThread_release_lock(import_lock);
190 }
191 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000192}
193
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000194/* This function is called from PyOS_AfterFork to ensure that newly
195 created child processes do not share locks with the parent.
196 We now acquire the import lock around fork() calls but on some platforms
197 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000198
199void
200_PyImport_ReInitLock(void)
201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if (import_lock != NULL)
203 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000204 if (import_lock_level > 1) {
205 /* Forked as a side effect of import */
206 long me = PyThread_get_thread_ident();
207 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100208 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000209 import_lock_thread = me;
210 import_lock_level--;
211 } else {
212 import_lock_thread = -1;
213 import_lock_level = 0;
214 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000215}
216
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000217#endif
218
Tim Peters69232342001-08-30 05:16:13 +0000219static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000220imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000221{
Tim Peters69232342001-08-30 05:16:13 +0000222#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000224#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000226#endif
227}
228
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000229static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000230imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000231{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000232#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000234#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 Py_INCREF(Py_None);
236 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000237}
238
239static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000240imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000241{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000242#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 if (_PyImport_ReleaseLock() < 0) {
244 PyErr_SetString(PyExc_RuntimeError,
245 "not holding the import lock");
246 return NULL;
247 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000248#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 Py_INCREF(Py_None);
250 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000251}
252
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100253void
254_PyImport_Fini(void)
255{
256 Py_XDECREF(extensions);
257 extensions = NULL;
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100258#ifdef WITH_THREAD
259 if (import_lock != NULL) {
260 PyThread_free_lock(import_lock);
261 import_lock = NULL;
262 }
263#endif
264}
265
Guido van Rossum25ce5661997-08-02 03:10:38 +0000266/* Helper for sys */
267
268PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000269PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PyInterpreterState *interp = PyThreadState_GET()->interp;
272 if (interp->modules == NULL)
273 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
274 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275}
276
Guido van Rossum3f5da241990-12-20 15:06:42 +0000277
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000278/* List of names to clear in sys */
279static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 "path", "argv", "ps1", "ps2",
281 "last_type", "last_value", "last_traceback",
282 "path_hooks", "path_importer_cache", "meta_path",
283 /* misc stuff */
284 "flags", "float_info",
285 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000286};
287
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000288static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 "stdin", "__stdin__",
290 "stdout", "__stdout__",
291 "stderr", "__stderr__",
292 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000293};
294
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000295
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000296/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000297
Guido van Rossum3f5da241990-12-20 15:06:42 +0000298void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000299PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 PyObject *key, *value, *dict;
303 PyInterpreterState *interp = PyThreadState_GET()->interp;
304 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (modules == NULL)
307 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 /* Delete some special variables first. These are common
310 places where user values hide and people complain when their
311 destructors fail. Since the modules containing them are
312 deleted *last* of all, they would come too late in the normal
313 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 value = PyDict_GetItemString(modules, "builtins");
316 if (value != NULL && PyModule_Check(value)) {
317 dict = PyModule_GetDict(value);
318 if (Py_VerboseFlag)
319 PySys_WriteStderr("# clear builtins._\n");
320 PyDict_SetItemString(dict, "_", Py_None);
321 }
322 value = PyDict_GetItemString(modules, "sys");
323 if (value != NULL && PyModule_Check(value)) {
324 char **p;
325 PyObject *v;
326 dict = PyModule_GetDict(value);
327 for (p = sys_deletes; *p != NULL; p++) {
328 if (Py_VerboseFlag)
329 PySys_WriteStderr("# clear sys.%s\n", *p);
330 PyDict_SetItemString(dict, *p, Py_None);
331 }
332 for (p = sys_files; *p != NULL; p+=2) {
333 if (Py_VerboseFlag)
334 PySys_WriteStderr("# restore sys.%s\n", *p);
335 v = PyDict_GetItemString(dict, *(p+1));
336 if (v == NULL)
337 v = Py_None;
338 PyDict_SetItemString(dict, *p, v);
339 }
340 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 /* First, delete __main__ */
343 value = PyDict_GetItemString(modules, "__main__");
344 if (value != NULL && PyModule_Check(value)) {
345 if (Py_VerboseFlag)
346 PySys_WriteStderr("# cleanup __main__\n");
347 _PyModule_Clear(value);
348 PyDict_SetItemString(modules, "__main__", Py_None);
349 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* The special treatment of "builtins" here is because even
352 when it's not referenced as a module, its dictionary is
353 referenced by almost every module's __builtins__. Since
354 deleting a module clears its dictionary (even if there are
355 references left to it), we need to delete the "builtins"
356 module last. Likewise, we don't delete sys until the very
357 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 Also note that we 'delete' modules by replacing their entry
360 in the modules dict with None, rather than really deleting
361 them; this avoids a rehash of the modules dictionary and
362 also marks them as "non existent" so they won't be
363 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 /* Next, repeatedly delete modules with a reference count of
366 one (skipping builtins and sys) and delete them */
367 do {
368 ndone = 0;
369 pos = 0;
370 while (PyDict_Next(modules, &pos, &key, &value)) {
371 if (value->ob_refcnt != 1)
372 continue;
373 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100374 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100376 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 continue;
378 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100379 PySys_FormatStderr(
380 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 _PyModule_Clear(value);
382 PyDict_SetItem(modules, key, Py_None);
383 ndone++;
384 }
385 }
386 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 /* Next, delete all modules (still skipping builtins and sys) */
389 pos = 0;
390 while (PyDict_Next(modules, &pos, &key, &value)) {
391 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100392 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100394 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 continue;
396 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100397 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 _PyModule_Clear(value);
399 PyDict_SetItem(modules, key, Py_None);
400 }
401 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* Next, delete sys and builtins (in that order) */
404 value = PyDict_GetItemString(modules, "sys");
405 if (value != NULL && PyModule_Check(value)) {
406 if (Py_VerboseFlag)
407 PySys_WriteStderr("# cleanup sys\n");
408 _PyModule_Clear(value);
409 PyDict_SetItemString(modules, "sys", Py_None);
410 }
411 value = PyDict_GetItemString(modules, "builtins");
412 if (value != NULL && PyModule_Check(value)) {
413 if (Py_VerboseFlag)
414 PySys_WriteStderr("# cleanup builtins\n");
415 _PyModule_Clear(value);
416 PyDict_SetItemString(modules, "builtins", Py_None);
417 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 /* Finally, clear and delete the modules directory */
420 PyDict_Clear(modules);
421 interp->modules = NULL;
422 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000423}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000424
425
Barry Warsaw28a691b2010-04-17 00:19:56 +0000426/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000427
428long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000429PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000430{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200431 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400432 PyInterpreterState *interp = PyThreadState_Get()->interp;
433 PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
434 "_RAW_MAGIC_NUMBER");
435 if (pyc_magic == NULL)
436 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200437 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700438 Py_DECREF(pyc_magic);
439 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000440}
441
442
Brett Cannon3adc7b72012-07-09 14:22:12 -0400443extern const char * _PySys_ImplCacheTag;
444
Barry Warsaw28a691b2010-04-17 00:19:56 +0000445const char *
446PyImport_GetMagicTag(void)
447{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400448 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000449}
450
Brett Cannon98979b82012-07-02 15:13:11 -0400451
Guido van Rossum25ce5661997-08-02 03:10:38 +0000452/* Magic for extension modules (built-in as well as dynamically
453 loaded). To prevent initializing an extension module more than
454 once, we keep a static dictionary 'extensions' keyed by module name
455 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000456 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100457 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000458 immediately after the module initialization function succeeds. A
459 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100460 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000461
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000462 Modules which do support multiple initialization set their m_size
463 field to a non-negative number (indicating the size of the
464 module-specific state). They are still recorded in the extensions
465 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000466*/
467
468int
Victor Stinner95872862011-03-07 18:20:56 +0100469_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
470 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *modules, *dict;
473 struct PyModuleDef *def;
474 if (extensions == NULL) {
475 extensions = PyDict_New();
476 if (extensions == NULL)
477 return -1;
478 }
479 if (mod == NULL || !PyModule_Check(mod)) {
480 PyErr_BadInternalCall();
481 return -1;
482 }
483 def = PyModule_GetDef(mod);
484 if (!def) {
485 PyErr_BadInternalCall();
486 return -1;
487 }
488 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100489 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return -1;
491 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100492 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return -1;
494 }
495 if (def->m_size == -1) {
496 if (def->m_base.m_copy) {
497 /* Somebody already imported the module,
498 likely under a different name.
499 XXX this should really not happen. */
500 Py_DECREF(def->m_base.m_copy);
501 def->m_base.m_copy = NULL;
502 }
503 dict = PyModule_GetDict(mod);
504 if (dict == NULL)
505 return -1;
506 def->m_base.m_copy = PyDict_Copy(dict);
507 if (def->m_base.m_copy == NULL)
508 return -1;
509 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000510 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000512}
513
Victor Stinner49d3f252010-10-17 01:24:53 +0000514int
515_PyImport_FixupBuiltin(PyObject *mod, char *name)
516{
517 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100518 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100519 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100520 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000521 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100522 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
523 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000524 return res;
525}
526
Guido van Rossum25ce5661997-08-02 03:10:38 +0000527PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100528_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 PyObject *mod, *mdict;
531 PyModuleDef* def;
532 if (extensions == NULL)
533 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000534 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (def == NULL)
536 return NULL;
537 if (def->m_size == -1) {
538 /* Module does not support repeated initialization */
539 if (def->m_base.m_copy == NULL)
540 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100541 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (mod == NULL)
543 return NULL;
544 mdict = PyModule_GetDict(mod);
545 if (mdict == NULL)
546 return NULL;
547 if (PyDict_Update(mdict, def->m_base.m_copy))
548 return NULL;
549 }
550 else {
551 if (def->m_base.m_init == NULL)
552 return NULL;
553 mod = def->m_base.m_init();
554 if (mod == NULL)
555 return NULL;
Christian Heimes09ca7942013-07-20 14:51:53 +0200556 if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
557 Py_DECREF(mod);
558 return NULL;
559 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 Py_DECREF(mod);
561 }
562 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100563 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 Py_DECREF(mod);
565 return NULL;
566 }
567 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100568 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 name, filename);
570 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000571
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000572}
573
Victor Stinner49d3f252010-10-17 01:24:53 +0000574PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000575_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000576{
Victor Stinner95872862011-03-07 18:20:56 +0100577 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100578 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100579 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000580 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100581 res = _PyImport_FindExtensionObject(nameobj, nameobj);
582 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000583 return res;
584}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000585
586/* Get the module object corresponding to a module name.
587 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000588 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000589 Because the former action is most common, THIS DOES NOT RETURN A
590 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000591
Guido van Rossum79f25d91997-04-29 20:08:16 +0000592PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000593PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyObject *modules = PyImport_GetModuleDict();
596 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000597
Victor Stinner27ee0892011-03-04 12:57:09 +0000598 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 PyModule_Check(m))
600 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000601 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (m == NULL)
603 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000604 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 Py_DECREF(m);
606 return NULL;
607 }
608 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000611}
612
Victor Stinner27ee0892011-03-04 12:57:09 +0000613PyObject *
614PyImport_AddModule(const char *name)
615{
616 PyObject *nameobj, *module;
617 nameobj = PyUnicode_FromString(name);
618 if (nameobj == NULL)
619 return NULL;
620 module = PyImport_AddModuleObject(nameobj);
621 Py_DECREF(nameobj);
622 return module;
623}
624
625
Tim Peters1cd70172004-08-02 03:52:12 +0000626/* Remove name from sys.modules, if it's there. */
627static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000628remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000631 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000633 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_FatalError("import: deleting existing key in"
635 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000636}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000637
Christian Heimes3b06e532008-01-07 20:12:44 +0000638
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000639/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000640 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
641 * removed from sys.modules, to avoid leaving damaged module objects
642 * in sys.modules. The caller may wish to restore the original
643 * module object (if any) in this case; PyImport_ReloadModule is an
644 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000645 *
646 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
647 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000648 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000649PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000650PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return PyImport_ExecCodeModuleWithPathnames(
653 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000654}
655
656PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000657PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 return PyImport_ExecCodeModuleWithPathnames(
660 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000661}
662
663PyObject *
664PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000666{
Victor Stinner27ee0892011-03-04 12:57:09 +0000667 PyObject *m = NULL;
668 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
669
670 nameobj = PyUnicode_FromString(name);
671 if (nameobj == NULL)
672 return NULL;
673
Victor Stinner27ee0892011-03-04 12:57:09 +0000674 if (cpathname != NULL) {
675 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
676 if (cpathobj == NULL)
677 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400678 }
679 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000680 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400681
682 if (pathname != NULL) {
683 pathobj = PyUnicode_DecodeFSDefault(pathname);
684 if (pathobj == NULL)
685 goto error;
686 }
687 else if (cpathobj != NULL) {
688 PyInterpreterState *interp = PyThreadState_GET()->interp;
689 _Py_IDENTIFIER(_get_sourcefile);
690
691 if (interp == NULL) {
692 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
693 "no interpreter!");
694 }
695
696 pathobj = _PyObject_CallMethodObjIdArgs(interp->importlib,
697 &PyId__get_sourcefile, cpathobj,
698 NULL);
699 if (pathobj == NULL)
700 PyErr_Clear();
701 }
702 else
703 pathobj = NULL;
704
Victor Stinner27ee0892011-03-04 12:57:09 +0000705 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
706error:
707 Py_DECREF(nameobj);
708 Py_XDECREF(pathobj);
709 Py_XDECREF(cpathobj);
710 return m;
711}
712
713PyObject*
714PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
715 PyObject *cpathname)
716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *modules = PyImport_GetModuleDict();
718 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000719
Victor Stinner27ee0892011-03-04 12:57:09 +0000720 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (m == NULL)
722 return NULL;
723 /* If the module is being reloaded, we get the old module back
724 and re-use its dict to exec the new code. */
725 d = PyModule_GetDict(m);
726 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
727 if (PyDict_SetItemString(d, "__builtins__",
728 PyEval_GetBuiltins()) != 0)
729 goto error;
730 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (pathname != NULL) {
Brett Cannona6473f92012-07-13 13:57:03 -0400732 v = pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 }
Brett Cannona6473f92012-07-13 13:57:03 -0400734 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 v = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 }
Brett Cannona6473f92012-07-13 13:57:03 -0400737 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (PyDict_SetItemString(d, "__file__", v) != 0)
739 PyErr_Clear(); /* Not important enough to report */
740 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000743 if (cpathname != NULL)
744 v = cpathname;
745 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (PyDict_SetItemString(d, "__cached__", v) != 0)
748 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000749
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000750 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (v == NULL)
752 goto error;
753 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000754
Victor Stinner27ee0892011-03-04 12:57:09 +0000755 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000757 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 name);
759 return NULL;
760 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000765
766 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 remove_module(name);
768 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769}
770
771
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000772static void
773update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 PyObject *constants, *tmp;
776 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (PyUnicode_Compare(co->co_filename, oldname))
779 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 tmp = co->co_filename;
782 co->co_filename = newname;
783 Py_INCREF(co->co_filename);
784 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 constants = co->co_consts;
787 n = PyTuple_GET_SIZE(constants);
788 for (i = 0; i < n; i++) {
789 tmp = PyTuple_GET_ITEM(constants, i);
790 if (PyCode_Check(tmp))
791 update_code_filenames((PyCodeObject *)tmp,
792 oldname, newname);
793 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000794}
795
Victor Stinner2f42ae52011-03-20 00:41:24 +0100796static void
797update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000798{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100799 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000800
Victor Stinner2f42ae52011-03-20 00:41:24 +0100801 if (PyUnicode_Compare(co->co_filename, newname) == 0)
802 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 oldname = co->co_filename;
805 Py_INCREF(oldname);
806 update_code_filenames(co, oldname, newname);
807 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000808}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000809
Brett Cannon442c9b92011-03-23 16:14:42 -0700810static PyObject *
811imp_fix_co_filename(PyObject *self, PyObject *args)
812{
813 PyObject *co;
814 PyObject *file_path;
815
816 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
817 return NULL;
818
819 if (!PyCode_Check(co)) {
820 PyErr_SetString(PyExc_TypeError,
821 "first argument must be a code object");
822 return NULL;
823 }
824
825 if (!PyUnicode_Check(file_path)) {
826 PyErr_SetString(PyExc_TypeError,
827 "second argument must be a string");
828 return NULL;
829 }
830
831 update_compiled_module((PyCodeObject*)co, file_path);
832
833 Py_RETURN_NONE;
834}
835
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000836
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000837/* Forward */
Victor Stinner53dc7352011-03-20 01:50:21 +0100838static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000839
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000840
841/* Helper to test for built-in module */
842
843static int
Victor Stinner95872862011-03-07 18:20:56 +0100844is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000845{
Victor Stinner95872862011-03-07 18:20:56 +0100846 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +0100848 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
849 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (PyImport_Inittab[i].initfunc == NULL)
851 return -1;
852 else
853 return 1;
854 }
855 }
856 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000857}
858
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000859
Just van Rossum52e14d62002-12-30 22:08:05 +0000860/* Return an importer object for a sys.path/pkg.__path__ item 'p',
861 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +0000862 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +0000863 that can handle the path item. Return None if no hook could;
864 this tells our caller it should fall back to the builtin
865 import mechanism. Cache the result in path_importer_cache.
866 Returns a borrowed reference. */
867
868static PyObject *
869get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +0000871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyObject *importer;
873 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 /* These conditions are the caller's responsibility: */
876 assert(PyList_Check(path_hooks));
877 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 nhooks = PyList_Size(path_hooks);
880 if (nhooks < 0)
881 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 importer = PyDict_GetItem(path_importer_cache, p);
884 if (importer != NULL)
885 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* set path_importer_cache[p] to None to avoid recursion */
888 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
889 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 for (j = 0; j < nhooks; j++) {
892 PyObject *hook = PyList_GetItem(path_hooks, j);
893 if (hook == NULL)
894 return NULL;
895 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
896 if (importer != NULL)
897 break;
Just van Rossum52e14d62002-12-30 22:08:05 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
900 return NULL;
901 }
902 PyErr_Clear();
903 }
904 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -0400905 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
907 if (importer != NULL) {
908 int err = PyDict_SetItem(path_importer_cache, p, importer);
909 Py_DECREF(importer);
910 if (err != 0)
911 return NULL;
912 }
913 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +0000914}
915
Christian Heimes9cd17752007-11-18 19:35:23 +0000916PyAPI_FUNC(PyObject *)
917PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
921 if ((path_hooks = PySys_GetObject("path_hooks"))) {
922 importer = get_path_importer(path_importer_cache,
923 path_hooks, path);
924 }
925 }
926 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
927 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +0000928}
929
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000930
Victor Stinner95872862011-03-07 18:20:56 +0100931static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000932
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000933/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000934 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000935 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000936
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000937static int
Victor Stinner95872862011-03-07 18:20:56 +0100938init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000941
Victor Stinner95872862011-03-07 18:20:56 +0100942 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 for (p = PyImport_Inittab; p->name != NULL; p++) {
946 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +0100947 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +0100948 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (p->initfunc == NULL) {
950 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +0100951 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 name);
953 return -1;
954 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 mod = (*p->initfunc)();
956 if (mod == 0)
957 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +0100958 /* Remember pointer to module init function. */
959 def = PyModule_GetDef(mod);
960 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +0100961 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return -1;
963 /* FixupExtension has put the module into sys.modules,
964 so we can release our own reference. */
965 Py_DECREF(mod);
966 return 1;
967 }
968 }
969 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000970}
Guido van Rossumf56e3db1993-04-01 20:59:32 +0000971
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000972
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000973/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000974
Guido van Rossumcfd0a221996-06-17 17:06:34 +0000975static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +0100976find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000979
Victor Stinner53dc7352011-03-20 01:50:21 +0100980 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 for (p = PyImport_FrozenModules; ; p++) {
984 if (p->name == NULL)
985 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +0100986 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 break;
988 }
989 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000990}
991
Guido van Rossum79f25d91997-04-29 20:08:16 +0000992static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +0100993get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 struct _frozen *p = find_frozen(name);
996 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (p == NULL) {
999 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001000 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 name);
1002 return NULL;
1003 }
1004 if (p->code == NULL) {
1005 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001006 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 name);
1008 return NULL;
1009 }
1010 size = p->size;
1011 if (size < 0)
1012 size = -size;
1013 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001014}
1015
Brett Cannon8d110132009-03-15 02:20:16 +00001016static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001017is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 struct _frozen *p = find_frozen(name);
1020 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (p == NULL) {
1023 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001024 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 name);
1026 return NULL;
1027 }
Brett Cannon8d110132009-03-15 02:20:16 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (size < 0)
1032 Py_RETURN_TRUE;
1033 else
1034 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001035}
1036
1037
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001038/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001039 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001040 an exception set if the initialization failed.
1041 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001042
1043int
Victor Stinner53dc7352011-03-20 01:50:21 +01001044PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001045{
Victor Stinner53dc7352011-03-20 01:50:21 +01001046 struct _frozen *p;
1047 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 int ispackage;
1049 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001050
Victor Stinner53dc7352011-03-20 01:50:21 +01001051 p = find_frozen(name);
1052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 if (p == NULL)
1054 return 0;
1055 if (p->code == NULL) {
1056 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001057 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 name);
1059 return -1;
1060 }
1061 size = p->size;
1062 ispackage = (size < 0);
1063 if (ispackage)
1064 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1066 if (co == NULL)
1067 return -1;
1068 if (!PyCode_Check(co)) {
1069 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001070 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 name);
1072 goto err_return;
1073 }
1074 if (ispackage) {
1075 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01001076 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001078 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 if (m == NULL)
1080 goto err_return;
1081 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 l = PyList_New(1);
1083 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 goto err_return;
1085 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001086 Py_INCREF(name);
1087 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 err = PyDict_SetItemString(d, "__path__", l);
1089 Py_DECREF(l);
1090 if (err != 0)
1091 goto err_return;
1092 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001093 path = PyUnicode_FromString("<frozen>");
1094 if (path == NULL)
1095 goto err_return;
1096 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1097 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (m == NULL)
1099 goto err_return;
1100 Py_DECREF(co);
1101 Py_DECREF(m);
1102 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001103err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 Py_DECREF(co);
1105 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001106}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001107
Victor Stinner53dc7352011-03-20 01:50:21 +01001108int
1109PyImport_ImportFrozenModule(char *name)
1110{
1111 PyObject *nameobj;
1112 int ret;
1113 nameobj = PyUnicode_InternFromString(name);
1114 if (nameobj == NULL)
1115 return -1;
1116 ret = PyImport_ImportFrozenModuleObject(nameobj);
1117 Py_DECREF(nameobj);
1118 return ret;
1119}
1120
Guido van Rossum74e6a111994-08-29 12:54:38 +00001121
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001122/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001123 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001124
Guido van Rossum79f25d91997-04-29 20:08:16 +00001125PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001126PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyObject *pname;
1129 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 pname = PyUnicode_FromString(name);
1132 if (pname == NULL)
1133 return NULL;
1134 result = PyImport_Import(pname);
1135 Py_DECREF(pname);
1136 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001137}
1138
Christian Heimes072c0f12008-01-03 23:01:04 +00001139/* Import a module without blocking
1140 *
1141 * At first it tries to fetch the module from sys.modules. If the module was
1142 * never loaded before it loads it with PyImport_ImportModule() unless another
1143 * thread holds the import lock. In the latter case the function raises an
1144 * ImportError instead of blocking.
1145 *
1146 * Returns the module object with incremented ref count.
1147 */
1148PyObject *
1149PyImport_ImportModuleNoBlock(const char *name)
1150{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001151 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001152}
1153
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001154
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001155/* Remove importlib frames from the traceback,
1156 * except in Verbose mode. */
1157static void
1158remove_importlib_frames(void)
1159{
1160 const char *importlib_filename = "<frozen importlib._bootstrap>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001161 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001162 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001163 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001164 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001165 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001166
1167 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001168 from the traceback. We always trim chunks
1169 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001170
1171 PyErr_Fetch(&exception, &value, &base_tb);
1172 if (!exception || Py_VerboseFlag)
1173 goto done;
1174 if (PyType_IsSubtype((PyTypeObject *) exception,
1175 (PyTypeObject *) PyExc_ImportError))
1176 always_trim = 1;
1177
1178 prev_link = &base_tb;
1179 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001180 while (tb != NULL) {
1181 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1182 PyObject *next = (PyObject *) traceback->tb_next;
1183 PyFrameObject *frame = traceback->tb_frame;
1184 PyCodeObject *code = frame->f_code;
1185 int now_in_importlib;
1186
1187 assert(PyTraceBack_Check(tb));
1188 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1189 code->co_filename,
1190 importlib_filename) == 0);
1191 if (now_in_importlib && !in_importlib) {
1192 /* This is the link to this chunk of importlib tracebacks */
1193 outer_link = prev_link;
1194 }
1195 in_importlib = now_in_importlib;
1196
1197 if (in_importlib &&
1198 (always_trim ||
Nick Coghlan42c07662012-07-31 21:14:18 +10001199 PyUnicode_CompareWithASCIIString(code->co_name,
1200 remove_frames) == 0)) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001201 PyObject *tmp = *outer_link;
1202 *outer_link = next;
1203 Py_XINCREF(next);
1204 Py_DECREF(tmp);
1205 prev_link = outer_link;
1206 }
1207 else {
1208 prev_link = (PyObject **) &traceback->tb_next;
1209 }
1210 tb = next;
1211 }
1212done:
1213 PyErr_Restore(exception, value, base_tb);
1214}
1215
1216
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001217PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001218PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1219 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001220 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001221{
Brett Cannonfd074152012-04-14 14:10:13 -04001222 _Py_IDENTIFIER(__import__);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001223 _Py_IDENTIFIER(__initializing__);
Brett Cannonfd074152012-04-14 14:10:13 -04001224 _Py_IDENTIFIER(__package__);
1225 _Py_IDENTIFIER(__path__);
1226 _Py_IDENTIFIER(__name__);
1227 _Py_IDENTIFIER(_find_and_load);
1228 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001229 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001230 _Py_static_string(single_dot, ".");
1231 PyObject *abs_name = NULL;
1232 PyObject *builtins_import = NULL;
1233 PyObject *final_mod = NULL;
1234 PyObject *mod = NULL;
1235 PyObject *package = NULL;
1236 PyObject *globals = NULL;
1237 PyObject *fromlist = NULL;
1238 PyInterpreterState *interp = PyThreadState_GET()->interp;
1239
1240 /* Make sure to use default values so as to not have
1241 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1242 NULL argument. */
1243 if (given_globals == NULL) {
1244 globals = PyDict_New();
1245 if (globals == NULL) {
1246 goto error;
1247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 }
Brett Cannonfd074152012-04-14 14:10:13 -04001249 else {
1250 /* Only have to care what given_globals is if it will be used
Brett Cannonecfefb72012-08-05 19:24:57 -04001251 for something. */
Brett Cannonfd074152012-04-14 14:10:13 -04001252 if (level > 0 && !PyDict_Check(given_globals)) {
1253 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1254 goto error;
1255 }
1256 globals = given_globals;
1257 Py_INCREF(globals);
1258 }
1259
1260 if (given_fromlist == NULL) {
1261 fromlist = PyList_New(0);
1262 if (fromlist == NULL) {
1263 goto error;
1264 }
1265 }
1266 else {
1267 fromlist = given_fromlist;
1268 Py_INCREF(fromlist);
1269 }
1270 if (name == NULL) {
1271 PyErr_SetString(PyExc_ValueError, "Empty module name");
1272 goto error;
1273 }
1274
1275 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1276 for added performance. */
1277
1278 if (!PyUnicode_Check(name)) {
1279 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1280 goto error;
1281 }
1282 else if (PyUnicode_READY(name) < 0) {
1283 goto error;
1284 }
1285 if (level < 0) {
1286 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1287 goto error;
1288 }
1289 else if (level > 0) {
1290 package = _PyDict_GetItemId(globals, &PyId___package__);
1291 if (package != NULL && package != Py_None) {
1292 Py_INCREF(package);
1293 if (!PyUnicode_Check(package)) {
1294 PyErr_SetString(PyExc_TypeError, "package must be a string");
1295 goto error;
1296 }
1297 }
1298 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001299 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001300 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001301 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001302 goto error;
1303 }
1304 else if (!PyUnicode_Check(package)) {
1305 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1306 }
1307 Py_INCREF(package);
1308
1309 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001310 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001311 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1312 if (borrowed_dot == NULL) {
1313 goto error;
1314 }
Brett Cannon740fce02012-04-14 14:23:49 -04001315 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001316 Py_DECREF(package);
1317 if (partition == NULL) {
1318 goto error;
1319 }
1320 package = PyTuple_GET_ITEM(partition, 0);
1321 Py_INCREF(package);
1322 Py_DECREF(partition);
1323 }
1324 }
1325
1326 if (PyDict_GetItem(interp->modules, package) == NULL) {
1327 PyErr_Format(PyExc_SystemError,
1328 "Parent module %R not loaded, cannot perform relative "
1329 "import", package);
1330 goto error;
1331 }
1332 }
1333 else { /* level == 0 */
1334 if (PyUnicode_GET_LENGTH(name) == 0) {
1335 PyErr_SetString(PyExc_ValueError, "Empty module name");
1336 goto error;
1337 }
1338 package = Py_None;
1339 Py_INCREF(package);
1340 }
1341
1342 if (level > 0) {
1343 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1344 PyObject *base = NULL;
1345 int level_up = 1;
1346
1347 for (level_up = 1; level_up < level; level_up += 1) {
1348 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1349 if (last_dot == -2) {
1350 goto error;
1351 }
1352 else if (last_dot == -1) {
1353 PyErr_SetString(PyExc_ValueError,
1354 "attempted relative import beyond top-level "
1355 "package");
1356 goto error;
1357 }
1358 }
1359 base = PyUnicode_Substring(package, 0, last_dot);
1360 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001361 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001362
1363 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001364 seq = PyTuple_Pack(2, base, name);
1365 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001366 if (borrowed_dot == NULL || seq == NULL) {
1367 goto error;
1368 }
1369
1370 abs_name = PyUnicode_Join(borrowed_dot, seq);
1371 Py_DECREF(seq);
1372 if (abs_name == NULL) {
1373 goto error;
1374 }
1375 }
1376 else {
1377 abs_name = base;
1378 }
1379 }
1380 else {
1381 abs_name = name;
1382 Py_INCREF(abs_name);
1383 }
1384
Brian Curtine6b299f2012-04-14 14:19:33 -05001385#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001386 _PyImport_AcquireLock();
1387#endif
1388 /* From this point forward, goto error_with_unlock! */
1389 if (PyDict_Check(globals)) {
1390 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1391 }
1392 if (builtins_import == NULL) {
1393 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1394 if (builtins_import == NULL) {
Benjamin Peterson7d110042013-04-29 09:08:14 -04001395 PyErr_SetString(PyExc_ImportError, "__import__ not found");
1396 goto error_with_unlock;
Brett Cannonfd074152012-04-14 14:10:13 -04001397 }
1398 }
1399 Py_INCREF(builtins_import);
1400
1401 mod = PyDict_GetItem(interp->modules, abs_name);
1402 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001403 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1404 "None in sys.modules", abs_name);
1405 if (msg != NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -05001406 PyErr_SetImportError(msg, abs_name, NULL);
1407 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001408 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001409 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001410 goto error_with_unlock;
1411 }
1412 else if (mod != NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001413 PyObject *value;
1414 int initializing = 0;
1415
Brett Cannonfd074152012-04-14 14:10:13 -04001416 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001417 /* Optimization: only call _bootstrap._lock_unlock_module() if
1418 __initializing__ is true.
1419 NOTE: because of this, __initializing__ must be set *before*
1420 stuffing the new module in sys.modules.
1421 */
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001422 value = _PyObject_GetAttrId(mod, &PyId___initializing__);
1423 if (value == NULL)
1424 PyErr_Clear();
1425 else {
1426 initializing = PyObject_IsTrue(value);
1427 Py_DECREF(value);
1428 if (initializing == -1)
1429 PyErr_Clear();
1430 }
1431 if (initializing > 0) {
1432 /* _bootstrap._lock_unlock_module() releases the import lock */
1433 value = _PyObject_CallMethodObjIdArgs(interp->importlib,
1434 &PyId__lock_unlock_module, abs_name,
1435 NULL);
1436 if (value == NULL)
1437 goto error;
1438 Py_DECREF(value);
1439 }
1440 else {
1441#ifdef WITH_THREAD
1442 if (_PyImport_ReleaseLock() < 0) {
1443 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1444 goto error;
1445 }
1446#endif
1447 }
Brett Cannonfd074152012-04-14 14:10:13 -04001448 }
1449 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001450 /* _bootstrap._find_and_load() releases the import lock */
Brett Cannonfd074152012-04-14 14:10:13 -04001451 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1452 &PyId__find_and_load, abs_name,
1453 builtins_import, NULL);
1454 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001455 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001456 }
1457 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001458 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001459
1460 if (PyObject_Not(fromlist)) {
1461 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1462 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001463 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001464 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1465
1466 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001467 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001468 }
1469
Brian Curtine6b299f2012-04-14 14:19:33 -05001470 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001471 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001472 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001473 }
1474
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001475 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1476 /* No dot in module name, simple exit */
1477 Py_DECREF(partition);
1478 final_mod = mod;
1479 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001480 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001481 }
1482
Brett Cannonfd074152012-04-14 14:10:13 -04001483 front = PyTuple_GET_ITEM(partition, 0);
1484 Py_INCREF(front);
1485 Py_DECREF(partition);
1486
1487 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001488 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001489 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001490 }
1491 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001492 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1493 PyUnicode_GET_LENGTH(front);
1494 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001495 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001496 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001497 Py_DECREF(front);
1498 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001499 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001500 }
Brett Cannonfd074152012-04-14 14:10:13 -04001501
1502 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001503 if (final_mod == NULL) {
1504 PyErr_Format(PyExc_KeyError,
1505 "%R not in sys.modules as expected",
1506 to_return);
1507 }
1508 else {
1509 Py_INCREF(final_mod);
1510 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001511 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001512 }
1513 }
1514 else {
1515 final_mod = mod;
1516 Py_INCREF(mod);
1517 }
1518 }
1519 else {
1520 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1521 &PyId__handle_fromlist, mod,
1522 fromlist, builtins_import,
1523 NULL);
1524 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001525 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001526
Brett Cannonfd074152012-04-14 14:10:13 -04001527 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001528#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001529 if (_PyImport_ReleaseLock() < 0) {
1530 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1531 }
1532#endif
1533 error:
1534 Py_XDECREF(abs_name);
1535 Py_XDECREF(builtins_import);
1536 Py_XDECREF(mod);
1537 Py_XDECREF(package);
1538 Py_XDECREF(globals);
1539 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001540 if (final_mod == NULL)
1541 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001542 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001543}
1544
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001545PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001546PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001547 PyObject *fromlist, int level)
1548{
1549 PyObject *nameobj, *mod;
1550 nameobj = PyUnicode_FromString(name);
1551 if (nameobj == NULL)
1552 return NULL;
1553 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1554 fromlist, level);
1555 Py_DECREF(nameobj);
1556 return mod;
1557}
1558
1559
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001560/* Re-import a module of any kind and return its module object, WITH
1561 INCREMENTED REFERENCE COUNT */
1562
Guido van Rossum79f25d91997-04-29 20:08:16 +00001563PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001564PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001565{
Brett Cannon62228db2012-04-29 14:38:11 -04001566 _Py_IDENTIFIER(reload);
1567 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001569 PyObject *imp = PyDict_GetItemString(modules, "imp");
1570 if (imp == NULL) {
1571 imp = PyImport_ImportModule("imp");
1572 if (imp == NULL) {
1573 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 }
Brett Cannon62228db2012-04-29 14:38:11 -04001576 else {
1577 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001579
Brett Cannon62228db2012-04-29 14:38:11 -04001580 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1581 Py_DECREF(imp);
1582 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001583}
1584
1585
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001586/* Higher-level import emulator which emulates the "import" statement
1587 more accurately -- it invokes the __import__() function from the
1588 builtins of the current globals. This means that the import is
1589 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001590 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001591 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001592 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001593 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001594
1595PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001596PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 static PyObject *silly_list = NULL;
1599 static PyObject *builtins_str = NULL;
1600 static PyObject *import_str = NULL;
1601 PyObject *globals = NULL;
1602 PyObject *import = NULL;
1603 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001604 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 /* Initialize constant string objects */
1608 if (silly_list == NULL) {
1609 import_str = PyUnicode_InternFromString("__import__");
1610 if (import_str == NULL)
1611 return NULL;
1612 builtins_str = PyUnicode_InternFromString("__builtins__");
1613 if (builtins_str == NULL)
1614 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001615 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (silly_list == NULL)
1617 return NULL;
1618 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 /* Get the builtins from current globals */
1621 globals = PyEval_GetGlobals();
1622 if (globals != NULL) {
1623 Py_INCREF(globals);
1624 builtins = PyObject_GetItem(globals, builtins_str);
1625 if (builtins == NULL)
1626 goto err;
1627 }
1628 else {
1629 /* No globals -- use standard builtins, and fake globals */
1630 builtins = PyImport_ImportModuleLevel("builtins",
1631 NULL, NULL, NULL, 0);
1632 if (builtins == NULL)
1633 return NULL;
1634 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1635 if (globals == NULL)
1636 goto err;
1637 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 /* Get the __import__ function from the builtins */
1640 if (PyDict_Check(builtins)) {
1641 import = PyObject_GetItem(builtins, import_str);
1642 if (import == NULL)
1643 PyErr_SetObject(PyExc_KeyError, import_str);
1644 }
1645 else
1646 import = PyObject_GetAttr(builtins, import_str);
1647 if (import == NULL)
1648 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001651 Always use absolute import here.
1652 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1654 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001655 if (r == NULL)
1656 goto err;
1657 Py_DECREF(r);
1658
1659 modules = PyImport_GetModuleDict();
1660 r = PyDict_GetItem(modules, module_name);
1661 if (r != NULL)
1662 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001663
1664 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 Py_XDECREF(globals);
1666 Py_XDECREF(builtins);
1667 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001670}
1671
Barry Warsaw28a691b2010-04-17 00:19:56 +00001672static PyObject *
Brett Cannon2657df42012-05-04 15:20:40 -04001673imp_extension_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001676 const char *suffix;
1677 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 list = PyList_New(0);
1680 if (list == NULL)
1681 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001682#ifdef HAVE_DYNAMIC_LOADING
1683 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1684 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (item == NULL) {
1686 Py_DECREF(list);
1687 return NULL;
1688 }
1689 if (PyList_Append(list, item) < 0) {
1690 Py_DECREF(list);
1691 Py_DECREF(item);
1692 return NULL;
1693 }
1694 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001695 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 }
Brett Cannon2657df42012-05-04 15:20:40 -04001697#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001699}
1700
Guido van Rossum79f25d91997-04-29 20:08:16 +00001701static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001702imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001703{
Victor Stinner95872862011-03-07 18:20:56 +01001704 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 int ret;
1706 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01001707 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return NULL;
1709 ret = init_builtin(name);
1710 if (ret < 0)
1711 return NULL;
1712 if (ret == 0) {
1713 Py_INCREF(Py_None);
1714 return Py_None;
1715 }
Victor Stinner95872862011-03-07 18:20:56 +01001716 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 Py_XINCREF(m);
1718 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001719}
1720
Guido van Rossum79f25d91997-04-29 20:08:16 +00001721static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001722imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001723{
Victor Stinner53dc7352011-03-20 01:50:21 +01001724 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 int ret;
1726 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01001727 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001729 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 if (ret < 0)
1731 return NULL;
1732 if (ret == 0) {
1733 Py_INCREF(Py_None);
1734 return Py_None;
1735 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001736 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 Py_XINCREF(m);
1738 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001739}
1740
Guido van Rossum79f25d91997-04-29 20:08:16 +00001741static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001742imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001743{
Victor Stinner53dc7352011-03-20 01:50:21 +01001744 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00001745
Victor Stinner53dc7352011-03-20 01:50:21 +01001746 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 return NULL;
1748 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001749}
1750
Guido van Rossum79f25d91997-04-29 20:08:16 +00001751static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00001752imp_is_frozen_package(PyObject *self, PyObject *args)
1753{
Victor Stinner53dc7352011-03-20 01:50:21 +01001754 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00001755
Victor Stinner53dc7352011-03-20 01:50:21 +01001756 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 return NULL;
1758 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001759}
1760
1761static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001762imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001763{
Victor Stinner95872862011-03-07 18:20:56 +01001764 PyObject *name;
1765 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 return NULL;
1767 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001768}
1769
Guido van Rossum79f25d91997-04-29 20:08:16 +00001770static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001771imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001772{
Victor Stinner53dc7352011-03-20 01:50:21 +01001773 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01001775 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 return NULL;
1777 p = find_frozen(name);
1778 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001779}
1780
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001781#ifdef HAVE_DYNAMIC_LOADING
1782
Guido van Rossum79f25d91997-04-29 20:08:16 +00001783static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001784imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001785{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001786 PyObject *name, *pathname, *fob = NULL, *mod;
1787 FILE *fp;
1788
1789 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
1790 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001792 if (fob != NULL) {
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02001793 fp = _Py_fopen(pathname, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001794 if (fp == NULL) {
1795 Py_DECREF(pathname);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02001796 if (!PyErr_Occurred())
1797 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001799 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001801 else
1802 fp = NULL;
1803 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001804 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (fp)
1806 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001807 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001808}
1809
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001810#endif /* HAVE_DYNAMIC_LOADING */
1811
Barry Warsaw28a691b2010-04-17 00:19:56 +00001812
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001813/* Doc strings */
1814
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001815PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04001816"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001817
Brett Cannon2657df42012-05-04 15:20:40 -04001818PyDoc_STRVAR(doc_extension_suffixes,
1819"extension_suffixes() -> list of strings\n\
1820Returns the list of file suffixes used to identify extension modules.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001821
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001822PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00001823"lock_held() -> boolean\n\
1824Return True if the import lock is currently held, else False.\n\
1825On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00001826
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001827PyDoc_STRVAR(doc_acquire_lock,
1828"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00001829Acquires the interpreter's import lock for the current thread.\n\
1830This lock should be used by import hooks to ensure thread-safety\n\
1831when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001832On platforms without threads, this function does nothing.");
1833
1834PyDoc_STRVAR(doc_release_lock,
1835"release_lock() -> None\n\
1836Release the interpreter's import lock.\n\
1837On platforms without threads, this function does nothing.");
1838
Guido van Rossum79f25d91997-04-29 20:08:16 +00001839static PyMethodDef imp_methods[] = {
Brett Cannon2657df42012-05-04 15:20:40 -04001840 {"extension_suffixes", imp_extension_suffixes, METH_NOARGS,
1841 doc_extension_suffixes},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
1843 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
1844 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
1846 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
1847 {"init_builtin", imp_init_builtin, METH_VARARGS},
1848 {"init_frozen", imp_init_frozen, METH_VARARGS},
1849 {"is_builtin", imp_is_builtin, METH_VARARGS},
1850 {"is_frozen", imp_is_frozen, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001851#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001853#endif
Brett Cannon442c9b92011-03-23 16:14:42 -07001854 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001856};
1857
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001858
Martin v. Löwis1a214512008-06-11 05:26:20 +00001859static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04001861 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 doc_imp,
1863 0,
1864 imp_methods,
1865 NULL,
1866 NULL,
1867 NULL,
1868 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001869};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001870
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001871PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001872PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 m = PyModule_Create(&impmodule);
1877 if (m == NULL)
1878 goto failure;
1879 d = PyModule_GetDict(m);
1880 if (d == NULL)
1881 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001884 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 Py_XDECREF(m);
1886 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001887}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001888
1889
Guido van Rossumb18618d2000-05-03 23:44:39 +00001890/* API for embedding applications that want to add their own entries
1891 to the table of built-in modules. This should normally be called
1892 *before* Py_Initialize(). When the table resize fails, -1 is
1893 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001894
1895 After a similar function by Just van Rossum. */
1896
1897int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001898PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 static struct _inittab *our_copy = NULL;
1901 struct _inittab *p;
1902 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* Count the number of entries in both tables */
1905 for (n = 0; newtab[n].name != NULL; n++)
1906 ;
1907 if (n == 0)
1908 return 0; /* Nothing to do */
1909 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
1910 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* Allocate new memory for the combined table */
1913 p = our_copy;
1914 PyMem_RESIZE(p, struct _inittab, i+n+1);
1915 if (p == NULL)
1916 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* Copy the tables into the new memory */
1919 if (our_copy != PyImport_Inittab)
1920 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
1921 PyImport_Inittab = our_copy = p;
1922 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001925}
1926
1927/* Shorthand to add a single entry given a name and a function */
1928
1929int
Brett Cannona826f322009-04-02 03:41:46 +00001930PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 newtab[0].name = (char *)name;
1937 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00001940}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001941
1942#ifdef __cplusplus
1943}
1944#endif