blob: d201dae54fba0f6ffeac640007e5e64b7acb74f5 [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 */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
22extern "C" {
23#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Christian Heimesd3eb5a152008-02-24 00:38:49 +000025#ifdef MS_WINDOWS
26/* for stat.st_mode */
27typedef unsigned short mode_t;
28#endif
29
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000030extern time_t PyOS_GetLastModificationTime(char *, FILE *);
31 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000032
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000033/* Magic word to reject .pyc files generated by other Python versions.
34 It should change for each incompatible change to the bytecode.
35
36 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000037 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000038 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Guido van Rossum45aecf42006-03-15 04:58:47 +000040 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000041 -U interpeter flag will cause MAGIC+1 being used. They have been
42 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000044 There were a variety of old schemes for setting the magic number.
45 The current working scheme is to increment the previous value by
46 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000047
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000048 Known values:
49 Python 1.5: 20121
50 Python 1.5.1: 20121
51 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Python 2.0: 50823
54 Python 2.0.1: 50823
55 Python 2.1: 60202
56 Python 2.1.1: 60202
57 Python 2.1.2: 60202
58 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000059 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000060 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000061 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000062 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000063 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000064 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000065 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000066 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000067 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000068 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
70 Python 2.5b3: 62111 (fix wrong code: x += yield)
71 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
72 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000073 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000074 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000075 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000076 Python 3000: 3000
Brett Cannone2e23ef2006-08-25 05:05:30 +000077 3010 (removed UNARY_CONVERT)
Guido van Rossum86e58e22006-08-28 15:27:34 +000078 3020 (added BUILD_SET)
Guido van Rossum4f72a782006-10-27 23:31:49 +000079 3030 (added keyword-only parameters)
Guido van Rossum3203bdc2006-12-28 21:03:31 +000080 3040 (added signature annotations)
Guido van Rossum452bf512007-02-09 05:32:43 +000081 3050 (print becomes a function)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000082 3060 (PEP 3115 metaclass syntax)
Guido van Rossum00bc0e02007-10-15 02:52:41 +000083 3070 (PEP 3109 raise changes)
84 3080 (PEP 3137 make __file__ and __name__ unicode)
Guido van Rossum98297ee2007-11-06 21:34:58 +000085 3090 (kill str8 interning)
Christian Heimes99170a52007-12-19 02:07:34 +000086 3100 (merge from 2.6a0, see 62151)
Christian Heimes3b06e532008-01-07 20:12:44 +000087 3102 (__file__ points to source file)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000088 Python 3.0a4: 3110 (WITH_CLEANUP optimization).
Tim Peters36515e22001-11-18 04:06:29 +000089*/
Christian Heimesdd15f6c2008-03-16 00:07:10 +000090#define MAGIC (3110 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000091
Guido van Rossum96774c12000-05-01 20:19:08 +000092/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000093 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000094 compiler works which are enabled by command line switches. */
95static long pyc_magic = MAGIC;
96
Guido van Rossum25ce5661997-08-02 03:10:38 +000097/* See _PyImport_FixupExtension() below */
98static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000099
Guido van Rossum771c6c81997-10-31 18:37:24 +0000100/* This table is defined in config.c: */
101extern struct _inittab _PyImport_Inittab[];
102
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000103/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000104extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000105
Guido van Rossum771c6c81997-10-31 18:37:24 +0000106struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000107
Guido van Rossumed1170e1999-12-20 21:23:41 +0000108/* these tables define the module suffixes that Python recognizes */
109struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000110
Guido van Rossumed1170e1999-12-20 21:23:41 +0000111static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +0000112 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000113#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000114 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000115#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000116 {".pyc", "rb", PY_COMPILED},
117 {0, 0}
118};
119
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000121/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000122
123void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000124_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000126 const struct filedescr *scan;
127 struct filedescr *filetab;
128 int countD = 0;
129 int countS = 0;
130
131 /* prepare _PyImport_Filetab: copy entries from
132 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
133 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000134#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000135 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
136 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000137#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000138 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
139 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000140 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141 if (filetab == NULL)
142 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000143#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000144 memcpy(filetab, _PyImport_DynLoadFiletab,
145 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000146#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000147 memcpy(filetab + countD, _PyImport_StandardFiletab,
148 countS * sizeof(struct filedescr));
149 filetab[countD + countS].suffix = NULL;
150
151 _PyImport_Filetab = filetab;
152
Guido van Rossum0824f631997-03-11 18:37:35 +0000153 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000154 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
155 for (; filetab->suffix != NULL; filetab++) {
156 if (strcmp(filetab->suffix, ".pyc") == 0)
157 filetab->suffix = ".pyo";
Guido van Rossum0824f631997-03-11 18:37:35 +0000158 }
159 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000160
Guido van Rossum572dbf82007-04-27 23:53:51 +0000161 {
Guido van Rossum96774c12000-05-01 20:19:08 +0000162 /* Fix the pyc_magic so that byte compiled code created
163 using the all-Unicode method doesn't interfere with
164 code created in normal operation mode. */
165 pyc_magic = MAGIC + 1;
166 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167}
168
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169void
Just van Rossum52e14d62002-12-30 22:08:05 +0000170_PyImportHooks_Init(void)
171{
172 PyObject *v, *path_hooks = NULL, *zimpimport;
173 int err = 0;
174
175 /* adding sys.path_hooks and sys.path_importer_cache, setting up
176 zipimport */
Christian Heimes9cd17752007-11-18 19:35:23 +0000177 if (PyType_Ready(&PyNullImporter_Type) < 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000178 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000179
180 if (Py_VerboseFlag)
181 PySys_WriteStderr("# installing zipimport hook\n");
182
183 v = PyList_New(0);
184 if (v == NULL)
185 goto error;
186 err = PySys_SetObject("meta_path", v);
187 Py_DECREF(v);
188 if (err)
189 goto error;
190 v = PyDict_New();
191 if (v == NULL)
192 goto error;
193 err = PySys_SetObject("path_importer_cache", v);
194 Py_DECREF(v);
195 if (err)
196 goto error;
197 path_hooks = PyList_New(0);
198 if (path_hooks == NULL)
199 goto error;
200 err = PySys_SetObject("path_hooks", path_hooks);
201 if (err) {
202 error:
203 PyErr_Print();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000204 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
205 "path_importer_cache, or NullImporter failed"
206 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000207 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000208
Just van Rossum52e14d62002-12-30 22:08:05 +0000209 zimpimport = PyImport_ImportModule("zipimport");
210 if (zimpimport == NULL) {
211 PyErr_Clear(); /* No zip import module -- okay */
212 if (Py_VerboseFlag)
213 PySys_WriteStderr("# can't import zipimport\n");
214 }
215 else {
216 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
217 "zipimporter");
218 Py_DECREF(zimpimport);
219 if (zipimporter == NULL) {
220 PyErr_Clear(); /* No zipimporter object -- okay */
221 if (Py_VerboseFlag)
222 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000223 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000224 }
225 else {
226 /* sys.path_hooks.append(zipimporter) */
227 err = PyList_Append(path_hooks, zipimporter);
228 Py_DECREF(zipimporter);
229 if (err)
230 goto error;
231 if (Py_VerboseFlag)
232 PySys_WriteStderr(
233 "# installed zipimport hook\n");
234 }
235 }
236 Py_DECREF(path_hooks);
237}
238
239void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000240_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241{
242 Py_XDECREF(extensions);
243 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000244 PyMem_DEL(_PyImport_Filetab);
245 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000246}
247
248
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000249/* Locking primitives to prevent parallel imports of the same module
250 in different threads to return with a partially loaded module.
251 These calls are serialized by the global interpreter lock. */
252
253#ifdef WITH_THREAD
254
Guido van Rossum49b56061998-10-01 20:42:43 +0000255#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000256
Guido van Rossum65d5b571998-12-21 19:32:43 +0000257static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000258static long import_lock_thread = -1;
259static int import_lock_level = 0;
260
261static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000262lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000263{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000264 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000265 if (me == -1)
266 return; /* Too bad */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000267 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000268 import_lock = PyThread_allocate_lock();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000269 if (import_lock == NULL)
270 return; /* Nothing much we can do. */
271 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000272 if (import_lock_thread == me) {
273 import_lock_level++;
274 return;
275 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000276 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
277 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000278 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000279 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280 PyEval_RestoreThread(tstate);
281 }
282 import_lock_thread = me;
283 import_lock_level = 1;
284}
285
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000286static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000287unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000288{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000289 long me = PyThread_get_thread_ident();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000290 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000291 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000292 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000293 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000294 import_lock_level--;
295 if (import_lock_level == 0) {
296 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000297 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000298 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000299 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300}
301
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000302/* This function is called from PyOS_AfterFork to ensure that newly
303 created child processes do not share locks with the parent. */
304
305void
306_PyImport_ReInitLock(void)
307{
308#ifdef _AIX
309 if (import_lock != NULL)
310 import_lock = PyThread_allocate_lock();
311#endif
312}
313
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000314#else
315
316#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000317#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000318
319#endif
320
Tim Peters69232342001-08-30 05:16:13 +0000321static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000322imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000323{
Tim Peters69232342001-08-30 05:16:13 +0000324#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000325 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000326#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000327 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000328#endif
329}
330
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000331static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000332imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000333{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000334#ifdef WITH_THREAD
335 lock_import();
336#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000337 Py_INCREF(Py_None);
338 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000339}
340
341static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000342imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000343{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000344#ifdef WITH_THREAD
345 if (unlock_import() < 0) {
346 PyErr_SetString(PyExc_RuntimeError,
347 "not holding the import lock");
348 return NULL;
349 }
350#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000351 Py_INCREF(Py_None);
352 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353}
354
Guido van Rossumd8faa362007-04-27 19:54:29 +0000355static void
356imp_modules_reloading_clear(void)
357{
358 PyInterpreterState *interp = PyThreadState_Get()->interp;
359 if (interp->modules_reloading != NULL)
360 PyDict_Clear(interp->modules_reloading);
361}
362
Guido van Rossum25ce5661997-08-02 03:10:38 +0000363/* Helper for sys */
364
365PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000366PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000368 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000369 if (interp->modules == NULL)
370 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
371 return interp->modules;
372}
373
Guido van Rossum3f5da241990-12-20 15:06:42 +0000374
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000375/* List of names to clear in sys */
376static char* sys_deletes[] = {
Collin Winter670e6922007-03-21 02:57:17 +0000377 "path", "argv", "ps1", "ps2",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000378 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000379 "path_hooks", "path_importer_cache", "meta_path",
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000380 /* misc stuff */
381 "flags", "float_info",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000382 NULL
383};
384
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000385static char* sys_files[] = {
386 "stdin", "__stdin__",
387 "stdout", "__stdout__",
388 "stderr", "__stderr__",
389 NULL
390};
391
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000393/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000394
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000396PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000397{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000398 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000399 char *name;
400 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000401 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000402 PyObject *modules = interp->modules;
403
404 if (modules == NULL)
405 return; /* Already done */
406
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000407 /* Delete some special variables first. These are common
408 places where user values hide and people complain when their
409 destructors fail. Since the modules containing them are
410 deleted *last* of all, they would come too late in the normal
411 destruction order. Sigh. */
412
Georg Brandl1a3284e2007-12-02 09:40:06 +0000413 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000414 if (value != NULL && PyModule_Check(value)) {
415 dict = PyModule_GetDict(value);
416 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000417 PySys_WriteStderr("# clear builtins._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000418 PyDict_SetItemString(dict, "_", Py_None);
419 }
420 value = PyDict_GetItemString(modules, "sys");
421 if (value != NULL && PyModule_Check(value)) {
422 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000423 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000424 dict = PyModule_GetDict(value);
425 for (p = sys_deletes; *p != NULL; p++) {
426 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000427 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000428 PyDict_SetItemString(dict, *p, Py_None);
429 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000430 for (p = sys_files; *p != NULL; p+=2) {
431 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000432 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000433 v = PyDict_GetItemString(dict, *(p+1));
434 if (v == NULL)
435 v = Py_None;
436 PyDict_SetItemString(dict, *p, v);
437 }
438 }
439
440 /* First, delete __main__ */
441 value = PyDict_GetItemString(modules, "__main__");
442 if (value != NULL && PyModule_Check(value)) {
443 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000444 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000445 _PyModule_Clear(value);
446 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000447 }
448
Georg Brandl1a3284e2007-12-02 09:40:06 +0000449 /* The special treatment of "builtins" here is because even
Guido van Rossum758eec01998-01-19 21:58:26 +0000450 when it's not referenced as a module, its dictionary is
451 referenced by almost every module's __builtins__. Since
452 deleting a module clears its dictionary (even if there are
Georg Brandl1a3284e2007-12-02 09:40:06 +0000453 references left to it), we need to delete the "builtins"
Guido van Rossum758eec01998-01-19 21:58:26 +0000454 module last. Likewise, we don't delete sys until the very
455 end because it is implicitly referenced (e.g. by print).
456
457 Also note that we 'delete' modules by replacing their entry
458 in the modules dict with None, rather than really deleting
459 them; this avoids a rehash of the modules dictionary and
460 also marks them as "non existent" so they won't be
461 re-imported. */
462
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000463 /* Next, repeatedly delete modules with a reference count of
Georg Brandl1a3284e2007-12-02 09:40:06 +0000464 one (skipping builtins and sys) and delete them */
Guido van Rossum758eec01998-01-19 21:58:26 +0000465 do {
466 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000467 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000468 while (PyDict_Next(modules, &pos, &key, &value)) {
469 if (value->ob_refcnt != 1)
470 continue;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000471 if (PyUnicode_Check(key) && PyModule_Check(value)) {
472 name = PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000473 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000474 continue;
475 if (strcmp(name, "sys") == 0)
476 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000477 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000478 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000479 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000480 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000481 PyDict_SetItem(modules, key, Py_None);
482 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000483 }
484 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000485 } while (ndone > 0);
486
Georg Brandl1a3284e2007-12-02 09:40:06 +0000487 /* Next, delete all modules (still skipping builtins and sys) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000488 pos = 0;
489 while (PyDict_Next(modules, &pos, &key, &value)) {
Neal Norwitz80e7f272007-08-26 06:45:23 +0000490 if (PyUnicode_Check(key) && PyModule_Check(value)) {
491 name = PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000492 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000493 continue;
494 if (strcmp(name, "sys") == 0)
495 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000496 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000497 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000498 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000499 PyDict_SetItem(modules, key, Py_None);
500 }
501 }
502
Georg Brandl1a3284e2007-12-02 09:40:06 +0000503 /* Next, delete sys and builtins (in that order) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000504 value = PyDict_GetItemString(modules, "sys");
505 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000506 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000507 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000508 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000509 PyDict_SetItemString(modules, "sys", Py_None);
510 }
Georg Brandl1a3284e2007-12-02 09:40:06 +0000511 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossum758eec01998-01-19 21:58:26 +0000512 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000513 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000514 PySys_WriteStderr("# cleanup builtins\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000515 _PyModule_Clear(value);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000516 PyDict_SetItemString(modules, "builtins", Py_None);
Guido van Rossum758eec01998-01-19 21:58:26 +0000517 }
518
519 /* Finally, clear and delete the modules directory */
520 PyDict_Clear(modules);
521 interp->modules = NULL;
522 Py_DECREF(modules);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000524}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000525
526
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000527/* Helper for pythonrun.c -- return magic number */
528
529long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000530PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000531{
Guido van Rossum96774c12000-05-01 20:19:08 +0000532 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000533}
534
535
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536/* Magic for extension modules (built-in as well as dynamically
537 loaded). To prevent initializing an extension module more than
538 once, we keep a static dictionary 'extensions' keyed by module name
539 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000540 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541 dictionary is stored by calling _PyImport_FixupExtension()
542 immediately after the module initialization function succeeds. A
543 copy can be retrieved from there by calling
544 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000545
Guido van Rossum79f25d91997-04-29 20:08:16 +0000546PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000547_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000548{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549 PyObject *modules, *mod, *dict, *copy;
550 if (extensions == NULL) {
551 extensions = PyDict_New();
552 if (extensions == NULL)
553 return NULL;
554 }
555 modules = PyImport_GetModuleDict();
556 mod = PyDict_GetItemString(modules, name);
557 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000558 PyErr_Format(PyExc_SystemError,
559 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560 return NULL;
561 }
562 dict = PyModule_GetDict(mod);
563 if (dict == NULL)
564 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000565 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566 if (copy == NULL)
567 return NULL;
568 PyDict_SetItemString(extensions, filename, copy);
569 Py_DECREF(copy);
570 return copy;
571}
572
573PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000574_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000576 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577 if (extensions == NULL)
578 return NULL;
579 dict = PyDict_GetItemString(extensions, filename);
580 if (dict == NULL)
581 return NULL;
582 mod = PyImport_AddModule(name);
583 if (mod == NULL)
584 return NULL;
585 mdict = PyModule_GetDict(mod);
586 if (mdict == NULL)
587 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000588 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000591 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592 name, filename);
593 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000594}
595
596
597/* Get the module object corresponding to a module name.
598 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000599 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000600 Because the former action is most common, THIS DOES NOT RETURN A
601 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000602
Guido van Rossum79f25d91997-04-29 20:08:16 +0000603PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000604PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000605{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000607 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000608
Guido van Rossum25ce5661997-08-02 03:10:38 +0000609 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000610 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000611 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000612 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000613 if (m == NULL)
614 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000615 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000617 return NULL;
618 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000619 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620
621 return m;
622}
623
Tim Peters1cd70172004-08-02 03:52:12 +0000624/* Remove name from sys.modules, if it's there. */
625static void
626_RemoveModule(const char *name)
627{
628 PyObject *modules = PyImport_GetModuleDict();
629 if (PyDict_GetItemString(modules, name) == NULL)
630 return;
631 if (PyDict_DelItemString(modules, name) < 0)
632 Py_FatalError("import: deleting existing key in"
633 "sys.modules failed");
634}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000635
Christian Heimes3b06e532008-01-07 20:12:44 +0000636static PyObject * get_sourcefile(const char *file);
637
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000638/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000639 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
640 * removed from sys.modules, to avoid leaving damaged module objects
641 * in sys.modules. The caller may wish to restore the original
642 * module object (if any) in this case; PyImport_ReloadModule is an
643 * example.
644 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000645PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000646PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000647{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000648 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
649}
650
651PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000652PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000653{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000654 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656
Guido van Rossum79f25d91997-04-29 20:08:16 +0000657 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658 if (m == NULL)
659 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000660 /* If the module is being reloaded, we get the old module back
661 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000662 d = PyModule_GetDict(m);
663 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
664 if (PyDict_SetItemString(d, "__builtins__",
665 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000666 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000667 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000668 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000669 v = NULL;
670 if (pathname != NULL) {
Christian Heimes3b06e532008-01-07 20:12:44 +0000671 v = get_sourcefile(pathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000672 if (v == NULL)
673 PyErr_Clear();
674 }
675 if (v == NULL) {
676 v = ((PyCodeObject *)co)->co_filename;
677 Py_INCREF(v);
678 }
679 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000680 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000681 Py_DECREF(v);
682
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000683 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000684 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000685 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000686 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000687
Guido van Rossum25ce5661997-08-02 03:10:38 +0000688 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000689 PyErr_Format(PyExc_ImportError,
690 "Loaded module %.200s not found in sys.modules",
691 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000692 return NULL;
693 }
694
Guido van Rossum79f25d91997-04-29 20:08:16 +0000695 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696
697 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000698
699 error:
700 _RemoveModule(name);
701 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702}
703
704
705/* Given a pathname for a Python source file, fill a buffer with the
706 pathname for the corresponding compiled file. Return the pathname
707 for the compiled file, or NULL if there's no space in the buffer.
708 Doesn't set an exception. */
709
710static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000712{
Tim Petersc1731372001-08-04 08:12:36 +0000713 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714 if (len+2 > buflen)
715 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000716
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000717#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000718 /* Treat .pyw as if it were .py. The case of ".pyw" must match
719 that used in _PyImport_StandardFiletab. */
720 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
721 --len; /* pretend 'w' isn't there */
722#endif
723 memcpy(buf, pathname, len);
724 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
725 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000726
727 return buf;
728}
729
730
731/* Given a pathname for a Python source file, its time of last
732 modification, and a pathname for a compiled file, check whether the
733 compiled file represents the same version of the source. If so,
734 return a FILE pointer for the compiled file, positioned just after
735 the header; if not, return NULL.
736 Doesn't set an exception. */
737
738static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000739check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740{
741 FILE *fp;
742 long magic;
743 long pyc_mtime;
744
745 fp = fopen(cpathname, "rb");
746 if (fp == NULL)
747 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000748 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000749 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000750 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000751 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000752 fclose(fp);
753 return NULL;
754 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000756 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000757 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000758 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759 fclose(fp);
760 return NULL;
761 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000762 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000763 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000764 return fp;
765}
766
767
768/* Read a code object from a file and check it for validity */
769
Guido van Rossum79f25d91997-04-29 20:08:16 +0000770static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000771read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000772{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000773 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000774
Tim Petersd9b9ac82001-01-28 00:27:39 +0000775 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000776 if (co == NULL)
777 return NULL;
778 if (!PyCode_Check(co)) {
779 PyErr_Format(PyExc_ImportError,
780 "Non-code object in %.200s", cpathname);
781 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000782 return NULL;
783 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000784 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785}
786
787
788/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000789 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000790
Guido van Rossum79f25d91997-04-29 20:08:16 +0000791static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000792load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793{
794 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000795 PyCodeObject *co;
796 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000797
Guido van Rossum79f25d91997-04-29 20:08:16 +0000798 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000799 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000800 PyErr_Format(PyExc_ImportError,
801 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000802 return NULL;
803 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000804 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000805 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000806 if (co == NULL)
807 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000808 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000809 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000810 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000811 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000812 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813
814 return m;
815}
816
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817/* Parse a source file and return the corresponding code object */
818
Guido van Rossum79f25d91997-04-29 20:08:16 +0000819static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000820parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000821{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822 PyCodeObject *co = NULL;
823 mod_ty mod;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000824 PyArena *arena = PyArena_New();
825 if (arena == NULL)
826 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000827
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000828 mod = PyParser_ASTFromFile(fp, pathname, NULL,
829 Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000830 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000832 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835 return co;
836}
837
838
Guido van Rossum55a83382000-09-20 20:31:38 +0000839/* Helper to open a bytecode file for writing in exclusive mode */
840
841static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +0000842open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +0000843{
844#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
845 /* Use O_EXCL to avoid a race condition when another process tries to
846 write the same file. When that happens, our open() call fails,
847 which is just fine (since it's only a cache).
848 XXX If the file exists and is writable but the directory is not
849 writable, the file will never be written. Oh well.
850 */
851 int fd;
852 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000853 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
854#ifdef O_BINARY
855 |O_BINARY /* necessary for Windows */
856#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000857#ifdef __VMS
Christian Heimes05e8be12008-02-23 18:30:17 +0000858 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000859#else
Christian Heimes05e8be12008-02-23 18:30:17 +0000860 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000861#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000862 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000863 if (fd < 0)
864 return NULL;
865 return fdopen(fd, "wb");
866#else
867 /* Best we can do -- on Windows this can't happen anyway */
868 return fopen(filename, "wb");
869#endif
870}
871
872
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000873/* Write a compiled module to a file, placing the time of last
874 modification of its source into the header.
875 Errors are ignored, if a write error occurs an attempt is made to
876 remove the file. */
877
878static void
Christian Heimes05e8be12008-02-23 18:30:17 +0000879write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000880{
881 FILE *fp;
Christian Heimes05e8be12008-02-23 18:30:17 +0000882 time_t mtime = srcstat->st_mtime;
883 mode_t mode = srcstat->st_mode;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884
Christian Heimes05e8be12008-02-23 18:30:17 +0000885 fp = open_exclusive(cpathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000887 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000888 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000889 "# can't create %s\n", cpathname);
890 return;
891 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000892 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000893 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000894 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
895 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000896 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000897 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000898 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000899 /* Don't keep partial file */
900 fclose(fp);
901 (void) unlink(cpathname);
902 return;
903 }
904 /* Now write the true mtime */
905 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000906 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000907 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000908 fflush(fp);
909 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000910 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000911 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912}
913
914
915/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000916 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
917 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000918
Guido van Rossum79f25d91997-04-29 20:08:16 +0000919static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000920load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000921{
Christian Heimes05e8be12008-02-23 18:30:17 +0000922 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000923 FILE *fpc;
924 char buf[MAXPATHLEN+1];
925 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000926 PyCodeObject *co;
927 PyObject *m;
Christian Heimes05e8be12008-02-23 18:30:17 +0000928
929 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +0000930 PyErr_Format(PyExc_RuntimeError,
Christian Heimes05e8be12008-02-23 18:30:17 +0000931 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +0000932 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000933 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000934 }
Fred Drake4c82b232000-06-30 16:18:57 +0000935#if SIZEOF_TIME_T > 4
936 /* Python's .pyc timestamp handling presumes that the timestamp fits
937 in 4 bytes. This will be fine until sometime in the year 2038,
938 when a 4-byte signed time_t will overflow.
939 */
Christian Heimes05e8be12008-02-23 18:30:17 +0000940 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +0000941 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000942 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000943 return NULL;
944 }
945#endif
Tim Peters36515e22001-11-18 04:06:29 +0000946 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000947 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000948 if (cpathname != NULL &&
Christian Heimes05e8be12008-02-23 18:30:17 +0000949 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000950 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000951 fclose(fpc);
952 if (co == NULL)
953 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000954 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000955 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000956 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000957 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000958 }
959 else {
960 co = parse_source_module(pathname, fp);
961 if (co == NULL)
962 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000963 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000964 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000965 name, pathname);
Christian Heimes790c8232008-01-07 21:14:23 +0000966 if (cpathname) {
967 PyObject *ro = PySys_GetObject("dont_write_bytecode");
968 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes05e8be12008-02-23 18:30:17 +0000969 write_compiled_module(co, cpathname, &st);
Christian Heimes790c8232008-01-07 21:14:23 +0000970 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000971 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000972 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000973 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000974
975 return m;
976}
977
Christian Heimes3b06e532008-01-07 20:12:44 +0000978/* Get source file -> unicode or None
979 * Returns the path to the py file if available, else the given path
980 */
981static PyObject *
982get_sourcefile(const char *file)
983{
984 char py[MAXPATHLEN + 1];
985 Py_ssize_t len;
986 PyObject *u;
987 struct stat statbuf;
988
989 if (!file || !*file) {
990 Py_RETURN_NONE;
991 }
992
993 len = strlen(file);
Christian Heimes3540b502008-01-11 07:03:05 +0000994 /* match '*.py?' */
995 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
Christian Heimes3b06e532008-01-07 20:12:44 +0000996 return PyUnicode_DecodeFSDefault(file);
997 }
998
999 strncpy(py, file, len-1);
Martin v. Löwis5021ebc2008-03-22 22:07:13 +00001000 py[len-1] = '\0';
Christian Heimes3b06e532008-01-07 20:12:44 +00001001 if (stat(py, &statbuf) == 0 &&
1002 S_ISREG(statbuf.st_mode)) {
1003 u = PyUnicode_DecodeFSDefault(py);
1004 }
1005 else {
1006 u = PyUnicode_DecodeFSDefault(file);
1007 }
1008 return u;
1009}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001010
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001011/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001012static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1013static struct filedescr *find_module(char *, char *, PyObject *,
1014 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001015static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001016
1017/* Load a package and return its module object WITH INCREMENTED
1018 REFERENCE COUNT */
1019
1020static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001021load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001022{
Tim Peters1cd70172004-08-02 03:52:12 +00001023 PyObject *m, *d;
1024 PyObject *file = NULL;
1025 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001026 int err;
1027 char buf[MAXPATHLEN+1];
1028 FILE *fp = NULL;
1029 struct filedescr *fdp;
1030
1031 m = PyImport_AddModule(name);
1032 if (m == NULL)
1033 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001034 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001035 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001036 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001037 d = PyModule_GetDict(m);
Christian Heimes3b06e532008-01-07 20:12:44 +00001038 file = get_sourcefile(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001039 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +00001040 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001041 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001042 if (path == NULL)
1043 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001044 err = PyDict_SetItemString(d, "__file__", file);
1045 if (err == 0)
1046 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001047 if (err != 0)
1048 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001049 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001050 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001051 if (fdp == NULL) {
1052 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1053 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001054 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001055 }
1056 else
1057 m = NULL;
1058 goto cleanup;
1059 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001060 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001061 if (fp != NULL)
1062 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001063 goto cleanup;
1064
1065 error:
1066 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001067 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001068 Py_XDECREF(path);
1069 Py_XDECREF(file);
1070 return m;
1071}
1072
1073
1074/* Helper to test for built-in module */
1075
1076static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001077is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001078{
1079 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001080 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1081 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1082 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001083 return -1;
1084 else
1085 return 1;
1086 }
1087 }
1088 return 0;
1089}
1090
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001091
Just van Rossum52e14d62002-12-30 22:08:05 +00001092/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1093 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001094 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001095 that can handle the path item. Return None if no hook could;
1096 this tells our caller it should fall back to the builtin
1097 import mechanism. Cache the result in path_importer_cache.
1098 Returns a borrowed reference. */
1099
1100static PyObject *
1101get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1102 PyObject *p)
1103{
1104 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001105 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001106
1107 /* These conditions are the caller's responsibility: */
1108 assert(PyList_Check(path_hooks));
1109 assert(PyDict_Check(path_importer_cache));
1110
1111 nhooks = PyList_Size(path_hooks);
1112 if (nhooks < 0)
1113 return NULL; /* Shouldn't happen */
1114
1115 importer = PyDict_GetItem(path_importer_cache, p);
1116 if (importer != NULL)
1117 return importer;
1118
1119 /* set path_importer_cache[p] to None to avoid recursion */
1120 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1121 return NULL;
1122
1123 for (j = 0; j < nhooks; j++) {
1124 PyObject *hook = PyList_GetItem(path_hooks, j);
1125 if (hook == NULL)
1126 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001128 if (importer != NULL)
1129 break;
1130
1131 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1132 return NULL;
1133 }
1134 PyErr_Clear();
1135 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001136 if (importer == NULL) {
1137 importer = PyObject_CallFunctionObjArgs(
Christian Heimes9cd17752007-11-18 19:35:23 +00001138 (PyObject *)&PyNullImporter_Type, p, NULL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001139 );
1140 if (importer == NULL) {
1141 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1142 PyErr_Clear();
1143 return Py_None;
1144 }
1145 }
1146 }
1147 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001148 int err = PyDict_SetItem(path_importer_cache, p, importer);
1149 Py_DECREF(importer);
1150 if (err != 0)
1151 return NULL;
1152 }
1153 return importer;
1154}
1155
Christian Heimes9cd17752007-11-18 19:35:23 +00001156PyAPI_FUNC(PyObject *)
1157PyImport_GetImporter(PyObject *path) {
1158 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1159
1160 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1161 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1162 importer = get_path_importer(path_importer_cache,
1163 path_hooks, path);
1164 }
1165 }
1166 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1167 return importer;
1168}
1169
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001170/* Search the path (default sys.path) for a module. Return the
1171 corresponding filedescr struct, and (via return arguments) the
1172 pathname and an open file. Return NULL if the module is not found. */
1173
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001174#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001175extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001176 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001177#endif
1178
Martin v. Löwis18e16552006-02-15 17:27:45 +00001179static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001180static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001181static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001182
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001183static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001184find_module(char *fullname, char *subname, PyObject *path, char *buf,
1185 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001186{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001187 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001188 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001189 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001190 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001191 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001192 PyObject *path_hooks, *path_importer_cache;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001193 struct stat statbuf;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001194 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1195 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1196 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001197 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001198#if defined(PYOS_OS2)
1199 size_t saved_len;
1200 size_t saved_namelen;
1201 char *saved_buf = NULL;
1202#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001203 if (p_loader != NULL)
1204 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001205
Just van Rossum52e14d62002-12-30 22:08:05 +00001206 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001207 PyErr_SetString(PyExc_OverflowError,
1208 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001209 return NULL;
1210 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001211 strcpy(name, subname);
1212
1213 /* sys.meta_path import hook */
1214 if (p_loader != NULL) {
1215 PyObject *meta_path;
1216
1217 meta_path = PySys_GetObject("meta_path");
1218 if (meta_path == NULL || !PyList_Check(meta_path)) {
1219 PyErr_SetString(PyExc_ImportError,
1220 "sys.meta_path must be a list of "
1221 "import hooks");
1222 return NULL;
1223 }
1224 Py_INCREF(meta_path); /* zap guard */
1225 npath = PyList_Size(meta_path);
1226 for (i = 0; i < npath; i++) {
1227 PyObject *loader;
1228 PyObject *hook = PyList_GetItem(meta_path, i);
1229 loader = PyObject_CallMethod(hook, "find_module",
1230 "sO", fullname,
1231 path != NULL ?
1232 path : Py_None);
1233 if (loader == NULL) {
1234 Py_DECREF(meta_path);
1235 return NULL; /* true error */
1236 }
1237 if (loader != Py_None) {
1238 /* a loader was found */
1239 *p_loader = loader;
1240 Py_DECREF(meta_path);
1241 return &importhookdescr;
1242 }
1243 Py_DECREF(loader);
1244 }
1245 Py_DECREF(meta_path);
1246 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001247
Guido van Rossum13d77992007-07-23 03:16:50 +00001248 if (path != NULL && PyUnicode_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001249 /* The only type of submodule allowed inside a "frozen"
1250 package are other frozen modules or packages. */
Guido van Rossum13d77992007-07-23 03:16:50 +00001251 char *p = PyUnicode_AsString(path);
1252 if (strlen(p) + 1 + strlen(name) >= (size_t)buflen) {
Guido van Rossum0506a431998-08-11 15:07:39 +00001253 PyErr_SetString(PyExc_ImportError,
1254 "full frozen module name too long");
1255 return NULL;
1256 }
Guido van Rossum13d77992007-07-23 03:16:50 +00001257 strcpy(buf, p);
Guido van Rossum0506a431998-08-11 15:07:39 +00001258 strcat(buf, ".");
1259 strcat(buf, name);
1260 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001261 if (find_frozen(name) != NULL) {
1262 strcpy(buf, name);
1263 return &fd_frozen;
1264 }
1265 PyErr_Format(PyExc_ImportError,
1266 "No frozen submodule named %.200s", name);
1267 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001268 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001269 if (path == NULL) {
1270 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001271 strcpy(buf, name);
1272 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001273 }
Greg Ward201baee2001-10-04 14:52:06 +00001274 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001275 strcpy(buf, name);
1276 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001277 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001278
Guido van Rossumac279101996-08-22 23:10:58 +00001279#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001280 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1281 if (fp != NULL) {
1282 *p_fp = fp;
1283 return fdp;
1284 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001285#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001286 path = PySys_GetObject("path");
1287 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001288 if (path == NULL || !PyList_Check(path)) {
1289 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001290 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001291 return NULL;
1292 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001293
1294 path_hooks = PySys_GetObject("path_hooks");
1295 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1296 PyErr_SetString(PyExc_ImportError,
1297 "sys.path_hooks must be a list of "
1298 "import hooks");
1299 return NULL;
1300 }
1301 path_importer_cache = PySys_GetObject("path_importer_cache");
1302 if (path_importer_cache == NULL ||
1303 !PyDict_Check(path_importer_cache)) {
1304 PyErr_SetString(PyExc_ImportError,
1305 "sys.path_importer_cache must be a dict");
1306 return NULL;
1307 }
1308
Guido van Rossum79f25d91997-04-29 20:08:16 +00001309 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001310 namelen = strlen(name);
1311 for (i = 0; i < npath; i++) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001312 PyObject *v = PyList_GetItem(path, i);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001313 PyObject *origv = v;
Guido van Rossum6262cc72007-05-09 23:29:27 +00001314 const char *base;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001315 Py_ssize_t size;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001316 if (!v)
1317 return NULL;
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +00001318 if (PyUnicode_Check(v)) {
1319 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1320 if (v == NULL)
1321 return NULL;
1322 }
1323 if (!PyString_Check(v))
1324 continue;
1325 base = PyString_AS_STRING(v);
1326 size = PyString_GET_SIZE(v);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001327 len = size;
Walter Dörwald3430d702002-06-17 10:43:59 +00001328 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001329 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001330 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001331 strcpy(buf, base);
Walter Dörwald3430d702002-06-17 10:43:59 +00001332 if (strlen(buf) != len) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001333 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001334 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001335
1336 /* sys.path_hooks import hook */
1337 if (p_loader != NULL) {
1338 PyObject *importer;
1339
1340 importer = get_path_importer(path_importer_cache,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001341 path_hooks, origv);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001342 if (importer == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001343 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001344 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001345 /* Note: importer is a borrowed reference */
1346 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001347 PyObject *loader;
1348 loader = PyObject_CallMethod(importer,
1349 "find_module",
1350 "s", fullname);
1351 if (loader == NULL)
1352 return NULL; /* error */
1353 if (loader != Py_None) {
1354 /* a loader was found */
1355 *p_loader = loader;
1356 return &importhookdescr;
1357 }
1358 Py_DECREF(loader);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001360 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001361 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001362 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001363
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001364 if (len > 0 && buf[len-1] != SEP
1365#ifdef ALTSEP
1366 && buf[len-1] != ALTSEP
1367#endif
1368 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001369 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001370 strcpy(buf+len, name);
1371 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001372
1373 /* Check for package import (buf holds a directory name,
1374 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001375#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001376 if (stat(buf, &statbuf) == 0 && /* it exists */
1377 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378 case_ok(buf, len, namelen, name)) { /* case matches */
1379 if (find_init_module(buf)) { /* and has __init__.py */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001380 return &fd_package;
1381 }
1382 else {
1383 char warnstr[MAXPATHLEN+80];
1384 sprintf(warnstr, "Not importing directory "
1385 "'%.*s': missing __init__.py",
1386 MAXPATHLEN, buf);
Skip Montanaro46fc3372007-08-12 11:44:53 +00001387 if (PyErr_WarnEx(PyExc_ImportWarning,
1388 warnstr, 1)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001389 return NULL;
1390 }
1391 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001392 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001393#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001394#if defined(PYOS_OS2)
1395 /* take a snapshot of the module spec for restoration
1396 * after the 8 character DLL hackery
1397 */
1398 saved_buf = strdup(buf);
1399 saved_len = len;
1400 saved_namelen = namelen;
1401#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001402 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001403#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001404 /* OS/2 limits DLLs to 8 character names (w/o
1405 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001406 * so if the name is longer than that and its a
1407 * dynamically loaded module we're going to try,
1408 * truncate the name before trying
1409 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001410 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001411 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001412 const struct filedescr *scan;
1413 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001414 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001415 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001416 break;
1417 else
1418 scan++;
1419 }
1420 if (scan->suffix != NULL) {
1421 /* yes, so truncate the name */
1422 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001423 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001424 buf[len] = '\0';
1425 }
1426 }
1427#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001428 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001429 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001430 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001431 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001432 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001433 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001434 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001435 if (fp != NULL) {
1436 if (case_ok(buf, len, namelen, name))
1437 break;
1438 else { /* continue search */
1439 fclose(fp);
1440 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001441 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001442 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001443#if defined(PYOS_OS2)
1444 /* restore the saved snapshot */
1445 strcpy(buf, saved_buf);
1446 len = saved_len;
1447 namelen = saved_namelen;
1448#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001449 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001450#if defined(PYOS_OS2)
1451 /* don't need/want the module name snapshot anymore */
1452 if (saved_buf)
1453 {
1454 free(saved_buf);
1455 saved_buf = NULL;
1456 }
1457#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001458 if (fp != NULL)
1459 break;
1460 }
1461 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001462 PyErr_Format(PyExc_ImportError,
1463 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001464 return NULL;
1465 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001466 *p_fp = fp;
1467 return fdp;
1468}
1469
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001470/* Helpers for main.c
1471 * Find the source file corresponding to a named module
1472 */
1473struct filedescr *
1474_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1475 size_t buflen, FILE **p_fp, PyObject **p_loader)
1476{
1477 return find_module((char *) name, (char *) name, path,
1478 buf, buflen, p_fp, p_loader);
1479}
1480
1481PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1482{
1483 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1484}
1485
Martin v. Löwis18e16552006-02-15 17:27:45 +00001486/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001487 * The arguments here are tricky, best shown by example:
1488 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1489 * ^ ^ ^ ^
1490 * |--------------------- buf ---------------------|
1491 * |------------------- len ------------------|
1492 * |------ name -------|
1493 * |----- namelen -----|
1494 * buf is the full path, but len only counts up to (& exclusive of) the
1495 * extension. name is the module name, also exclusive of extension.
1496 *
1497 * We've already done a successful stat() or fopen() on buf, so know that
1498 * there's some match, possibly case-insensitive.
1499 *
Tim Peters50d8d372001-02-28 05:34:27 +00001500 * case_ok() is to return 1 if there's a case-sensitive match for
1501 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1502 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001503 *
Tim Peters50d8d372001-02-28 05:34:27 +00001504 * case_ok() is used to implement case-sensitive import semantics even
1505 * on platforms with case-insensitive filesystems. It's trivial to implement
1506 * for case-sensitive filesystems. It's pretty much a cross-platform
1507 * nightmare for systems with case-insensitive filesystems.
1508 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001509
Tim Peters50d8d372001-02-28 05:34:27 +00001510/* First we may need a pile of platform-specific header files; the sequence
1511 * of #if's here should match the sequence in the body of case_ok().
1512 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001513#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001514#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001515
Tim Peters50d8d372001-02-28 05:34:27 +00001516#elif defined(DJGPP)
1517#include <dir.h>
1518
Jason Tishler7961aa62005-05-20 00:56:54 +00001519#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001520#include <sys/types.h>
1521#include <dirent.h>
1522
Andrew MacIntyred9400542002-02-26 11:41:34 +00001523#elif defined(PYOS_OS2)
1524#define INCL_DOS
1525#define INCL_DOSERRORS
1526#define INCL_NOPMAPI
1527#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001528#endif
1529
Guido van Rossum0980bd91998-02-13 17:18:36 +00001530static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001531case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001532{
Tim Peters50d8d372001-02-28 05:34:27 +00001533/* Pick a platform-specific implementation; the sequence of #if's here should
1534 * match the sequence just above.
1535 */
1536
Jason Tishler7961aa62005-05-20 00:56:54 +00001537/* MS_WINDOWS */
1538#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001539 WIN32_FIND_DATA data;
1540 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001541
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001542 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001543 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001544
Guido van Rossum0980bd91998-02-13 17:18:36 +00001545 h = FindFirstFile(buf, &data);
1546 if (h == INVALID_HANDLE_VALUE) {
1547 PyErr_Format(PyExc_NameError,
1548 "Can't find file for module %.100s\n(filename %.300s)",
1549 name, buf);
1550 return 0;
1551 }
1552 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001553 return strncmp(data.cFileName, name, namelen) == 0;
1554
1555/* DJGPP */
1556#elif defined(DJGPP)
1557 struct ffblk ffblk;
1558 int done;
1559
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001560 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001561 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001562
1563 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1564 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001565 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001566 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001567 name, buf);
1568 return 0;
1569 }
Tim Peters50d8d372001-02-28 05:34:27 +00001570 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001571
Jason Tishler7961aa62005-05-20 00:56:54 +00001572/* new-fangled macintosh (macosx) or Cygwin */
1573#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001574 DIR *dirp;
1575 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001576 char dirname[MAXPATHLEN + 1];
1577 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001578
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001579 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001580 return 1;
1581
Tim Petersd1e87a82001-03-01 18:12:00 +00001582 /* Copy the dir component into dirname; substitute "." if empty */
1583 if (dirlen <= 0) {
1584 dirname[0] = '.';
1585 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001586 }
1587 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001588 assert(dirlen <= MAXPATHLEN);
1589 memcpy(dirname, buf, dirlen);
1590 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001591 }
1592 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001593 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001594 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001595 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001596 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001597 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001598#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001599 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001600#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001601 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001602#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001603 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001604 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001605 (void)closedir(dirp);
1606 return 1; /* Found */
1607 }
1608 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001609 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001610 }
Tim Peters430f5d42001-03-01 01:30:56 +00001611 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001612
Andrew MacIntyred9400542002-02-26 11:41:34 +00001613/* OS/2 */
1614#elif defined(PYOS_OS2)
1615 HDIR hdir = 1;
1616 ULONG srchcnt = 1;
1617 FILEFINDBUF3 ffbuf;
1618 APIRET rc;
1619
Christian Heimes790c8232008-01-07 21:14:23 +00001620 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001621 return 1;
1622
1623 rc = DosFindFirst(buf,
1624 &hdir,
1625 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1626 &ffbuf, sizeof(ffbuf),
1627 &srchcnt,
1628 FIL_STANDARD);
1629 if (rc != NO_ERROR)
1630 return 0;
1631 return strncmp(ffbuf.achName, name, namelen) == 0;
1632
Tim Peters50d8d372001-02-28 05:34:27 +00001633/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1634#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001635 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001636
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001637#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001638}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001639
Guido van Rossum0980bd91998-02-13 17:18:36 +00001640
Guido van Rossum197346f1997-10-31 18:38:52 +00001641#ifdef HAVE_STAT
1642/* Helper to look for __init__.py or __init__.py[co] in potential package */
1643static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001644find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001645{
Tim Peters0f9431f2001-07-05 03:47:53 +00001646 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001647 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001648 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001649 struct stat statbuf;
1650
Tim Peters0f9431f2001-07-05 03:47:53 +00001651/* For calling case_ok(buf, len, namelen, name):
1652 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1653 * ^ ^ ^ ^
1654 * |--------------------- buf ---------------------|
1655 * |------------------- len ------------------|
1656 * |------ name -------|
1657 * |----- namelen -----|
1658 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001659 if (save_len + 13 >= MAXPATHLEN)
1660 return 0;
1661 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001662 pname = buf + i;
1663 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001664 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001665 if (case_ok(buf,
1666 save_len + 9, /* len("/__init__") */
1667 8, /* len("__init__") */
1668 pname)) {
1669 buf[save_len] = '\0';
1670 return 1;
1671 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001672 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001673 i += strlen(pname);
1674 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001675 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001676 if (case_ok(buf,
1677 save_len + 9, /* len("/__init__") */
1678 8, /* len("__init__") */
1679 pname)) {
1680 buf[save_len] = '\0';
1681 return 1;
1682 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001683 }
1684 buf[save_len] = '\0';
1685 return 0;
1686}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001687
Guido van Rossum197346f1997-10-31 18:38:52 +00001688#endif /* HAVE_STAT */
1689
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001690
Tim Petersdbd9ba62000-07-09 03:09:57 +00001691static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001692
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001693/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001694 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001695
Guido van Rossum79f25d91997-04-29 20:08:16 +00001696static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001697load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001698{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001699 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001700 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001701 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001702
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001703 /* First check that there's an open file (if we need one) */
1704 switch (type) {
1705 case PY_SOURCE:
1706 case PY_COMPILED:
1707 if (fp == NULL) {
1708 PyErr_Format(PyExc_ValueError,
1709 "file object required for import (type code %d)",
1710 type);
1711 return NULL;
1712 }
1713 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001714
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001715 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001716
1717 case PY_SOURCE:
1718 m = load_source_module(name, buf, fp);
1719 break;
1720
1721 case PY_COMPILED:
1722 m = load_compiled_module(name, buf, fp);
1723 break;
1724
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001725#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001726 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001727 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001728 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001729#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001730
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001731 case PKG_DIRECTORY:
1732 m = load_package(name, buf);
1733 break;
1734
1735 case C_BUILTIN:
1736 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001737 if (buf != NULL && buf[0] != '\0')
1738 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001739 if (type == C_BUILTIN)
1740 err = init_builtin(name);
1741 else
1742 err = PyImport_ImportFrozenModule(name);
1743 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001744 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001745 if (err == 0) {
1746 PyErr_Format(PyExc_ImportError,
1747 "Purported %s module %.200s not found",
1748 type == C_BUILTIN ?
1749 "builtin" : "frozen",
1750 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001751 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001752 }
1753 modules = PyImport_GetModuleDict();
1754 m = PyDict_GetItemString(modules, name);
1755 if (m == NULL) {
1756 PyErr_Format(
1757 PyExc_ImportError,
1758 "%s module %.200s not properly initialized",
1759 type == C_BUILTIN ?
1760 "builtin" : "frozen",
1761 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001762 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001763 }
1764 Py_INCREF(m);
1765 break;
1766
Just van Rossum52e14d62002-12-30 22:08:05 +00001767 case IMP_HOOK: {
1768 if (loader == NULL) {
1769 PyErr_SetString(PyExc_ImportError,
1770 "import hook without loader");
1771 return NULL;
1772 }
1773 m = PyObject_CallMethod(loader, "load_module", "s", name);
1774 break;
1775 }
1776
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001777 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001778 PyErr_Format(PyExc_ImportError,
1779 "Don't know how to import %.200s (type code %d)",
1780 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001781 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001782
1783 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001784
1785 return m;
1786}
1787
1788
1789/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001790 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001791 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001792
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001793static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001794init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001795{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001796 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001797
Greg Ward201baee2001-10-04 14:52:06 +00001798 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001799 return 1;
1800
Guido van Rossum771c6c81997-10-31 18:37:24 +00001801 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001802 if (strcmp(name, p->name) == 0) {
1803 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001804 PyErr_Format(PyExc_ImportError,
1805 "Cannot re-init internal module %.200s",
1806 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001807 return -1;
1808 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001809 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001810 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001811 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001812 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001813 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001814 if (_PyImport_FixupExtension(name, name) == NULL)
1815 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001816 return 1;
1817 }
1818 }
1819 return 0;
1820}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001821
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001822
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001823/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001824
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001825static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001826find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001827{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001828 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001829
Guido van Rossum79f25d91997-04-29 20:08:16 +00001830 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001831 if (p->name == NULL)
1832 return NULL;
1833 if (strcmp(p->name, name) == 0)
1834 break;
1835 }
1836 return p;
1837}
1838
Guido van Rossum79f25d91997-04-29 20:08:16 +00001839static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001840get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001841{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001842 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001843 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001844
1845 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001846 PyErr_Format(PyExc_ImportError,
1847 "No such frozen object named %.200s",
1848 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001849 return NULL;
1850 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001851 if (p->code == NULL) {
1852 PyErr_Format(PyExc_ImportError,
1853 "Excluded frozen object named %.200s",
1854 name);
1855 return NULL;
1856 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001857 size = p->size;
1858 if (size < 0)
1859 size = -size;
1860 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001861}
1862
1863/* Initialize a frozen module.
1864 Return 1 for succes, 0 if the module is not found, and -1 with
1865 an exception set if the initialization failed.
1866 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001867
1868int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001869PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001870{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001871 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001872 PyObject *co;
1873 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001874 int ispackage;
1875 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001876
1877 if (p == NULL)
1878 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001879 if (p->code == NULL) {
1880 PyErr_Format(PyExc_ImportError,
1881 "Excluded frozen object named %.200s",
1882 name);
1883 return -1;
1884 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001885 size = p->size;
1886 ispackage = (size < 0);
1887 if (ispackage)
1888 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001889 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001890 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001891 name, ispackage ? " package" : "");
1892 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001893 if (co == NULL)
1894 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001895 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001896 PyErr_Format(PyExc_TypeError,
1897 "frozen object %.200s is not a code object",
1898 name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001899 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001900 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001901 if (ispackage) {
1902 /* Set __path__ to the package name */
1903 PyObject *d, *s;
1904 int err;
1905 m = PyImport_AddModule(name);
1906 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001907 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001908 d = PyModule_GetDict(m);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001909 s = PyUnicode_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001910 if (s == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001911 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001912 err = PyDict_SetItemString(d, "__path__", s);
1913 Py_DECREF(s);
1914 if (err != 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001915 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001916 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001917 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001918 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001919 goto err_return;
1920 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001921 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001922 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001923err_return:
1924 Py_DECREF(co);
1925 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001926}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001927
1928
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001929/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001930 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001931
Guido van Rossum79f25d91997-04-29 20:08:16 +00001932PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001933PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001934{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001935 PyObject *pname;
1936 PyObject *result;
1937
Martin v. Löwis5b222132007-06-10 09:51:05 +00001938 pname = PyUnicode_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001939 if (pname == NULL)
1940 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001941 result = PyImport_Import(pname);
1942 Py_DECREF(pname);
1943 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001944}
1945
Christian Heimes072c0f12008-01-03 23:01:04 +00001946/* Import a module without blocking
1947 *
1948 * At first it tries to fetch the module from sys.modules. If the module was
1949 * never loaded before it loads it with PyImport_ImportModule() unless another
1950 * thread holds the import lock. In the latter case the function raises an
1951 * ImportError instead of blocking.
1952 *
1953 * Returns the module object with incremented ref count.
1954 */
1955PyObject *
1956PyImport_ImportModuleNoBlock(const char *name)
1957{
1958 PyObject *result;
1959 PyObject *modules;
1960 long me;
1961
1962 /* Try to get the module from sys.modules[name] */
1963 modules = PyImport_GetModuleDict();
1964 if (modules == NULL)
1965 return NULL;
1966
1967 result = PyDict_GetItemString(modules, name);
1968 if (result != NULL) {
1969 Py_INCREF(result);
1970 return result;
1971 }
1972 else {
1973 PyErr_Clear();
1974 }
1975
1976 /* check the import lock
1977 * me might be -1 but I ignore the error here, the lock function
1978 * takes care of the problem */
1979 me = PyThread_get_thread_ident();
1980 if (import_lock_thread == -1 || import_lock_thread == me) {
1981 /* no thread or me is holding the lock */
1982 return PyImport_ImportModule(name);
1983 }
1984 else {
1985 PyErr_Format(PyExc_ImportError,
1986 "Failed to import %.200s because the import lock"
1987 "is held by another thread.",
1988 name);
1989 return NULL;
1990 }
1991}
1992
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001993/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001994static PyObject *get_parent(PyObject *globals, char *buf,
1995 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001996static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001998static int mark_miss(char *name);
1999static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002000 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002001static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002002
2003/* The Magnum Opus of dotted-name import :-) */
2004
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002005static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002006import_module_level(char *name, PyObject *globals, PyObject *locals,
2007 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002008{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002009 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002010 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002011 PyObject *parent, *head, *next, *tail;
2012
Christian Heimes454f37b2008-01-10 00:10:02 +00002013 if (strchr(name, '/') != NULL
2014#ifdef MS_WINDOWS
2015 || strchr(name, '\\') != NULL
2016#endif
2017 ) {
2018 PyErr_SetString(PyExc_ImportError,
2019 "Import by filename is not supported.");
2020 return NULL;
2021 }
2022
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002023 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002024 if (parent == NULL)
2025 return NULL;
2026
2027 head = load_next(parent, Py_None, &name, buf, &buflen);
2028 if (head == NULL)
2029 return NULL;
2030
2031 tail = head;
2032 Py_INCREF(tail);
2033 while (name) {
2034 next = load_next(tail, tail, &name, buf, &buflen);
2035 Py_DECREF(tail);
2036 if (next == NULL) {
2037 Py_DECREF(head);
2038 return NULL;
2039 }
2040 tail = next;
2041 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002042 if (tail == Py_None) {
2043 /* If tail is Py_None, both get_parent and load_next found
2044 an empty module name: someone called __import__("") or
2045 doctored faulty bytecode */
2046 Py_DECREF(tail);
2047 Py_DECREF(head);
2048 PyErr_SetString(PyExc_ValueError,
2049 "Empty module name");
2050 return NULL;
2051 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002052
2053 if (fromlist != NULL) {
2054 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2055 fromlist = NULL;
2056 }
2057
2058 if (fromlist == NULL) {
2059 Py_DECREF(tail);
2060 return head;
2061 }
2062
2063 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002064 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002065 Py_DECREF(tail);
2066 return NULL;
2067 }
2068
2069 return tail;
2070}
2071
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002072PyObject *
2073PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2074 PyObject *fromlist, int level)
2075{
2076 PyObject *result;
2077 lock_import();
2078 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002079 if (unlock_import() < 0) {
2080 Py_XDECREF(result);
2081 PyErr_SetString(PyExc_RuntimeError,
2082 "not holding the import lock");
2083 return NULL;
2084 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002085 return result;
2086}
2087
Fred Drake87590902004-05-28 20:21:36 +00002088/* Return the package that an import is being performed in. If globals comes
2089 from the module foo.bar.bat (not itself a package), this returns the
2090 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002091 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002092
2093 The *name* of the returned package is returned in buf, with the length of
2094 the name in *p_buflen.
2095
2096 If globals doesn't come from a package or a module in a package, or a
2097 corresponding entry is not found in sys.modules, Py_None is returned.
2098*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002099static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002100get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002101{
2102 static PyObject *namestr = NULL;
2103 static PyObject *pathstr = NULL;
Nick Coghlande10c852007-12-04 12:22:52 +00002104 static PyObject *pkgstr = NULL;
2105 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002106
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002107 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002108 return Py_None;
2109
2110 if (namestr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002111 namestr = PyUnicode_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002112 if (namestr == NULL)
2113 return NULL;
2114 }
2115 if (pathstr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002116 pathstr = PyUnicode_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002117 if (pathstr == NULL)
2118 return NULL;
2119 }
Nick Coghlande10c852007-12-04 12:22:52 +00002120 if (pkgstr == NULL) {
2121 pkgstr = PyUnicode_InternFromString("__package__");
2122 if (pkgstr == NULL)
2123 return NULL;
2124 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002125
2126 *buf = '\0';
2127 *p_buflen = 0;
Nick Coghlande10c852007-12-04 12:22:52 +00002128 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002129
Nick Coghlande10c852007-12-04 12:22:52 +00002130 if ((pkgname != NULL) && (pkgname != Py_None)) {
2131 /* __package__ is set, so use it */
2132 Py_ssize_t len;
2133 if (!PyUnicode_Check(pkgname)) {
2134 PyErr_SetString(PyExc_ValueError,
2135 "__package__ set to non-string");
2136 return NULL;
2137 }
2138 len = PyUnicode_GET_SIZE(pkgname);
2139 if (len == 0) {
2140 if (level > 0) {
2141 PyErr_SetString(PyExc_ValueError,
2142 "Attempted relative import in non-package");
2143 return NULL;
2144 }
2145 return Py_None;
2146 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002147 if (len > MAXPATHLEN) {
2148 PyErr_SetString(PyExc_ValueError,
Nick Coghlande10c852007-12-04 12:22:52 +00002149 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002150 return NULL;
2151 }
Nick Coghlande10c852007-12-04 12:22:52 +00002152 strcpy(buf, PyUnicode_AsString(pkgname));
2153 } else {
2154 /* __package__ not set, so figure it out and set it */
2155 modname = PyDict_GetItem(globals, namestr);
2156 if (modname == NULL || !PyUnicode_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002157 return Py_None;
Nick Coghlande10c852007-12-04 12:22:52 +00002158
2159 modpath = PyDict_GetItem(globals, pathstr);
2160 if (modpath != NULL) {
2161 /* __path__ is set, so modname is already the package name */
2162 Py_ssize_t len = PyUnicode_GET_SIZE(modname);
2163 int error;
2164 if (len > MAXPATHLEN) {
2165 PyErr_SetString(PyExc_ValueError,
2166 "Module name too long");
2167 return NULL;
2168 }
2169 strcpy(buf, PyUnicode_AsString(modname));
2170 error = PyDict_SetItem(globals, pkgstr, modname);
2171 if (error) {
2172 PyErr_SetString(PyExc_ValueError,
2173 "Could not set __package__");
2174 return NULL;
2175 }
2176 } else {
2177 /* Normal module, so work out the package name if any */
2178 char *start = PyUnicode_AsString(modname);
2179 char *lastdot = strrchr(start, '.');
2180 size_t len;
2181 int error;
2182 if (lastdot == NULL && level > 0) {
2183 PyErr_SetString(PyExc_ValueError,
2184 "Attempted relative import in non-package");
2185 return NULL;
2186 }
2187 if (lastdot == NULL) {
2188 error = PyDict_SetItem(globals, pkgstr, Py_None);
2189 if (error) {
2190 PyErr_SetString(PyExc_ValueError,
2191 "Could not set __package__");
2192 return NULL;
2193 }
2194 return Py_None;
2195 }
2196 len = lastdot - start;
2197 if (len >= MAXPATHLEN) {
2198 PyErr_SetString(PyExc_ValueError,
2199 "Module name too long");
2200 return NULL;
2201 }
2202 strncpy(buf, start, len);
2203 buf[len] = '\0';
2204 pkgname = PyUnicode_FromString(buf);
2205 if (pkgname == NULL) {
2206 return NULL;
2207 }
2208 error = PyDict_SetItem(globals, pkgstr, pkgname);
2209 Py_DECREF(pkgname);
2210 if (error) {
2211 PyErr_SetString(PyExc_ValueError,
2212 "Could not set __package__");
2213 return NULL;
2214 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002215 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002216 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002217 while (--level > 0) {
2218 char *dot = strrchr(buf, '.');
2219 if (dot == NULL) {
2220 PyErr_SetString(PyExc_ValueError,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002221 "Attempted relative import beyond "
2222 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002223 return NULL;
2224 }
2225 *dot = '\0';
2226 }
2227 *p_buflen = strlen(buf);
2228
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002229 modules = PyImport_GetModuleDict();
2230 parent = PyDict_GetItemString(modules, buf);
2231 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002232 PyErr_Format(PyExc_SystemError,
2233 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002234 return parent;
2235 /* We expect, but can't guarantee, if parent != None, that:
2236 - parent.__name__ == buf
2237 - parent.__dict__ is globals
2238 If this is violated... Who cares? */
2239}
2240
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002241/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002242static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002243load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002244 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002245{
2246 char *name = *p_name;
2247 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002248 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002249 char *p;
2250 PyObject *result;
2251
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002252 if (strlen(name) == 0) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002253 /* completely empty module name should only happen in
2254 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002255 Py_INCREF(mod);
2256 *p_name = NULL;
2257 return mod;
2258 }
2259
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002260 if (dot == NULL) {
2261 *p_name = NULL;
2262 len = strlen(name);
2263 }
2264 else {
2265 *p_name = dot+1;
2266 len = dot-name;
2267 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002268 if (len == 0) {
2269 PyErr_SetString(PyExc_ValueError,
2270 "Empty module name");
2271 return NULL;
2272 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002273
2274 p = buf + *p_buflen;
2275 if (p != buf)
2276 *p++ = '.';
2277 if (p+len-buf >= MAXPATHLEN) {
2278 PyErr_SetString(PyExc_ValueError,
2279 "Module name too long");
2280 return NULL;
2281 }
2282 strncpy(p, name, len);
2283 p[len] = '\0';
2284 *p_buflen = p+len-buf;
2285
2286 result = import_submodule(mod, p, buf);
2287 if (result == Py_None && altmod != mod) {
2288 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002289 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002290 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002291 if (result != NULL && result != Py_None) {
2292 if (mark_miss(buf) != 0) {
2293 Py_DECREF(result);
2294 return NULL;
2295 }
2296 strncpy(buf, name, len);
2297 buf[len] = '\0';
2298 *p_buflen = len;
2299 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002300 }
2301 if (result == NULL)
2302 return NULL;
2303
2304 if (result == Py_None) {
2305 Py_DECREF(result);
2306 PyErr_Format(PyExc_ImportError,
2307 "No module named %.200s", name);
2308 return NULL;
2309 }
2310
2311 return result;
2312}
2313
2314static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002315mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002316{
2317 PyObject *modules = PyImport_GetModuleDict();
2318 return PyDict_SetItemString(modules, name, Py_None);
2319}
2320
2321static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002322ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002323 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002324{
2325 int i;
2326
2327 if (!PyObject_HasAttrString(mod, "__path__"))
2328 return 1;
2329
2330 for (i = 0; ; i++) {
2331 PyObject *item = PySequence_GetItem(fromlist, i);
2332 int hasit;
2333 if (item == NULL) {
2334 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2335 PyErr_Clear();
2336 return 1;
2337 }
2338 return 0;
2339 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002340 if (!PyUnicode_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002341 PyErr_SetString(PyExc_TypeError,
Neal Norwitz80e7f272007-08-26 06:45:23 +00002342 "Item in ``from list'' not a string");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002343 Py_DECREF(item);
2344 return 0;
2345 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002346 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002347 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002348 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002349 /* See if the package defines __all__ */
2350 if (recursive)
2351 continue; /* Avoid endless recursion */
2352 all = PyObject_GetAttrString(mod, "__all__");
2353 if (all == NULL)
2354 PyErr_Clear();
2355 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002356 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002357 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002358 if (!ret)
2359 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002360 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002361 continue;
2362 }
2363 hasit = PyObject_HasAttr(mod, item);
2364 if (!hasit) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002365 PyObject *item8;
2366 char *subname;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002367 PyObject *submod;
2368 char *p;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002369 if (!Py_FileSystemDefaultEncoding) {
2370 item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item),
2371 PyUnicode_GetSize(item),
Martin v. Löwis427dbff2007-06-12 05:53:00 +00002372 NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002373 } else {
Guido van Rossum98297ee2007-11-06 21:34:58 +00002374 item8 = PyUnicode_AsEncodedString(item,
2375 Py_FileSystemDefaultEncoding, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002376 }
2377 if (!item8) {
2378 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2379 return 0;
2380 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002381 subname = PyString_AS_STRING(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002382 if (buflen + strlen(subname) >= MAXPATHLEN) {
2383 PyErr_SetString(PyExc_ValueError,
2384 "Module name too long");
2385 Py_DECREF(item);
2386 return 0;
2387 }
2388 p = buf + buflen;
2389 *p++ = '.';
2390 strcpy(p, subname);
2391 submod = import_submodule(mod, subname, buf);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002392 Py_DECREF(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002393 Py_XDECREF(submod);
2394 if (submod == NULL) {
2395 Py_DECREF(item);
2396 return 0;
2397 }
2398 }
2399 Py_DECREF(item);
2400 }
2401
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002402 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002403}
2404
Neil Schemenauer00b09662003-06-16 21:03:07 +00002405static int
2406add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2407 PyObject *modules)
2408{
2409 if (mod == Py_None)
2410 return 1;
2411 /* Irrespective of the success of this load, make a
2412 reference to it in the parent package module. A copy gets
2413 saved in the modules dictionary under the full name, so get a
2414 reference from there, if need be. (The exception is when the
2415 load failed with a SyntaxError -- then there's no trace in
2416 sys.modules. In that case, of course, do nothing extra.) */
2417 if (submod == NULL) {
2418 submod = PyDict_GetItemString(modules, fullname);
2419 if (submod == NULL)
2420 return 1;
2421 }
2422 if (PyModule_Check(mod)) {
2423 /* We can't use setattr here since it can give a
2424 * spurious warning if the submodule name shadows a
2425 * builtin name */
2426 PyObject *dict = PyModule_GetDict(mod);
2427 if (!dict)
2428 return 0;
2429 if (PyDict_SetItemString(dict, subname, submod) < 0)
2430 return 0;
2431 }
2432 else {
2433 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2434 return 0;
2435 }
2436 return 1;
2437}
2438
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002439static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002440import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002441{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002442 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002443 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002444
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002445 /* Require:
2446 if mod == None: subname == fullname
2447 else: mod.__name__ + "." + subname == fullname
2448 */
2449
Tim Peters50d8d372001-02-28 05:34:27 +00002450 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002451 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002452 }
2453 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002454 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002455 char buf[MAXPATHLEN+1];
2456 struct filedescr *fdp;
2457 FILE *fp = NULL;
2458
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002459 if (mod == Py_None)
2460 path = NULL;
2461 else {
2462 path = PyObject_GetAttrString(mod, "__path__");
2463 if (path == NULL) {
2464 PyErr_Clear();
2465 Py_INCREF(Py_None);
2466 return Py_None;
2467 }
2468 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002469
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002470 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002471 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2472 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002473 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002474 if (fdp == NULL) {
2475 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2476 return NULL;
2477 PyErr_Clear();
2478 Py_INCREF(Py_None);
2479 return Py_None;
2480 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002481 m = load_module(fullname, fp, buf, fdp->type, loader);
2482 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002483 if (fp)
2484 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002485 if (!add_submodule(mod, m, fullname, subname, modules)) {
2486 Py_XDECREF(m);
2487 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002488 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002489 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002490
2491 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002492}
2493
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002494
2495/* Re-import a module of any kind and return its module object, WITH
2496 INCREMENTED REFERENCE COUNT */
2497
Guido van Rossum79f25d91997-04-29 20:08:16 +00002498PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002499PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002500{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002501 PyInterpreterState *interp = PyThreadState_Get()->interp;
2502 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002503 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossumd8faa362007-04-27 19:54:29 +00002504 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002505 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002506 char buf[MAXPATHLEN+1];
2507 struct filedescr *fdp;
2508 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002509 PyObject *newm;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002510
2511 if (modules_reloading == NULL) {
2512 Py_FatalError("PyImport_ReloadModule: "
Guido van Rossume7ba4952007-06-06 23:52:48 +00002513 "no modules_reloading dictionary!");
Guido van Rossumd8faa362007-04-27 19:54:29 +00002514 return NULL;
2515 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002516
Guido van Rossum79f25d91997-04-29 20:08:16 +00002517 if (m == NULL || !PyModule_Check(m)) {
2518 PyErr_SetString(PyExc_TypeError,
2519 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002520 return NULL;
2521 }
Neal Norwitz5616c6d2007-08-26 05:32:41 +00002522 name = (char*)PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002523 if (name == NULL)
2524 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002525 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002526 PyErr_Format(PyExc_ImportError,
2527 "reload(): module %.200s not in sys.modules",
2528 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002529 return NULL;
2530 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002531 existing_m = PyDict_GetItemString(modules_reloading, name);
2532 if (existing_m != NULL) {
2533 /* Due to a recursive reload, this module is already
2534 being reloaded. */
2535 Py_INCREF(existing_m);
2536 return existing_m;
2537 }
2538 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2539 return NULL;
2540
Guido van Rossum222ef561997-09-06 19:41:09 +00002541 subname = strrchr(name, '.');
2542 if (subname == NULL)
2543 subname = name;
2544 else {
2545 PyObject *parentname, *parent;
Christian Heimesc4cb3b82007-11-04 12:10:01 +00002546 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002547 if (parentname == NULL) {
2548 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002549 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002550 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002551 parent = PyDict_GetItem(modules, parentname);
2552 if (parent == NULL) {
2553 PyErr_Format(PyExc_ImportError,
2554 "reload(): parent %.200s not in sys.modules",
Christian Heimesc4cb3b82007-11-04 12:10:01 +00002555 PyUnicode_AsString(parentname));
Georg Brandl0c55f292005-09-14 06:56:20 +00002556 Py_DECREF(parentname);
Guido van Rossume7ba4952007-06-06 23:52:48 +00002557 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002558 return NULL;
2559 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002560 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002561 subname++;
2562 path = PyObject_GetAttrString(parent, "__path__");
2563 if (path == NULL)
2564 PyErr_Clear();
2565 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002566 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002567 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002568 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002569
2570 if (fdp == NULL) {
2571 Py_XDECREF(loader);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002572 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002573 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002574 }
2575
2576 newm = load_module(name, fp, buf, fdp->type, loader);
2577 Py_XDECREF(loader);
2578
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002579 if (fp)
2580 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002581 if (newm == NULL) {
2582 /* load_module probably removed name from modules because of
2583 * the error. Put back the original module object. We're
2584 * going to return NULL in this case regardless of whether
2585 * replacing name succeeds, so the return value is ignored.
2586 */
2587 PyDict_SetItemString(modules, name, m);
2588 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002589 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002590 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002591}
2592
2593
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002594/* Higher-level import emulator which emulates the "import" statement
2595 more accurately -- it invokes the __import__() function from the
2596 builtins of the current globals. This means that the import is
2597 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002598 environment, e.g. by "rexec".
2599 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002600 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002601 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002602
2603PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002604PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002605{
2606 static PyObject *silly_list = NULL;
2607 static PyObject *builtins_str = NULL;
2608 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002609 PyObject *globals = NULL;
2610 PyObject *import = NULL;
2611 PyObject *builtins = NULL;
2612 PyObject *r = NULL;
2613
2614 /* Initialize constant string objects */
2615 if (silly_list == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002616 import_str = PyUnicode_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002617 if (import_str == NULL)
2618 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002619 builtins_str = PyUnicode_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002620 if (builtins_str == NULL)
2621 return NULL;
2622 silly_list = Py_BuildValue("[s]", "__doc__");
2623 if (silly_list == NULL)
2624 return NULL;
2625 }
2626
2627 /* Get the builtins from current globals */
2628 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002629 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002630 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002631 builtins = PyObject_GetItem(globals, builtins_str);
2632 if (builtins == NULL)
2633 goto err;
2634 }
2635 else {
2636 /* No globals -- use standard builtins, and fake globals */
2637 PyErr_Clear();
2638
Georg Brandl1a3284e2007-12-02 09:40:06 +00002639 builtins = PyImport_ImportModuleLevel("builtins",
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002640 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002641 if (builtins == NULL)
2642 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002643 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2644 if (globals == NULL)
2645 goto err;
2646 }
2647
2648 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002650 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651 if (import == NULL)
2652 PyErr_SetObject(PyExc_KeyError, import_str);
2653 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002654 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002655 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002656 if (import == NULL)
2657 goto err;
2658
Christian Heimes072c0f12008-01-03 23:01:04 +00002659 /* Call the __import__ function with the proper argument list
2660 * Always use absolute import here. */
2661 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2662 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002663
2664 err:
2665 Py_XDECREF(globals);
2666 Py_XDECREF(builtins);
2667 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002668
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002669 return r;
2670}
2671
2672
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002673/* Module 'imp' provides Python access to the primitives used for
2674 importing modules.
2675*/
2676
Guido van Rossum79f25d91997-04-29 20:08:16 +00002677static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002678imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002679{
2680 char buf[4];
2681
Guido van Rossum96774c12000-05-01 20:19:08 +00002682 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2683 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2684 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2685 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002686
Guido van Rossumad8d3002007-08-03 18:40:49 +00002687 return PyBytes_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002688}
2689
Guido van Rossum79f25d91997-04-29 20:08:16 +00002690static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002691imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002692{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002693 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002694 struct filedescr *fdp;
2695
Guido van Rossum79f25d91997-04-29 20:08:16 +00002696 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002697 if (list == NULL)
2698 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002699 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2700 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002701 fdp->suffix, fdp->mode, fdp->type);
2702 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002703 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002704 return NULL;
2705 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002706 if (PyList_Append(list, item) < 0) {
2707 Py_DECREF(list);
2708 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002709 return NULL;
2710 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002711 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002712 }
2713 return list;
2714}
2715
Guido van Rossum79f25d91997-04-29 20:08:16 +00002716static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002717call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002718{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002719 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002720 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002721 struct filedescr *fdp;
2722 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002723 FILE *fp = NULL;
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002724 int fd = -1;
Brett Cannon3bb42d92007-10-20 03:43:15 +00002725 char *found_encoding = NULL;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002726 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002727
2728 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002729 if (path == Py_None)
2730 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002731 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002732 if (fdp == NULL)
2733 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002734 if (fp != NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002735 fd = fileno(fp);
2736 if (fd != -1)
2737 fd = dup(fd);
2738 fclose(fp);
2739 fp = NULL;
2740 }
2741 if (fd != -1) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002742 if (strchr(fdp->mode, 'b') == NULL) {
Brett Cannon3bb42d92007-10-20 03:43:15 +00002743 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
2744 memory. */
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002745 found_encoding = PyTokenizer_FindEncoding(fd);
2746 lseek(fd, 0, 0); /* Reset position */
Brett Cannon3bb42d92007-10-20 03:43:15 +00002747 encoding = (found_encoding != NULL) ? found_encoding :
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002748 (char*)PyUnicode_GetDefaultEncoding();
2749 }
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002750 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
Guido van Rossume7fc50f2007-12-03 22:54:21 +00002751 (char*)encoding, NULL, NULL, 1);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002752 if (fob == NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002753 close(fd);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002754 PyMem_FREE(found_encoding);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002755 return NULL;
2756 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002757 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002758 else {
2759 fob = Py_None;
2760 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002761 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002762 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002763 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002764 Py_DECREF(fob);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002765 PyMem_FREE(found_encoding);
2766
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002767 return ret;
2768}
2769
Guido van Rossum79f25d91997-04-29 20:08:16 +00002770static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002771imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002772{
2773 char *name;
2774 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002775 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002776 return NULL;
2777 return call_find_module(name, path);
2778}
2779
2780static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002781imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002782{
2783 char *name;
2784 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002785 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002786 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002787 return NULL;
2788 ret = init_builtin(name);
2789 if (ret < 0)
2790 return NULL;
2791 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002792 Py_INCREF(Py_None);
2793 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002794 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002795 m = PyImport_AddModule(name);
2796 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002797 return m;
2798}
2799
Guido van Rossum79f25d91997-04-29 20:08:16 +00002800static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002801imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002802{
2803 char *name;
2804 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002805 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002806 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002807 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002808 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002809 if (ret < 0)
2810 return NULL;
2811 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002812 Py_INCREF(Py_None);
2813 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002814 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002815 m = PyImport_AddModule(name);
2816 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002817 return m;
2818}
2819
Guido van Rossum79f25d91997-04-29 20:08:16 +00002820static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002821imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002822{
2823 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002824
Guido van Rossum43713e52000-02-29 13:59:29 +00002825 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002826 return NULL;
2827 return get_frozen_object(name);
2828}
2829
Guido van Rossum79f25d91997-04-29 20:08:16 +00002830static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002831imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002832{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002833 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002834 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002835 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00002836 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002837}
2838
Guido van Rossum79f25d91997-04-29 20:08:16 +00002839static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002840imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002841{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002842 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002843 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002844 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002845 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002846 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002847 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002848}
2849
2850static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002851get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002852{
2853 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002854 if (mode[0] == 'U')
2855 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002856 if (fob == NULL) {
2857 fp = fopen(pathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002858 }
2859 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002860 int fd = PyObject_AsFileDescriptor(fob);
2861 if (fd == -1)
2862 return NULL;
2863 /* XXX This will leak a FILE struct. Fix this!!!!
2864 (But it doesn't leak a file descrioptor!) */
2865 fp = fdopen(fd, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002866 }
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002867 if (fp == NULL)
2868 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002869 return fp;
2870}
2871
Guido van Rossum79f25d91997-04-29 20:08:16 +00002872static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002873imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002874{
2875 char *name;
2876 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002877 PyObject *fob = NULL;
2878 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002879 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002880 if (!PyArg_ParseTuple(args, "ss|O:load_compiled",
2881 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002882 return NULL;
2883 fp = get_file(pathname, fob, "rb");
2884 if (fp == NULL)
2885 return NULL;
2886 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002887 if (fob == NULL)
2888 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002889 return m;
2890}
2891
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002892#ifdef HAVE_DYNAMIC_LOADING
2893
Guido van Rossum79f25d91997-04-29 20:08:16 +00002894static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002895imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002896{
2897 char *name;
2898 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002899 PyObject *fob = NULL;
2900 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002901 FILE *fp = NULL;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002902 if (!PyArg_ParseTuple(args, "ss|O:load_dynamic",
2903 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002904 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002905 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002906 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002907 if (fp == NULL)
2908 return NULL;
2909 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002910 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002911 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002912}
2913
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002914#endif /* HAVE_DYNAMIC_LOADING */
2915
Guido van Rossum79f25d91997-04-29 20:08:16 +00002916static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002917imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002918{
2919 char *name;
2920 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002921 PyObject *fob = NULL;
2922 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002923 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002924 if (!PyArg_ParseTuple(args, "ss|O:load_source",
2925 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002926 return NULL;
2927 fp = get_file(pathname, fob, "r");
2928 if (fp == NULL)
2929 return NULL;
2930 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002931 if (fob == NULL)
2932 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002933 return m;
2934}
2935
Guido van Rossum79f25d91997-04-29 20:08:16 +00002936static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002937imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002938{
2939 char *name;
2940 PyObject *fob;
2941 char *pathname;
2942 char *suffix; /* Unused */
2943 char *mode;
2944 int type;
2945 FILE *fp;
2946
Guido van Rossum43713e52000-02-29 13:59:29 +00002947 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002948 &name, &fob, &pathname,
2949 &suffix, &mode, &type))
2950 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002951 if (*mode) {
2952 /* Mode must start with 'r' or 'U' and must not contain '+'.
2953 Implicit in this test is the assumption that the mode
2954 may contain other modifiers like 'b' or 't'. */
2955
2956 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002957 PyErr_Format(PyExc_ValueError,
2958 "invalid file open mode %.200s", mode);
2959 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002960 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002961 }
2962 if (fob == Py_None)
2963 fp = NULL;
2964 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002965 fp = get_file(NULL, fob, mode);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002966 if (fp == NULL)
2967 return NULL;
2968 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002969 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002970}
2971
2972static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002973imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002974{
2975 char *name;
2976 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002977 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002978 return NULL;
2979 return load_package(name, pathname);
2980}
2981
2982static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002983imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002984{
2985 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002986 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002987 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002988 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002989}
2990
Christian Heimes13a7a212008-01-07 17:13:09 +00002991static PyObject *
2992imp_reload(PyObject *self, PyObject *v)
2993{
2994 return PyImport_ReloadModule(v);
2995}
2996
2997PyDoc_STRVAR(doc_reload,
2998"reload(module) -> module\n\
2999\n\
3000Reload the module. The module must have been successfully imported before.");
3001
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003002/* Doc strings */
3003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003004PyDoc_STRVAR(doc_imp,
3005"This module provides the components needed to build your own\n\
3006__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003007
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003008PyDoc_STRVAR(doc_find_module,
3009"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003010Search for a module. If path is omitted or None, search for a\n\
3011built-in, frozen or special module and continue search in sys.path.\n\
3012The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003013package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003015PyDoc_STRVAR(doc_load_module,
3016"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003017Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003018The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003019
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003020PyDoc_STRVAR(doc_get_magic,
3021"get_magic() -> string\n\
3022Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003024PyDoc_STRVAR(doc_get_suffixes,
3025"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003026Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003027that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003028
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003029PyDoc_STRVAR(doc_new_module,
3030"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003031Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003032The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003033
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003034PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003035"lock_held() -> boolean\n\
3036Return True if the import lock is currently held, else False.\n\
3037On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003038
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003039PyDoc_STRVAR(doc_acquire_lock,
3040"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003041Acquires the interpreter's import lock for the current thread.\n\
3042This lock should be used by import hooks to ensure thread-safety\n\
3043when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003044On platforms without threads, this function does nothing.");
3045
3046PyDoc_STRVAR(doc_release_lock,
3047"release_lock() -> None\n\
3048Release the interpreter's import lock.\n\
3049On platforms without threads, this function does nothing.");
3050
Guido van Rossum79f25d91997-04-29 20:08:16 +00003051static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003052 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3053 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3054 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3055 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3056 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3057 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3058 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3059 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Christian Heimes13a7a212008-01-07 17:13:09 +00003060 {"reload", imp_reload, METH_O, doc_reload},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003061 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003062 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3063 {"init_builtin", imp_init_builtin, METH_VARARGS},
3064 {"init_frozen", imp_init_frozen, METH_VARARGS},
3065 {"is_builtin", imp_is_builtin, METH_VARARGS},
3066 {"is_frozen", imp_is_frozen, METH_VARARGS},
3067 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003068#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003069 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003070#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003071 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003072 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003073 {NULL, NULL} /* sentinel */
3074};
3075
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003076static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003077setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003078{
3079 PyObject *v;
3080 int err;
3081
Christian Heimes217cfd12007-12-02 14:31:20 +00003082 v = PyLong_FromLong((long)value);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003083 err = PyDict_SetItemString(d, name, v);
3084 Py_XDECREF(v);
3085 return err;
3086}
3087
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003088typedef struct {
3089 PyObject_HEAD
3090} NullImporter;
3091
3092static int
3093NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3094{
3095 char *path;
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003096 Py_ssize_t pathlen;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003097
3098 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3099 return -1;
3100
3101 if (!PyArg_ParseTuple(args, "s:NullImporter",
3102 &path))
3103 return -1;
3104
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003105 pathlen = strlen(path);
3106 if (pathlen == 0) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003107 PyErr_SetString(PyExc_ImportError, "empty pathname");
3108 return -1;
3109 } else {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003110 struct stat statbuf;
3111 int rv;
3112
3113 rv = stat(path, &statbuf);
Guido van Rossumc1bdbc32007-11-07 17:46:34 +00003114#ifdef MS_WINDOWS
3115 /* MS Windows stat() chokes on paths like C:\path\. Try to
3116 * recover *one* time by stripping off a trailing slash or
3117 * backslash. http://bugs.python.org/issue1293
3118 */
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003119 if (rv != 0 && pathlen <= MAXPATHLEN &&
3120 (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
3121 char mangled[MAXPATHLEN+1];
3122
3123 strcpy(mangled, path);
3124 mangled[pathlen-1] = '\0';
3125 rv = stat(mangled, &statbuf);
3126 }
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003127#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003128 if (rv == 0) {
3129 /* it exists */
3130 if (S_ISDIR(statbuf.st_mode)) {
3131 /* it's a directory */
3132 PyErr_SetString(PyExc_ImportError,
3133 "existing directory");
3134 return -1;
3135 }
3136 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003137 }
3138 return 0;
3139}
3140
3141static PyObject *
3142NullImporter_find_module(NullImporter *self, PyObject *args)
3143{
3144 Py_RETURN_NONE;
3145}
3146
3147static PyMethodDef NullImporter_methods[] = {
3148 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3149 "Always return None"
3150 },
3151 {NULL} /* Sentinel */
3152};
3153
3154
Christian Heimes9cd17752007-11-18 19:35:23 +00003155PyTypeObject PyNullImporter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003156 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003157 "imp.NullImporter", /*tp_name*/
3158 sizeof(NullImporter), /*tp_basicsize*/
3159 0, /*tp_itemsize*/
3160 0, /*tp_dealloc*/
3161 0, /*tp_print*/
3162 0, /*tp_getattr*/
3163 0, /*tp_setattr*/
3164 0, /*tp_compare*/
3165 0, /*tp_repr*/
3166 0, /*tp_as_number*/
3167 0, /*tp_as_sequence*/
3168 0, /*tp_as_mapping*/
3169 0, /*tp_hash */
3170 0, /*tp_call*/
3171 0, /*tp_str*/
3172 0, /*tp_getattro*/
3173 0, /*tp_setattro*/
3174 0, /*tp_as_buffer*/
3175 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3176 "Null importer object", /* tp_doc */
3177 0, /* tp_traverse */
3178 0, /* tp_clear */
3179 0, /* tp_richcompare */
3180 0, /* tp_weaklistoffset */
3181 0, /* tp_iter */
3182 0, /* tp_iternext */
3183 NullImporter_methods, /* tp_methods */
3184 0, /* tp_members */
3185 0, /* tp_getset */
3186 0, /* tp_base */
3187 0, /* tp_dict */
3188 0, /* tp_descr_get */
3189 0, /* tp_descr_set */
3190 0, /* tp_dictoffset */
3191 (initproc)NullImporter_init, /* tp_init */
3192 0, /* tp_alloc */
3193 PyType_GenericNew /* tp_new */
3194};
3195
3196
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003197PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003198initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003199{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003200 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003201
Christian Heimes9cd17752007-11-18 19:35:23 +00003202 if (PyType_Ready(&PyNullImporter_Type) < 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003203 goto failure;
3204
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003205 m = Py_InitModule4("imp", imp_methods, doc_imp,
3206 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003207 if (m == NULL)
3208 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003209 d = PyModule_GetDict(m);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003210 if (d == NULL)
3211 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003212
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003213 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3214 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3215 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3216 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3217 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3218 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3219 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3220 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003221 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003222 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003223
Christian Heimes9cd17752007-11-18 19:35:23 +00003224 Py_INCREF(&PyNullImporter_Type);
3225 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003226 failure:
3227 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003228}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003229
3230
Guido van Rossumb18618d2000-05-03 23:44:39 +00003231/* API for embedding applications that want to add their own entries
3232 to the table of built-in modules. This should normally be called
3233 *before* Py_Initialize(). When the table resize fails, -1 is
3234 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003235
3236 After a similar function by Just van Rossum. */
3237
3238int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003239PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003240{
3241 static struct _inittab *our_copy = NULL;
3242 struct _inittab *p;
3243 int i, n;
3244
3245 /* Count the number of entries in both tables */
3246 for (n = 0; newtab[n].name != NULL; n++)
3247 ;
3248 if (n == 0)
3249 return 0; /* Nothing to do */
3250 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3251 ;
3252
3253 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003254 p = our_copy;
3255 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003256 if (p == NULL)
3257 return -1;
3258
3259 /* Copy the tables into the new memory */
3260 if (our_copy != PyImport_Inittab)
3261 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3262 PyImport_Inittab = our_copy = p;
3263 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3264
3265 return 0;
3266}
3267
3268/* Shorthand to add a single entry given a name and a function */
3269
3270int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003271PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003272{
3273 struct _inittab newtab[2];
3274
3275 memset(newtab, '\0', sizeof newtab);
3276
3277 newtab[0].name = name;
3278 newtab[0].initfunc = initfunc;
3279
3280 return PyImport_ExtendInittab(newtab);
3281}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003282
3283#ifdef __cplusplus
3284}
3285#endif