blob: 2038cfdd4fab5e5c00d35490441ab54f260f870a [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
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006#include "node.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007#include "token.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
10#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000011#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Jack Jansen9c96a921995-02-15 22:57:06 +000014#ifdef macintosh
15#include "macglue.h"
16#endif
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
21
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000022extern time_t PyOS_GetLastModificationTime(char *, FILE *);
23 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000024
Guido van Rossum6c849691994-09-26 15:47:17 +000025/* Magic word to reject .pyc files generated by other Python versions */
Guido van Rossum7faeab31995-07-07 22:50:36 +000026/* Change for each incompatible change */
27/* The value of CR and LF is incorporated so if you ever read or write
28 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000029 Apple MPW compiler swaps their values, botching string constants.
30 XXX That probably isn't important anymore.
31*/
Guido van Rossum7faeab31995-07-07 22:50:36 +000032/* XXX Perhaps the magic number should be frozen and a version field
33 added to the .pyc file header? */
Tim Peters36515e22001-11-18 04:06:29 +000034/* New way to come up with the low 16 bits of the magic number:
35 (YEAR-1995) * 10000 + MONTH * 100 + DAY
36 where MONTH and DAY are 1-based.
37 XXX Whatever the "old way" may have been isn't documented.
38 XXX This scheme breaks in 2002, as (2002-1995)*10000 = 70000 doesn't
39 fit in 16 bits.
40 XXX Later, sometimes 1 gets added to MAGIC in order to record that
41 the Unicode -U option is in use. IMO (Tim's), that's a Bad Idea
42 (quite apart from that the -U option doesn't work so isn't used
43 anyway).
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000044
45 XXX MAL, 2002-02-07: I had to modify the MAGIC due to a fix of the
46 UTF-8 encoder (it previously produced invalid UTF-8 for unpaired
47 high surrogates), so I simply bumped the month value to 20 (invalid
48 month) and set the day to 1. This should be recognizable by any
49 algorithm relying on the above scheme. Perhaps we should simply
50 start counting in increments of 10 from now on ?!
51
Michael W. Hudsondd32a912002-08-15 14:59:02 +000052 MWH, 2002-08-03: Removed SET_LINENO. Couldn't be bothered figuring
53 out the MAGIC schemes, so just incremented it by 10.
54
Guido van Rossumf6894922002-08-31 15:16:14 +000055 GvR, 2002-08-31: Because MWH changed the bytecode again, moved the
56 magic number *back* to 62011. This should get the snake-farm to
57 throw away its old .pyc files, amongst others.
58
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000059 Known values:
60 Python 1.5: 20121
61 Python 1.5.1: 20121
62 Python 1.5.2: 20121
63 Python 2.0: 50823
64 Python 2.0.1: 50823
65 Python 2.1: 60202
66 Python 2.1.1: 60202
67 Python 2.1.2: 60202
68 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000069 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000070 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000071 Python 2.3a0: 62011 (!)
Tim Peters36515e22001-11-18 04:06:29 +000072*/
Guido van Rossumf6894922002-08-31 15:16:14 +000073#define MAGIC (62011 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000074
Guido van Rossum96774c12000-05-01 20:19:08 +000075/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000076 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000077 compiler works which are enabled by command line switches. */
78static long pyc_magic = MAGIC;
79
Guido van Rossum25ce5661997-08-02 03:10:38 +000080/* See _PyImport_FixupExtension() below */
81static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000082
Guido van Rossum771c6c81997-10-31 18:37:24 +000083/* This table is defined in config.c: */
84extern struct _inittab _PyImport_Inittab[];
85
86struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000087
Guido van Rossumed1170e1999-12-20 21:23:41 +000088/* these tables define the module suffixes that Python recognizes */
89struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000090
91#ifdef RISCOS
92static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000093 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +000094 {"/pyc", "rb", PY_COMPILED},
95 {0, 0}
96};
97#else
Guido van Rossumed1170e1999-12-20 21:23:41 +000098static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000099 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000100#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000101 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000102#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000103 {".pyc", "rb", PY_COMPILED},
104 {0, 0}
105};
Guido van Rossum48a680c2001-03-02 06:34:14 +0000106#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000107
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000108/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109
110void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000111_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000112{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000113 const struct filedescr *scan;
114 struct filedescr *filetab;
115 int countD = 0;
116 int countS = 0;
117
118 /* prepare _PyImport_Filetab: copy entries from
119 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
120 */
121 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
122 ++countD;
123 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
124 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000125 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Guido van Rossumed1170e1999-12-20 21:23:41 +0000126 memcpy(filetab, _PyImport_DynLoadFiletab,
127 countD * sizeof(struct filedescr));
128 memcpy(filetab + countD, _PyImport_StandardFiletab,
129 countS * sizeof(struct filedescr));
130 filetab[countD + countS].suffix = NULL;
131
132 _PyImport_Filetab = filetab;
133
Guido van Rossum0824f631997-03-11 18:37:35 +0000134 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000135 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
136 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000137#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000138 if (strcmp(filetab->suffix, ".pyc") == 0)
139 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000140#else
141 if (strcmp(filetab->suffix, "/pyc") == 0)
142 filetab->suffix = "/pyo";
143#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000144 }
145 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000146
147 if (Py_UnicodeFlag) {
148 /* Fix the pyc_magic so that byte compiled code created
149 using the all-Unicode method doesn't interfere with
150 code created in normal operation mode. */
151 pyc_magic = MAGIC + 1;
152 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
Guido van Rossum25ce5661997-08-02 03:10:38 +0000155void
Just van Rossum52e14d62002-12-30 22:08:05 +0000156_PyImportHooks_Init(void)
157{
158 PyObject *v, *path_hooks = NULL, *zimpimport;
159 int err = 0;
160
161 /* adding sys.path_hooks and sys.path_importer_cache, setting up
162 zipimport */
163
164 if (Py_VerboseFlag)
165 PySys_WriteStderr("# installing zipimport hook\n");
166
167 v = PyList_New(0);
168 if (v == NULL)
169 goto error;
170 err = PySys_SetObject("meta_path", v);
171 Py_DECREF(v);
172 if (err)
173 goto error;
174 v = PyDict_New();
175 if (v == NULL)
176 goto error;
177 err = PySys_SetObject("path_importer_cache", v);
178 Py_DECREF(v);
179 if (err)
180 goto error;
181 path_hooks = PyList_New(0);
182 if (path_hooks == NULL)
183 goto error;
184 err = PySys_SetObject("path_hooks", path_hooks);
185 if (err) {
186 error:
187 PyErr_Print();
188 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
189 "path_importer_cache failed");
190 }
191 zimpimport = PyImport_ImportModule("zipimport");
192 if (zimpimport == NULL) {
193 PyErr_Clear(); /* No zip import module -- okay */
194 if (Py_VerboseFlag)
195 PySys_WriteStderr("# can't import zipimport\n");
196 }
197 else {
198 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
199 "zipimporter");
200 Py_DECREF(zimpimport);
201 if (zipimporter == NULL) {
202 PyErr_Clear(); /* No zipimporter object -- okay */
203 if (Py_VerboseFlag)
204 PySys_WriteStderr(
205 "# can't import zipimport.zimimporter\n");
206 }
207 else {
208 /* sys.path_hooks.append(zipimporter) */
209 err = PyList_Append(path_hooks, zipimporter);
210 Py_DECREF(zipimporter);
211 if (err)
212 goto error;
213 if (Py_VerboseFlag)
214 PySys_WriteStderr(
215 "# installed zipimport hook\n");
216 }
217 }
218 Py_DECREF(path_hooks);
219}
220
221void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000222_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000223{
224 Py_XDECREF(extensions);
225 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000226 PyMem_DEL(_PyImport_Filetab);
227 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000228}
229
230
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000231/* Locking primitives to prevent parallel imports of the same module
232 in different threads to return with a partially loaded module.
233 These calls are serialized by the global interpreter lock. */
234
235#ifdef WITH_THREAD
236
Guido van Rossum49b56061998-10-01 20:42:43 +0000237#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000238
Guido van Rossum65d5b571998-12-21 19:32:43 +0000239static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000240static long import_lock_thread = -1;
241static int import_lock_level = 0;
242
243static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000244lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000245{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000246 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000247 if (me == -1)
248 return; /* Too bad */
249 if (import_lock == NULL)
Guido van Rossum65d5b571998-12-21 19:32:43 +0000250 import_lock = PyThread_allocate_lock();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000251 if (import_lock_thread == me) {
252 import_lock_level++;
253 return;
254 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000255 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
256 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000257 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000258 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000259 PyEval_RestoreThread(tstate);
260 }
261 import_lock_thread = me;
262 import_lock_level = 1;
263}
264
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000266unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000267{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000268 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000269 if (me == -1)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000271 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000272 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000273 import_lock_level--;
274 if (import_lock_level == 0) {
275 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000276 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000278 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000279}
280
281#else
282
283#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000284#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000285
286#endif
287
Tim Peters69232342001-08-30 05:16:13 +0000288static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000289imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000290{
Tim Peters69232342001-08-30 05:16:13 +0000291#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000292 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000293#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000294 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000295#endif
296}
297
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000298static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000299imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000300{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000301#ifdef WITH_THREAD
302 lock_import();
303#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000304 Py_INCREF(Py_None);
305 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000306}
307
308static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000309imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000310{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000311#ifdef WITH_THREAD
312 if (unlock_import() < 0) {
313 PyErr_SetString(PyExc_RuntimeError,
314 "not holding the import lock");
315 return NULL;
316 }
317#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000318 Py_INCREF(Py_None);
319 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000320}
321
Guido van Rossum25ce5661997-08-02 03:10:38 +0000322/* Helper for sys */
323
324PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000325PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000326{
327 PyInterpreterState *interp = PyThreadState_Get()->interp;
328 if (interp->modules == NULL)
329 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
330 return interp->modules;
331}
332
Guido van Rossum3f5da241990-12-20 15:06:42 +0000333
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000334/* List of names to clear in sys */
335static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000336 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000337 "exc_type", "exc_value", "exc_traceback",
338 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000339 "path_hooks", "path_importer_cache", "meta_path",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000340 NULL
341};
342
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000343static char* sys_files[] = {
344 "stdin", "__stdin__",
345 "stdout", "__stdout__",
346 "stderr", "__stderr__",
347 NULL
348};
349
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000350
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000351/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000352
Guido van Rossum3f5da241990-12-20 15:06:42 +0000353void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000354PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000355{
Guido van Rossum758eec01998-01-19 21:58:26 +0000356 int pos, ndone;
357 char *name;
358 PyObject *key, *value, *dict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359 PyInterpreterState *interp = PyThreadState_Get()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000360 PyObject *modules = interp->modules;
361
362 if (modules == NULL)
363 return; /* Already done */
364
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000365 /* Delete some special variables first. These are common
366 places where user values hide and people complain when their
367 destructors fail. Since the modules containing them are
368 deleted *last* of all, they would come too late in the normal
369 destruction order. Sigh. */
370
371 value = PyDict_GetItemString(modules, "__builtin__");
372 if (value != NULL && PyModule_Check(value)) {
373 dict = PyModule_GetDict(value);
374 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000375 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000376 PyDict_SetItemString(dict, "_", Py_None);
377 }
378 value = PyDict_GetItemString(modules, "sys");
379 if (value != NULL && PyModule_Check(value)) {
380 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000381 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000382 dict = PyModule_GetDict(value);
383 for (p = sys_deletes; *p != NULL; p++) {
384 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000385 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000386 PyDict_SetItemString(dict, *p, Py_None);
387 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000388 for (p = sys_files; *p != NULL; p+=2) {
389 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000390 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000391 v = PyDict_GetItemString(dict, *(p+1));
392 if (v == NULL)
393 v = Py_None;
394 PyDict_SetItemString(dict, *p, v);
395 }
396 }
397
398 /* First, delete __main__ */
399 value = PyDict_GetItemString(modules, "__main__");
400 if (value != NULL && PyModule_Check(value)) {
401 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000402 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000403 _PyModule_Clear(value);
404 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405 }
406
Guido van Rossum758eec01998-01-19 21:58:26 +0000407 /* The special treatment of __builtin__ here is because even
408 when it's not referenced as a module, its dictionary is
409 referenced by almost every module's __builtins__. Since
410 deleting a module clears its dictionary (even if there are
411 references left to it), we need to delete the __builtin__
412 module last. Likewise, we don't delete sys until the very
413 end because it is implicitly referenced (e.g. by print).
414
415 Also note that we 'delete' modules by replacing their entry
416 in the modules dict with None, rather than really deleting
417 them; this avoids a rehash of the modules dictionary and
418 also marks them as "non existent" so they won't be
419 re-imported. */
420
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000421 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000422 one (skipping __builtin__ and sys) and delete them */
423 do {
424 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000426 while (PyDict_Next(modules, &pos, &key, &value)) {
427 if (value->ob_refcnt != 1)
428 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000429 if (PyString_Check(key) && PyModule_Check(value)) {
430 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000431 if (strcmp(name, "__builtin__") == 0)
432 continue;
433 if (strcmp(name, "sys") == 0)
434 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000435 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000436 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000438 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000439 PyDict_SetItem(modules, key, Py_None);
440 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000441 }
442 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000443 } while (ndone > 0);
444
Guido van Rossum758eec01998-01-19 21:58:26 +0000445 /* Next, delete all modules (still skipping __builtin__ and sys) */
446 pos = 0;
447 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000448 if (PyString_Check(key) && PyModule_Check(value)) {
449 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000450 if (strcmp(name, "__builtin__") == 0)
451 continue;
452 if (strcmp(name, "sys") == 0)
453 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000454 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000455 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000456 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000457 PyDict_SetItem(modules, key, Py_None);
458 }
459 }
460
461 /* Next, delete sys and __builtin__ (in that order) */
462 value = PyDict_GetItemString(modules, "sys");
463 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000464 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000465 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000466 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000467 PyDict_SetItemString(modules, "sys", Py_None);
468 }
469 value = PyDict_GetItemString(modules, "__builtin__");
470 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000471 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000472 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000473 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000474 PyDict_SetItemString(modules, "__builtin__", Py_None);
475 }
476
477 /* Finally, clear and delete the modules directory */
478 PyDict_Clear(modules);
479 interp->modules = NULL;
480 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000481}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000482
483
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000484/* Helper for pythonrun.c -- return magic number */
485
486long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000487PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000488{
Guido van Rossum96774c12000-05-01 20:19:08 +0000489 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000490}
491
492
Guido van Rossum25ce5661997-08-02 03:10:38 +0000493/* Magic for extension modules (built-in as well as dynamically
494 loaded). To prevent initializing an extension module more than
495 once, we keep a static dictionary 'extensions' keyed by module name
496 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000497 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498 dictionary is stored by calling _PyImport_FixupExtension()
499 immediately after the module initialization function succeeds. A
500 copy can be retrieved from there by calling
501 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000502
Guido van Rossum79f25d91997-04-29 20:08:16 +0000503PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000504_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000505{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000506 PyObject *modules, *mod, *dict, *copy;
507 if (extensions == NULL) {
508 extensions = PyDict_New();
509 if (extensions == NULL)
510 return NULL;
511 }
512 modules = PyImport_GetModuleDict();
513 mod = PyDict_GetItemString(modules, name);
514 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000515 PyErr_Format(PyExc_SystemError,
516 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000517 return NULL;
518 }
519 dict = PyModule_GetDict(mod);
520 if (dict == NULL)
521 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000522 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000523 if (copy == NULL)
524 return NULL;
525 PyDict_SetItemString(extensions, filename, copy);
526 Py_DECREF(copy);
527 return copy;
528}
529
530PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000531_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000532{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000533 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534 if (extensions == NULL)
535 return NULL;
536 dict = PyDict_GetItemString(extensions, filename);
537 if (dict == NULL)
538 return NULL;
539 mod = PyImport_AddModule(name);
540 if (mod == NULL)
541 return NULL;
542 mdict = PyModule_GetDict(mod);
543 if (mdict == NULL)
544 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000545 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000548 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549 name, filename);
550 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000551}
552
553
554/* Get the module object corresponding to a module name.
555 First check the modules dictionary if there's one there,
556 if not, create a new one and insert in in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000557 Because the former action is most common, THIS DOES NOT RETURN A
558 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000559
Guido van Rossum79f25d91997-04-29 20:08:16 +0000560PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000561PyImport_AddModule(char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000562{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000564 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000565
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000567 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000568 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000569 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000570 if (m == NULL)
571 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000573 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000574 return NULL;
575 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000576 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000577
578 return m;
579}
580
581
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000582/* Execute a code object in a module and return the module object
583 WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000584
Guido van Rossum79f25d91997-04-29 20:08:16 +0000585PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000586PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000588 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
589}
590
591PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000592PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000593{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000595 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000596
Guido van Rossum79f25d91997-04-29 20:08:16 +0000597 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000598 if (m == NULL)
599 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000600 d = PyModule_GetDict(m);
601 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
602 if (PyDict_SetItemString(d, "__builtins__",
603 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000604 return NULL;
605 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000606 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000607 v = NULL;
608 if (pathname != NULL) {
609 v = PyString_FromString(pathname);
610 if (v == NULL)
611 PyErr_Clear();
612 }
613 if (v == NULL) {
614 v = ((PyCodeObject *)co)->co_filename;
615 Py_INCREF(v);
616 }
617 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000618 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000619 Py_DECREF(v);
620
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000621 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000622 if (v == NULL)
623 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000624 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000625
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000627 PyErr_Format(PyExc_ImportError,
628 "Loaded module %.200s not found in sys.modules",
629 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000630 return NULL;
631 }
632
Guido van Rossum79f25d91997-04-29 20:08:16 +0000633 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000634
635 return m;
636}
637
638
639/* Given a pathname for a Python source file, fill a buffer with the
640 pathname for the corresponding compiled file. Return the pathname
641 for the compiled file, or NULL if there's no space in the buffer.
642 Doesn't set an exception. */
643
644static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000645make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000646{
Tim Petersc1731372001-08-04 08:12:36 +0000647 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000648 if (len+2 > buflen)
649 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000650
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000651#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000652 /* Treat .pyw as if it were .py. The case of ".pyw" must match
653 that used in _PyImport_StandardFiletab. */
654 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
655 --len; /* pretend 'w' isn't there */
656#endif
657 memcpy(buf, pathname, len);
658 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
659 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000660
661 return buf;
662}
663
664
665/* Given a pathname for a Python source file, its time of last
666 modification, and a pathname for a compiled file, check whether the
667 compiled file represents the same version of the source. If so,
668 return a FILE pointer for the compiled file, positioned just after
669 the header; if not, return NULL.
670 Doesn't set an exception. */
671
672static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000673check_compiled_module(char *pathname, long mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000674{
675 FILE *fp;
676 long magic;
677 long pyc_mtime;
678
679 fp = fopen(cpathname, "rb");
680 if (fp == NULL)
681 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000682 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000683 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000684 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000685 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000686 fclose(fp);
687 return NULL;
688 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000689 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000690 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000691 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000692 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693 fclose(fp);
694 return NULL;
695 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000696 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000697 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000698 return fp;
699}
700
701
702/* Read a code object from a file and check it for validity */
703
Guido van Rossum79f25d91997-04-29 20:08:16 +0000704static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000705read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000706{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000707 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000708
Tim Petersd9b9ac82001-01-28 00:27:39 +0000709 co = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710 /* Ugly: rd_object() may return NULL with or without error */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000711 if (co == NULL || !PyCode_Check(co)) {
712 if (!PyErr_Occurred())
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000713 PyErr_Format(PyExc_ImportError,
714 "Non-code object in %.200s", cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000715 Py_XDECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000716 return NULL;
717 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000718 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000719}
720
721
722/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000723 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000724
Guido van Rossum79f25d91997-04-29 20:08:16 +0000725static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000726load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000727{
728 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000729 PyCodeObject *co;
730 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731
Guido van Rossum79f25d91997-04-29 20:08:16 +0000732 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000733 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000734 PyErr_Format(PyExc_ImportError,
735 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000736 return NULL;
737 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000739 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740 if (co == NULL)
741 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000742 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000743 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000744 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000745 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000746 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747
748 return m;
749}
750
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000751/* Parse a source file and return the corresponding code object */
752
Guido van Rossum79f25d91997-04-29 20:08:16 +0000753static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000754parse_source_module(char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000756 PyCodeObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000757 node *n;
758
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000759 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000760 if (n == NULL)
761 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000762 co = PyNode_Compile(n, pathname);
763 PyNode_Free(n);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000764
765 return co;
766}
767
768
Guido van Rossum55a83382000-09-20 20:31:38 +0000769/* Helper to open a bytecode file for writing in exclusive mode */
770
771static FILE *
772open_exclusive(char *filename)
773{
774#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
775 /* Use O_EXCL to avoid a race condition when another process tries to
776 write the same file. When that happens, our open() call fails,
777 which is just fine (since it's only a cache).
778 XXX If the file exists and is writable but the directory is not
779 writable, the file will never be written. Oh well.
780 */
781 int fd;
782 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000783 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
784#ifdef O_BINARY
785 |O_BINARY /* necessary for Windows */
786#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000787#ifdef __VMS
788 , 0666, "ctxt=bin", "shr=nil");
789#else
790 , 0666);
791#endif
Guido van Rossum55a83382000-09-20 20:31:38 +0000792 if (fd < 0)
793 return NULL;
794 return fdopen(fd, "wb");
795#else
796 /* Best we can do -- on Windows this can't happen anyway */
797 return fopen(filename, "wb");
798#endif
799}
800
801
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000802/* Write a compiled module to a file, placing the time of last
803 modification of its source into the header.
804 Errors are ignored, if a write error occurs an attempt is made to
805 remove the file. */
806
807static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000808write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000809{
810 FILE *fp;
811
Guido van Rossum55a83382000-09-20 20:31:38 +0000812 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000814 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000815 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000816 "# can't create %s\n", cpathname);
817 return;
818 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000819 PyMarshal_WriteLongToFile(pyc_magic, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000820 /* First write a 0 for mtime */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000821 PyMarshal_WriteLongToFile(0L, fp);
822 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000823 if (ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000824 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000825 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000826 /* Don't keep partial file */
827 fclose(fp);
828 (void) unlink(cpathname);
829 return;
830 }
831 /* Now write the true mtime */
832 fseek(fp, 4L, 0);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000833 PyMarshal_WriteLongToFile(mtime, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000834 fflush(fp);
835 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000836 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000837 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000838#ifdef macintosh
Jack Jansencbf630f2000-07-11 21:59:16 +0000839 PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000840#endif
841}
842
843
844/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000845 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
846 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000847
Guido van Rossum79f25d91997-04-29 20:08:16 +0000848static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000849load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000850{
Fred Drake4c82b232000-06-30 16:18:57 +0000851 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000852 FILE *fpc;
853 char buf[MAXPATHLEN+1];
854 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000855 PyCodeObject *co;
856 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000857
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000858 mtime = PyOS_GetLastModificationTime(pathname, fp);
Fred Drakec63d3e92001-03-01 06:33:32 +0000859 if (mtime == (time_t)(-1))
Fred Drake4c82b232000-06-30 16:18:57 +0000860 return NULL;
861#if SIZEOF_TIME_T > 4
862 /* Python's .pyc timestamp handling presumes that the timestamp fits
863 in 4 bytes. This will be fine until sometime in the year 2038,
864 when a 4-byte signed time_t will overflow.
865 */
866 if (mtime >> 32) {
867 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000868 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000869 return NULL;
870 }
871#endif
Tim Peters36515e22001-11-18 04:06:29 +0000872 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000873 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874 if (cpathname != NULL &&
875 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000876 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000877 fclose(fpc);
878 if (co == NULL)
879 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000880 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000881 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000883 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884 }
885 else {
886 co = parse_source_module(pathname, fp);
887 if (co == NULL)
888 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000889 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000890 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000891 name, pathname);
892 write_compiled_module(co, cpathname, mtime);
893 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000894 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000895 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000896
897 return m;
898}
899
900
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000901/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000902static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
903static struct filedescr *find_module(char *, char *, PyObject *,
904 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000905static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000906
907/* Load a package and return its module object WITH INCREMENTED
908 REFERENCE COUNT */
909
910static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000911load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000912{
913 PyObject *m, *d, *file, *path;
914 int err;
915 char buf[MAXPATHLEN+1];
916 FILE *fp = NULL;
917 struct filedescr *fdp;
918
919 m = PyImport_AddModule(name);
920 if (m == NULL)
921 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000922 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000923 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000924 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000925 d = PyModule_GetDict(m);
926 file = PyString_FromString(pathname);
927 if (file == NULL)
928 return NULL;
929 path = Py_BuildValue("[O]", file);
930 if (path == NULL) {
931 Py_DECREF(file);
932 return NULL;
933 }
934 err = PyDict_SetItemString(d, "__file__", file);
935 if (err == 0)
936 err = PyDict_SetItemString(d, "__path__", path);
937 if (err != 0) {
938 m = NULL;
939 goto cleanup;
940 }
941 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +0000942 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000943 if (fdp == NULL) {
944 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
945 PyErr_Clear();
946 }
947 else
948 m = NULL;
949 goto cleanup;
950 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000951 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000952 if (fp != NULL)
953 fclose(fp);
954 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000955 Py_XDECREF(path);
956 Py_XDECREF(file);
957 return m;
958}
959
960
961/* Helper to test for built-in module */
962
963static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000964is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000965{
966 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +0000967 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
968 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
969 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000970 return -1;
971 else
972 return 1;
973 }
974 }
975 return 0;
976}
977
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000978
Just van Rossum52e14d62002-12-30 22:08:05 +0000979/* Return an importer object for a sys.path/pkg.__path__ item 'p',
980 possibly by fetching it from the path_importer_cache dict. If it
981 wasn't yet cached, traverse path_hooks until it a hook is found
982 that can handle the path item. Return None if no hook could;
983 this tells our caller it should fall back to the builtin
984 import mechanism. Cache the result in path_importer_cache.
985 Returns a borrowed reference. */
986
987static PyObject *
988get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
989 PyObject *p)
990{
991 PyObject *importer;
992 int j, nhooks;
993
994 /* These conditions are the caller's responsibility: */
995 assert(PyList_Check(path_hooks));
996 assert(PyDict_Check(path_importer_cache));
997
998 nhooks = PyList_Size(path_hooks);
999 if (nhooks < 0)
1000 return NULL; /* Shouldn't happen */
1001
1002 importer = PyDict_GetItem(path_importer_cache, p);
1003 if (importer != NULL)
1004 return importer;
1005
1006 /* set path_importer_cache[p] to None to avoid recursion */
1007 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1008 return NULL;
1009
1010 for (j = 0; j < nhooks; j++) {
1011 PyObject *hook = PyList_GetItem(path_hooks, j);
1012 if (hook == NULL)
1013 return NULL;
1014 importer = PyObject_CallFunction(hook, "O", p);
1015 if (importer != NULL)
1016 break;
1017
1018 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1019 return NULL;
1020 }
1021 PyErr_Clear();
1022 }
1023 if (importer == NULL)
1024 importer = Py_None;
1025 else if (importer != Py_None) {
1026 int err = PyDict_SetItem(path_importer_cache, p, importer);
1027 Py_DECREF(importer);
1028 if (err != 0)
1029 return NULL;
1030 }
1031 return importer;
1032}
1033
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001034/* Search the path (default sys.path) for a module. Return the
1035 corresponding filedescr struct, and (via return arguments) the
1036 pathname and an open file. Return NULL if the module is not found. */
1037
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001038#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001039extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
1040 char *, int);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001041#endif
1042
Tim Peters50d8d372001-02-28 05:34:27 +00001043static int case_ok(char *, int, int, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001044static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001045static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001046
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001047static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001048find_module(char *fullname, char *subname, PyObject *path, char *buf,
1049 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001050{
Fred Drake4c82b232000-06-30 16:18:57 +00001051 int i, npath;
1052 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001053 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001054 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001055 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001056 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001057#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001058 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001059#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001060 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1061 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1062 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001063 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001064#if defined(PYOS_OS2)
1065 size_t saved_len;
1066 size_t saved_namelen;
1067 char *saved_buf = NULL;
1068#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001069 if (p_loader != NULL)
1070 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001071
Just van Rossum52e14d62002-12-30 22:08:05 +00001072 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001073 PyErr_SetString(PyExc_OverflowError,
1074 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001075 return NULL;
1076 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001077 strcpy(name, subname);
1078
1079 /* sys.meta_path import hook */
1080 if (p_loader != NULL) {
1081 PyObject *meta_path;
1082
1083 meta_path = PySys_GetObject("meta_path");
1084 if (meta_path == NULL || !PyList_Check(meta_path)) {
1085 PyErr_SetString(PyExc_ImportError,
1086 "sys.meta_path must be a list of "
1087 "import hooks");
1088 return NULL;
1089 }
1090 Py_INCREF(meta_path); /* zap guard */
1091 npath = PyList_Size(meta_path);
1092 for (i = 0; i < npath; i++) {
1093 PyObject *loader;
1094 PyObject *hook = PyList_GetItem(meta_path, i);
1095 loader = PyObject_CallMethod(hook, "find_module",
1096 "sO", fullname,
1097 path != NULL ?
1098 path : Py_None);
1099 if (loader == NULL) {
1100 Py_DECREF(meta_path);
1101 return NULL; /* true error */
1102 }
1103 if (loader != Py_None) {
1104 /* a loader was found */
1105 *p_loader = loader;
1106 Py_DECREF(meta_path);
1107 return &importhookdescr;
1108 }
1109 Py_DECREF(loader);
1110 }
1111 Py_DECREF(meta_path);
1112 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001113
1114 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001115 /* The only type of submodule allowed inside a "frozen"
1116 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +00001117 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1118 PyErr_SetString(PyExc_ImportError,
1119 "full frozen module name too long");
1120 return NULL;
1121 }
1122 strcpy(buf, PyString_AsString(path));
1123 strcat(buf, ".");
1124 strcat(buf, name);
1125 strcpy(name, buf);
Jack Jansen550fdae2001-10-30 13:08:39 +00001126#ifdef macintosh
1127 /* Freezing on the mac works different, and the modules are
1128 ** actually on sys.path. So we don't take the quick exit but
1129 ** continue with the normal flow.
1130 */
1131 path = NULL;
1132#else
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001133 if (find_frozen(name) != NULL) {
1134 strcpy(buf, name);
1135 return &fd_frozen;
1136 }
1137 PyErr_Format(PyExc_ImportError,
1138 "No frozen submodule named %.200s", name);
1139 return NULL;
Jack Jansen550fdae2001-10-30 13:08:39 +00001140#endif
Guido van Rossum0506a431998-08-11 15:07:39 +00001141 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001142 if (path == NULL) {
1143 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001144 strcpy(buf, name);
1145 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001146 }
Greg Ward201baee2001-10-04 14:52:06 +00001147 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001148 strcpy(buf, name);
1149 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001150 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001151
Guido van Rossumac279101996-08-22 23:10:58 +00001152#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001153 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1154 if (fp != NULL) {
1155 *p_fp = fp;
1156 return fdp;
1157 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001158#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001159 path = PySys_GetObject("path");
1160 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001161 if (path == NULL || !PyList_Check(path)) {
1162 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001163 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001164 return NULL;
1165 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001166
1167 path_hooks = PySys_GetObject("path_hooks");
1168 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1169 PyErr_SetString(PyExc_ImportError,
1170 "sys.path_hooks must be a list of "
1171 "import hooks");
1172 return NULL;
1173 }
1174 path_importer_cache = PySys_GetObject("path_importer_cache");
1175 if (path_importer_cache == NULL ||
1176 !PyDict_Check(path_importer_cache)) {
1177 PyErr_SetString(PyExc_ImportError,
1178 "sys.path_importer_cache must be a dict");
1179 return NULL;
1180 }
1181
Guido van Rossum79f25d91997-04-29 20:08:16 +00001182 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001183 namelen = strlen(name);
1184 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001185 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001186 PyObject *v = PyList_GetItem(path, i);
Walter Dörwald3430d702002-06-17 10:43:59 +00001187#ifdef Py_USING_UNICODE
1188 if (PyUnicode_Check(v)) {
1189 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1190 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1191 if (copy == NULL)
1192 return NULL;
1193 v = copy;
1194 }
1195 else
1196#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +00001197 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001198 continue;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001199 len = PyString_Size(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001200 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1201 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001202 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001203 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001204 strcpy(buf, PyString_AsString(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001205 if (strlen(buf) != len) {
1206 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001207 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001208 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001209
1210 /* sys.path_hooks import hook */
1211 if (p_loader != NULL) {
1212 PyObject *importer;
1213
1214 importer = get_path_importer(path_importer_cache,
1215 path_hooks, v);
1216 if (importer == NULL)
1217 return NULL;
1218 /* Note: importer is a borrowed reference */
1219 if (importer != Py_None) {
1220 PyObject *loader;
1221 loader = PyObject_CallMethod(importer,
1222 "find_module",
1223 "s", fullname);
1224 if (loader == NULL)
1225 return NULL; /* error */
1226 if (loader != Py_None) {
1227 /* a loader was found */
1228 *p_loader = loader;
1229 return &importhookdescr;
1230 }
1231 Py_DECREF(loader);
1232 }
1233 /* no hook was successful, use builtin import */
1234 }
1235
Jack Jansen9c96a921995-02-15 22:57:06 +00001236#ifdef macintosh
Tim Peters50d8d372001-02-28 05:34:27 +00001237 /*
Guido van Rossum741689d1997-08-12 14:53:39 +00001238 ** Speedup: each sys.path item is interned, and
1239 ** FindResourceModule remembers which items refer to
1240 ** folders (so we don't have to bother trying to look
Jack Jansen9363dca2003-01-24 16:15:45 +00001241 ** into them for resources). We only do this for string
1242 ** items.
Guido van Rossum741689d1997-08-12 14:53:39 +00001243 */
Jack Jansen9363dca2003-01-24 16:15:45 +00001244 if (PyString_Check(PyList_GET_ITEM(path, i))) {
1245 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
1246 v = PyList_GET_ITEM(path, i);
1247 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
1248 static struct filedescr resfiledescr =
1249 {"", "", PY_RESOURCE};
Tim Peters50d8d372001-02-28 05:34:27 +00001250
Jack Jansen9363dca2003-01-24 16:15:45 +00001251 Py_XDECREF(copy);
1252 return &resfiledescr;
1253 }
1254 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
1255 static struct filedescr resfiledescr =
1256 {"", "", PY_CODERESOURCE};
Tim Peters50d8d372001-02-28 05:34:27 +00001257
Jack Jansen9363dca2003-01-24 16:15:45 +00001258 Py_XDECREF(copy);
1259 return &resfiledescr;
1260 }
Guido van Rossum0f84a341998-08-06 13:36:01 +00001261 }
Jack Jansen9c96a921995-02-15 22:57:06 +00001262#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001263 if (len > 0 && buf[len-1] != SEP
1264#ifdef ALTSEP
1265 && buf[len-1] != ALTSEP
1266#endif
1267 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001268 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001269 strcpy(buf+len, name);
1270 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001271
1272 /* Check for package import (buf holds a directory name,
1273 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001274#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001275 if (stat(buf, &statbuf) == 0 && /* it exists */
1276 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1277 find_init_module(buf) && /* it has __init__.py */
1278 case_ok(buf, len, namelen, name)) { /* and case matches */
1279 Py_XDECREF(copy);
Tim Peterscab3f682001-04-29 22:21:25 +00001280 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001281 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001282#else
1283 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001284#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001285 if (isdir(buf) &&
1286 find_init_module(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001287 case_ok(buf, len, namelen, name)) {
1288 Py_XDECREF(copy);
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001289 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001290 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001291#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001292#endif
Guido van Rossum9a61dc91997-10-08 15:25:08 +00001293#ifdef macintosh
1294 fdp = PyMac_FindModuleExtension(buf, &len, name);
Jack Jansen4df3c522001-03-20 23:09:54 +00001295 if (fdp) {
Guido van Rossum9a61dc91997-10-08 15:25:08 +00001296#else
Andrew MacIntyred9400542002-02-26 11:41:34 +00001297#if defined(PYOS_OS2)
1298 /* take a snapshot of the module spec for restoration
1299 * after the 8 character DLL hackery
1300 */
1301 saved_buf = strdup(buf);
1302 saved_len = len;
1303 saved_namelen = namelen;
1304#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001305 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001306#if defined(PYOS_OS2)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001307 /* OS/2 limits DLLs to 8 character names (w/o
1308 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001309 * so if the name is longer than that and its a
1310 * dynamically loaded module we're going to try,
1311 * truncate the name before trying
1312 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001313 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001314 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001315 const struct filedescr *scan;
1316 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001317 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001318 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001319 break;
1320 else
1321 scan++;
1322 }
1323 if (scan->suffix != NULL) {
1324 /* yes, so truncate the name */
1325 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001326 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001327 buf[len] = '\0';
1328 }
1329 }
1330#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001331 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001332 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001333 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansen4df3c522001-03-20 23:09:54 +00001334#endif /* !macintosh */
Jack Jansenc88da1f2002-05-28 10:58:19 +00001335 filemode = fdp->mode;
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001336 if (filemode[0] == 'U')
1337 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001338 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001339 if (fp != NULL) {
1340 if (case_ok(buf, len, namelen, name))
1341 break;
1342 else { /* continue search */
1343 fclose(fp);
1344 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001345 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001346 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001347#if defined(PYOS_OS2)
1348 /* restore the saved snapshot */
1349 strcpy(buf, saved_buf);
1350 len = saved_len;
1351 namelen = saved_namelen;
1352#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001353 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001354#if defined(PYOS_OS2)
1355 /* don't need/want the module name snapshot anymore */
1356 if (saved_buf)
1357 {
1358 free(saved_buf);
1359 saved_buf = NULL;
1360 }
1361#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001362 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001363 if (fp != NULL)
1364 break;
1365 }
1366 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001367 PyErr_Format(PyExc_ImportError,
1368 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001369 return NULL;
1370 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001371 *p_fp = fp;
1372 return fdp;
1373}
1374
Tim Petersd1e87a82001-03-01 18:12:00 +00001375/* case_ok(char* buf, int len, int namelen, char* name)
1376 * The arguments here are tricky, best shown by example:
1377 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1378 * ^ ^ ^ ^
1379 * |--------------------- buf ---------------------|
1380 * |------------------- len ------------------|
1381 * |------ name -------|
1382 * |----- namelen -----|
1383 * buf is the full path, but len only counts up to (& exclusive of) the
1384 * extension. name is the module name, also exclusive of extension.
1385 *
1386 * We've already done a successful stat() or fopen() on buf, so know that
1387 * there's some match, possibly case-insensitive.
1388 *
Tim Peters50d8d372001-02-28 05:34:27 +00001389 * case_ok() is to return 1 if there's a case-sensitive match for
1390 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1391 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001392 *
Tim Peters50d8d372001-02-28 05:34:27 +00001393 * case_ok() is used to implement case-sensitive import semantics even
1394 * on platforms with case-insensitive filesystems. It's trivial to implement
1395 * for case-sensitive filesystems. It's pretty much a cross-platform
1396 * nightmare for systems with case-insensitive filesystems.
1397 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001398
Tim Peters50d8d372001-02-28 05:34:27 +00001399/* First we may need a pile of platform-specific header files; the sequence
1400 * of #if's here should match the sequence in the body of case_ok().
1401 */
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001402#if defined(MS_WINDOWS) || defined(__CYGWIN__)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001403#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001404#ifdef __CYGWIN__
1405#include <sys/cygwin.h>
1406#endif
1407
Tim Peters50d8d372001-02-28 05:34:27 +00001408#elif defined(DJGPP)
1409#include <dir.h>
1410
1411#elif defined(macintosh)
1412#include <TextUtils.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001413
Tim Petersd1e87a82001-03-01 18:12:00 +00001414#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001415#include <sys/types.h>
1416#include <dirent.h>
1417
Andrew MacIntyred9400542002-02-26 11:41:34 +00001418#elif defined(PYOS_OS2)
1419#define INCL_DOS
1420#define INCL_DOSERRORS
1421#define INCL_NOPMAPI
1422#include <os2.h>
1423
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001424#elif defined(RISCOS)
1425#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001426#endif
1427
Guido van Rossum0980bd91998-02-13 17:18:36 +00001428static int
Tim Peters50d8d372001-02-28 05:34:27 +00001429case_ok(char *buf, int len, int namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001430{
Tim Peters50d8d372001-02-28 05:34:27 +00001431/* Pick a platform-specific implementation; the sequence of #if's here should
1432 * match the sequence just above.
1433 */
1434
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001435/* MS_WINDOWS || __CYGWIN__ */
1436#if defined(MS_WINDOWS) || defined(__CYGWIN__)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001437 WIN32_FIND_DATA data;
1438 HANDLE h;
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001439#ifdef __CYGWIN__
1440 char tempbuf[MAX_PATH];
1441#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001442
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001443 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001444 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001445
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001446#ifdef __CYGWIN__
1447 cygwin32_conv_to_win32_path(buf, tempbuf);
1448 h = FindFirstFile(tempbuf, &data);
1449#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001450 h = FindFirstFile(buf, &data);
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001451#endif
Guido van Rossum0980bd91998-02-13 17:18:36 +00001452 if (h == INVALID_HANDLE_VALUE) {
1453 PyErr_Format(PyExc_NameError,
1454 "Can't find file for module %.100s\n(filename %.300s)",
1455 name, buf);
1456 return 0;
1457 }
1458 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001459 return strncmp(data.cFileName, name, namelen) == 0;
1460
1461/* DJGPP */
1462#elif defined(DJGPP)
1463 struct ffblk ffblk;
1464 int done;
1465
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001466 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001467 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001468
1469 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1470 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001471 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001472 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001473 name, buf);
1474 return 0;
1475 }
Tim Peters50d8d372001-02-28 05:34:27 +00001476 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001477
Tim Peters50d8d372001-02-28 05:34:27 +00001478/* macintosh */
1479#elif defined(macintosh)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001480 FSSpec fss;
1481 OSErr err;
Tim Peters50d8d372001-02-28 05:34:27 +00001482
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001483 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Peters50d8d372001-02-28 05:34:27 +00001484 return 1;
1485
Guido van Rossuma0f0a331998-09-14 13:40:53 +00001486 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
Guido van Rossum0980bd91998-02-13 17:18:36 +00001487 if (err) {
1488 PyErr_Format(PyExc_NameError,
Guido van Rossuma0f0a331998-09-14 13:40:53 +00001489 "Can't find file for module %.100s\n(filename %.300s)",
1490 name, buf);
Guido van Rossum0980bd91998-02-13 17:18:36 +00001491 return 0;
1492 }
Tim Peters50d8d372001-02-28 05:34:27 +00001493 return fss.name[0] >= namelen &&
1494 strncmp(name, (char *)fss.name+1, namelen) == 0;
1495
Tim Peters677898a2001-03-02 03:28:03 +00001496/* new-fangled macintosh (macosx) */
Tim Petersd1e87a82001-03-01 18:12:00 +00001497#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001498 DIR *dirp;
1499 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001500 char dirname[MAXPATHLEN + 1];
1501 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001502
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001503 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001504 return 1;
1505
Tim Petersd1e87a82001-03-01 18:12:00 +00001506 /* Copy the dir component into dirname; substitute "." if empty */
1507 if (dirlen <= 0) {
1508 dirname[0] = '.';
1509 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001510 }
1511 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001512 assert(dirlen <= MAXPATHLEN);
1513 memcpy(dirname, buf, dirlen);
1514 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001515 }
1516 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001517 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001518 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001519 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001520 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001521 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001522#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001523 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001524#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001525 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001526#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001527 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001528 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001529 (void)closedir(dirp);
1530 return 1; /* Found */
1531 }
1532 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001533 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001534 }
Tim Peters430f5d42001-03-01 01:30:56 +00001535 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001536
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001537/* RISC OS */
1538#elif defined(RISCOS)
1539 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1540 char buf2[MAXPATHLEN+2];
1541 char *nameWithExt = buf+len-namelen;
1542 int canonlen;
1543 os_error *e;
1544
1545 if (Py_GETENV("PYTHONCASEOK") != NULL)
1546 return 1;
1547
1548 /* workaround:
1549 append wildcard, otherwise case of filename wouldn't be touched */
1550 strcpy(buf2, buf);
1551 strcat(buf2, "*");
1552
1553 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1554 canonlen = MAXPATHLEN+1-canonlen;
1555 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1556 return 0;
1557 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1558 return 1; /* match */
1559
1560 return 0;
1561
Andrew MacIntyred9400542002-02-26 11:41:34 +00001562/* OS/2 */
1563#elif defined(PYOS_OS2)
1564 HDIR hdir = 1;
1565 ULONG srchcnt = 1;
1566 FILEFINDBUF3 ffbuf;
1567 APIRET rc;
1568
1569 if (getenv("PYTHONCASEOK") != NULL)
1570 return 1;
1571
1572 rc = DosFindFirst(buf,
1573 &hdir,
1574 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1575 &ffbuf, sizeof(ffbuf),
1576 &srchcnt,
1577 FIL_STANDARD);
1578 if (rc != NO_ERROR)
1579 return 0;
1580 return strncmp(ffbuf.achName, name, namelen) == 0;
1581
Tim Peters50d8d372001-02-28 05:34:27 +00001582/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1583#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001584 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001585
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001586#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001587}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001588
Guido van Rossum0980bd91998-02-13 17:18:36 +00001589
Guido van Rossum197346f1997-10-31 18:38:52 +00001590#ifdef HAVE_STAT
1591/* Helper to look for __init__.py or __init__.py[co] in potential package */
1592static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001593find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001594{
Tim Peters0f9431f2001-07-05 03:47:53 +00001595 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001596 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001597 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001598 struct stat statbuf;
1599
Tim Peters0f9431f2001-07-05 03:47:53 +00001600/* For calling case_ok(buf, len, namelen, name):
1601 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1602 * ^ ^ ^ ^
1603 * |--------------------- buf ---------------------|
1604 * |------------------- len ------------------|
1605 * |------ name -------|
1606 * |----- namelen -----|
1607 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001608 if (save_len + 13 >= MAXPATHLEN)
1609 return 0;
1610 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001611 pname = buf + i;
1612 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001613 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001614 if (case_ok(buf,
1615 save_len + 9, /* len("/__init__") */
1616 8, /* len("__init__") */
1617 pname)) {
1618 buf[save_len] = '\0';
1619 return 1;
1620 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001621 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001622 i += strlen(pname);
1623 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001624 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001625 if (case_ok(buf,
1626 save_len + 9, /* len("/__init__") */
1627 8, /* len("__init__") */
1628 pname)) {
1629 buf[save_len] = '\0';
1630 return 1;
1631 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001632 }
1633 buf[save_len] = '\0';
1634 return 0;
1635}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001636
1637#else
1638
1639#ifdef RISCOS
1640static int
1641find_init_module(buf)
1642 char *buf;
1643{
1644 int save_len = strlen(buf);
1645 int i = save_len;
1646
1647 if (save_len + 13 >= MAXPATHLEN)
1648 return 0;
1649 buf[i++] = SEP;
1650 strcpy(buf+i, "__init__/py");
1651 if (isfile(buf)) {
1652 buf[save_len] = '\0';
1653 return 1;
1654 }
1655
1656 if (Py_OptimizeFlag)
1657 strcpy(buf+i, "o");
1658 else
1659 strcpy(buf+i, "c");
1660 if (isfile(buf)) {
1661 buf[save_len] = '\0';
1662 return 1;
1663 }
1664 buf[save_len] = '\0';
1665 return 0;
1666}
1667#endif /*RISCOS*/
1668
Guido van Rossum197346f1997-10-31 18:38:52 +00001669#endif /* HAVE_STAT */
1670
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001671
Tim Petersdbd9ba62000-07-09 03:09:57 +00001672static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001673
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001674/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001675 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001676
Guido van Rossum79f25d91997-04-29 20:08:16 +00001677static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001678load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001679{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001680 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001681 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001682 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001683
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001684 /* First check that there's an open file (if we need one) */
1685 switch (type) {
1686 case PY_SOURCE:
1687 case PY_COMPILED:
1688 if (fp == NULL) {
1689 PyErr_Format(PyExc_ValueError,
1690 "file object required for import (type code %d)",
1691 type);
1692 return NULL;
1693 }
1694 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001695
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001696 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001697
1698 case PY_SOURCE:
1699 m = load_source_module(name, buf, fp);
1700 break;
1701
1702 case PY_COMPILED:
1703 m = load_compiled_module(name, buf, fp);
1704 break;
1705
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001706#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001707 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001708 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001709 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001710#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001711
Jack Jansen9c96a921995-02-15 22:57:06 +00001712#ifdef macintosh
1713 case PY_RESOURCE:
1714 m = PyMac_LoadResourceModule(name, buf);
1715 break;
Guido van Rossum0f84a341998-08-06 13:36:01 +00001716 case PY_CODERESOURCE:
1717 m = PyMac_LoadCodeResourceModule(name, buf);
1718 break;
Jack Jansen9c96a921995-02-15 22:57:06 +00001719#endif
1720
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001721 case PKG_DIRECTORY:
1722 m = load_package(name, buf);
1723 break;
1724
1725 case C_BUILTIN:
1726 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001727 if (buf != NULL && buf[0] != '\0')
1728 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001729 if (type == C_BUILTIN)
1730 err = init_builtin(name);
1731 else
1732 err = PyImport_ImportFrozenModule(name);
1733 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001734 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001735 if (err == 0) {
1736 PyErr_Format(PyExc_ImportError,
1737 "Purported %s module %.200s not found",
1738 type == C_BUILTIN ?
1739 "builtin" : "frozen",
1740 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001741 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001742 }
1743 modules = PyImport_GetModuleDict();
1744 m = PyDict_GetItemString(modules, name);
1745 if (m == NULL) {
1746 PyErr_Format(
1747 PyExc_ImportError,
1748 "%s module %.200s not properly initialized",
1749 type == C_BUILTIN ?
1750 "builtin" : "frozen",
1751 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001752 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001753 }
1754 Py_INCREF(m);
1755 break;
1756
Just van Rossum52e14d62002-12-30 22:08:05 +00001757 case IMP_HOOK: {
1758 if (loader == NULL) {
1759 PyErr_SetString(PyExc_ImportError,
1760 "import hook without loader");
1761 return NULL;
1762 }
1763 m = PyObject_CallMethod(loader, "load_module", "s", name);
1764 break;
1765 }
1766
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001767 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001768 PyErr_Format(PyExc_ImportError,
1769 "Don't know how to import %.200s (type code %d)",
1770 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001771 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001772
1773 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001774
1775 return m;
1776}
1777
1778
1779/* Initialize a built-in module.
1780 Return 1 for succes, 0 if the module is not found, and -1 with
1781 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001782
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001783static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001784init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001785{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001786 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001787
Greg Ward201baee2001-10-04 14:52:06 +00001788 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001789 return 1;
1790
Guido van Rossum771c6c81997-10-31 18:37:24 +00001791 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001792 if (strcmp(name, p->name) == 0) {
1793 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001794 PyErr_Format(PyExc_ImportError,
1795 "Cannot re-init internal module %.200s",
1796 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001797 return -1;
1798 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001799 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001800 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001801 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001802 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001803 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001804 if (_PyImport_FixupExtension(name, name) == NULL)
1805 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001806 return 1;
1807 }
1808 }
1809 return 0;
1810}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001811
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001812
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001813/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001814
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001815static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001816find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001817{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001818 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001819
Guido van Rossum79f25d91997-04-29 20:08:16 +00001820 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001821 if (p->name == NULL)
1822 return NULL;
1823 if (strcmp(p->name, name) == 0)
1824 break;
1825 }
1826 return p;
1827}
1828
Guido van Rossum79f25d91997-04-29 20:08:16 +00001829static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001830get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001831{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001832 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001833 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001834
1835 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001836 PyErr_Format(PyExc_ImportError,
1837 "No such frozen object named %.200s",
1838 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001839 return NULL;
1840 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001841 if (p->code == NULL) {
1842 PyErr_Format(PyExc_ImportError,
1843 "Excluded frozen object named %.200s",
1844 name);
1845 return NULL;
1846 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001847 size = p->size;
1848 if (size < 0)
1849 size = -size;
1850 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001851}
1852
1853/* Initialize a frozen module.
1854 Return 1 for succes, 0 if the module is not found, and -1 with
1855 an exception set if the initialization failed.
1856 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001857
1858int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001859PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001860{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001861 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001862 PyObject *co;
1863 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001864 int ispackage;
1865 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001866
1867 if (p == NULL)
1868 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001869 if (p->code == NULL) {
1870 PyErr_Format(PyExc_ImportError,
1871 "Excluded frozen object named %.200s",
1872 name);
1873 return -1;
1874 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001875 size = p->size;
1876 ispackage = (size < 0);
1877 if (ispackage)
1878 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001879 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001880 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001881 name, ispackage ? " package" : "");
1882 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001883 if (co == NULL)
1884 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001885 if (!PyCode_Check(co)) {
1886 Py_DECREF(co);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001887 PyErr_Format(PyExc_TypeError,
1888 "frozen object %.200s is not a code object",
1889 name);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001890 return -1;
1891 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001892 if (ispackage) {
1893 /* Set __path__ to the package name */
1894 PyObject *d, *s;
1895 int err;
1896 m = PyImport_AddModule(name);
1897 if (m == NULL)
1898 return -1;
1899 d = PyModule_GetDict(m);
1900 s = PyString_InternFromString(name);
1901 if (s == NULL)
1902 return -1;
1903 err = PyDict_SetItemString(d, "__path__", s);
1904 Py_DECREF(s);
1905 if (err != 0)
1906 return err;
1907 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001908 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum79f25d91997-04-29 20:08:16 +00001909 Py_DECREF(co);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001910 if (m == NULL)
1911 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001912 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001913 return 1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001914}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001915
1916
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001917/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001918 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001919
Guido van Rossum79f25d91997-04-29 20:08:16 +00001920PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001921PyImport_ImportModule(char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001922{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001923 PyObject *pname;
1924 PyObject *result;
1925
1926 pname = PyString_FromString(name);
1927 result = PyImport_Import(pname);
1928 Py_DECREF(pname);
1929 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001930}
1931
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001932/* Forward declarations for helper routines */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001933static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1934static PyObject *load_next(PyObject *mod, PyObject *altmod,
1935 char **p_name, char *buf, int *p_buflen);
1936static int mark_miss(char *name);
1937static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1938 char *buf, int buflen, int recursive);
1939static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001940
1941/* The Magnum Opus of dotted-name import :-) */
1942
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001943static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001944import_module_ex(char *name, PyObject *globals, PyObject *locals,
1945 PyObject *fromlist)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001946{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001947 char buf[MAXPATHLEN+1];
1948 int buflen = 0;
1949 PyObject *parent, *head, *next, *tail;
1950
1951 parent = get_parent(globals, buf, &buflen);
1952 if (parent == NULL)
1953 return NULL;
1954
1955 head = load_next(parent, Py_None, &name, buf, &buflen);
1956 if (head == NULL)
1957 return NULL;
1958
1959 tail = head;
1960 Py_INCREF(tail);
1961 while (name) {
1962 next = load_next(tail, tail, &name, buf, &buflen);
1963 Py_DECREF(tail);
1964 if (next == NULL) {
1965 Py_DECREF(head);
1966 return NULL;
1967 }
1968 tail = next;
1969 }
1970
1971 if (fromlist != NULL) {
1972 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1973 fromlist = NULL;
1974 }
1975
1976 if (fromlist == NULL) {
1977 Py_DECREF(tail);
1978 return head;
1979 }
1980
1981 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001982 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001983 Py_DECREF(tail);
1984 return NULL;
1985 }
1986
1987 return tail;
1988}
1989
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001990PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001991PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1992 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001993{
1994 PyObject *result;
1995 lock_import();
Guido van Rossumd65911b1998-03-03 22:33:27 +00001996 result = import_module_ex(name, globals, locals, fromlist);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001997 if (unlock_import() < 0) {
1998 Py_XDECREF(result);
1999 PyErr_SetString(PyExc_RuntimeError,
2000 "not holding the import lock");
2001 return NULL;
2002 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002003 return result;
2004}
2005
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002006static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002007get_parent(PyObject *globals, char *buf, int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002008{
2009 static PyObject *namestr = NULL;
2010 static PyObject *pathstr = NULL;
2011 PyObject *modname, *modpath, *modules, *parent;
2012
2013 if (globals == NULL || !PyDict_Check(globals))
2014 return Py_None;
2015
2016 if (namestr == NULL) {
2017 namestr = PyString_InternFromString("__name__");
2018 if (namestr == NULL)
2019 return NULL;
2020 }
2021 if (pathstr == NULL) {
2022 pathstr = PyString_InternFromString("__path__");
2023 if (pathstr == NULL)
2024 return NULL;
2025 }
2026
2027 *buf = '\0';
2028 *p_buflen = 0;
2029 modname = PyDict_GetItem(globals, namestr);
2030 if (modname == NULL || !PyString_Check(modname))
2031 return Py_None;
2032
2033 modpath = PyDict_GetItem(globals, pathstr);
2034 if (modpath != NULL) {
2035 int len = PyString_GET_SIZE(modname);
2036 if (len > MAXPATHLEN) {
2037 PyErr_SetString(PyExc_ValueError,
2038 "Module name too long");
2039 return NULL;
2040 }
2041 strcpy(buf, PyString_AS_STRING(modname));
2042 *p_buflen = len;
2043 }
2044 else {
2045 char *start = PyString_AS_STRING(modname);
2046 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002047 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002048 if (lastdot == NULL)
2049 return Py_None;
2050 len = lastdot - start;
2051 if (len >= MAXPATHLEN) {
2052 PyErr_SetString(PyExc_ValueError,
2053 "Module name too long");
2054 return NULL;
2055 }
2056 strncpy(buf, start, len);
2057 buf[len] = '\0';
2058 *p_buflen = len;
2059 }
2060
2061 modules = PyImport_GetModuleDict();
2062 parent = PyDict_GetItemString(modules, buf);
2063 if (parent == NULL)
2064 parent = Py_None;
2065 return parent;
2066 /* We expect, but can't guarantee, if parent != None, that:
2067 - parent.__name__ == buf
2068 - parent.__dict__ is globals
2069 If this is violated... Who cares? */
2070}
2071
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002072/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002073static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002074load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
2075 int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002076{
2077 char *name = *p_name;
2078 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002079 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002080 char *p;
2081 PyObject *result;
2082
2083 if (dot == NULL) {
2084 *p_name = NULL;
2085 len = strlen(name);
2086 }
2087 else {
2088 *p_name = dot+1;
2089 len = dot-name;
2090 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002091 if (len == 0) {
2092 PyErr_SetString(PyExc_ValueError,
2093 "Empty module name");
2094 return NULL;
2095 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002096
2097 p = buf + *p_buflen;
2098 if (p != buf)
2099 *p++ = '.';
2100 if (p+len-buf >= MAXPATHLEN) {
2101 PyErr_SetString(PyExc_ValueError,
2102 "Module name too long");
2103 return NULL;
2104 }
2105 strncpy(p, name, len);
2106 p[len] = '\0';
2107 *p_buflen = p+len-buf;
2108
2109 result = import_submodule(mod, p, buf);
2110 if (result == Py_None && altmod != mod) {
2111 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002112 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002113 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002114 if (result != NULL && result != Py_None) {
2115 if (mark_miss(buf) != 0) {
2116 Py_DECREF(result);
2117 return NULL;
2118 }
2119 strncpy(buf, name, len);
2120 buf[len] = '\0';
2121 *p_buflen = len;
2122 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002123 }
2124 if (result == NULL)
2125 return NULL;
2126
2127 if (result == Py_None) {
2128 Py_DECREF(result);
2129 PyErr_Format(PyExc_ImportError,
2130 "No module named %.200s", name);
2131 return NULL;
2132 }
2133
2134 return result;
2135}
2136
2137static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002138mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002139{
2140 PyObject *modules = PyImport_GetModuleDict();
2141 return PyDict_SetItemString(modules, name, Py_None);
2142}
2143
2144static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002145ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
2146 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002147{
2148 int i;
2149
2150 if (!PyObject_HasAttrString(mod, "__path__"))
2151 return 1;
2152
2153 for (i = 0; ; i++) {
2154 PyObject *item = PySequence_GetItem(fromlist, i);
2155 int hasit;
2156 if (item == NULL) {
2157 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2158 PyErr_Clear();
2159 return 1;
2160 }
2161 return 0;
2162 }
2163 if (!PyString_Check(item)) {
2164 PyErr_SetString(PyExc_TypeError,
2165 "Item in ``from list'' not a string");
2166 Py_DECREF(item);
2167 return 0;
2168 }
2169 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002170 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002171 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002172 /* See if the package defines __all__ */
2173 if (recursive)
2174 continue; /* Avoid endless recursion */
2175 all = PyObject_GetAttrString(mod, "__all__");
2176 if (all == NULL)
2177 PyErr_Clear();
2178 else {
2179 if (!ensure_fromlist(mod, all, buf, buflen, 1))
2180 return 0;
2181 Py_DECREF(all);
2182 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002183 continue;
2184 }
2185 hasit = PyObject_HasAttr(mod, item);
2186 if (!hasit) {
2187 char *subname = PyString_AS_STRING(item);
2188 PyObject *submod;
2189 char *p;
2190 if (buflen + strlen(subname) >= MAXPATHLEN) {
2191 PyErr_SetString(PyExc_ValueError,
2192 "Module name too long");
2193 Py_DECREF(item);
2194 return 0;
2195 }
2196 p = buf + buflen;
2197 *p++ = '.';
2198 strcpy(p, subname);
2199 submod = import_submodule(mod, subname, buf);
2200 Py_XDECREF(submod);
2201 if (submod == NULL) {
2202 Py_DECREF(item);
2203 return 0;
2204 }
2205 }
2206 Py_DECREF(item);
2207 }
2208
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002209 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002210}
2211
2212static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002213import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002214{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002215 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossumf48f11c2001-07-23 13:27:49 +00002216 PyObject *m, *res = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002217
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002218 /* Require:
2219 if mod == None: subname == fullname
2220 else: mod.__name__ + "." + subname == fullname
2221 */
2222
Tim Peters50d8d372001-02-28 05:34:27 +00002223 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002224 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002225 }
2226 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002227 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002228 char buf[MAXPATHLEN+1];
2229 struct filedescr *fdp;
2230 FILE *fp = NULL;
2231
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002232 if (mod == Py_None)
2233 path = NULL;
2234 else {
2235 path = PyObject_GetAttrString(mod, "__path__");
2236 if (path == NULL) {
2237 PyErr_Clear();
2238 Py_INCREF(Py_None);
2239 return Py_None;
2240 }
2241 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002242
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002243 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002244 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2245 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002246 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002247 if (fdp == NULL) {
2248 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2249 return NULL;
2250 PyErr_Clear();
2251 Py_INCREF(Py_None);
2252 return Py_None;
2253 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002254 m = load_module(fullname, fp, buf, fdp->type, loader);
2255 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002256 if (fp)
2257 fclose(fp);
Guido van Rossumf48f11c2001-07-23 13:27:49 +00002258 if (mod != Py_None) {
2259 /* Irrespective of the success of this load, make a
2260 reference to it in the parent package module.
2261 A copy gets saved in the modules dictionary
2262 under the full name, so get a reference from
2263 there, if need be. (The exception is when
2264 the load failed with a SyntaxError -- then
2265 there's no trace in sys.modules. In that case,
2266 of course, do nothing extra.) */
2267 res = m;
2268 if (res == NULL)
2269 res = PyDict_GetItemString(modules, fullname);
2270 if (res != NULL &&
2271 PyObject_SetAttrString(mod, subname, res) < 0) {
2272 Py_XDECREF(m);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002273 m = NULL;
2274 }
2275 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002276 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002277
2278 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002279}
2280
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002281
2282/* Re-import a module of any kind and return its module object, WITH
2283 INCREMENTED REFERENCE COUNT */
2284
Guido van Rossum79f25d91997-04-29 20:08:16 +00002285PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002286PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002287{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002288 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum222ef561997-09-06 19:41:09 +00002289 PyObject *path = NULL;
2290 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002291 char buf[MAXPATHLEN+1];
2292 struct filedescr *fdp;
2293 FILE *fp = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002294
Guido van Rossum79f25d91997-04-29 20:08:16 +00002295 if (m == NULL || !PyModule_Check(m)) {
2296 PyErr_SetString(PyExc_TypeError,
2297 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002298 return NULL;
2299 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002300 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002301 if (name == NULL)
2302 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002303 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002304 PyErr_Format(PyExc_ImportError,
2305 "reload(): module %.200s not in sys.modules",
2306 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002307 return NULL;
2308 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002309 subname = strrchr(name, '.');
2310 if (subname == NULL)
2311 subname = name;
2312 else {
2313 PyObject *parentname, *parent;
2314 parentname = PyString_FromStringAndSize(name, (subname-name));
2315 if (parentname == NULL)
2316 return NULL;
2317 parent = PyDict_GetItem(modules, parentname);
Barry Warsaw38793331999-01-27 17:54:20 +00002318 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002319 if (parent == NULL) {
2320 PyErr_Format(PyExc_ImportError,
2321 "reload(): parent %.200s not in sys.modules",
2322 name);
2323 return NULL;
2324 }
2325 subname++;
2326 path = PyObject_GetAttrString(parent, "__path__");
2327 if (path == NULL)
2328 PyErr_Clear();
2329 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002330 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002331 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum222ef561997-09-06 19:41:09 +00002332 Py_XDECREF(path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002333 if (fdp == NULL)
2334 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002335 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002336 if (fp)
2337 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002338 return m;
2339}
2340
2341
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002342/* Higher-level import emulator which emulates the "import" statement
2343 more accurately -- it invokes the __import__() function from the
2344 builtins of the current globals. This means that the import is
2345 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002346 environment, e.g. by "rexec".
2347 A dummy list ["__doc__"] is passed as the 4th argument so that
2348 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2349 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002350
2351PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002352PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002353{
2354 static PyObject *silly_list = NULL;
2355 static PyObject *builtins_str = NULL;
2356 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002357 PyObject *globals = NULL;
2358 PyObject *import = NULL;
2359 PyObject *builtins = NULL;
2360 PyObject *r = NULL;
2361
2362 /* Initialize constant string objects */
2363 if (silly_list == NULL) {
2364 import_str = PyString_InternFromString("__import__");
2365 if (import_str == NULL)
2366 return NULL;
2367 builtins_str = PyString_InternFromString("__builtins__");
2368 if (builtins_str == NULL)
2369 return NULL;
2370 silly_list = Py_BuildValue("[s]", "__doc__");
2371 if (silly_list == NULL)
2372 return NULL;
2373 }
2374
2375 /* Get the builtins from current globals */
2376 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002377 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002378 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002379 builtins = PyObject_GetItem(globals, builtins_str);
2380 if (builtins == NULL)
2381 goto err;
2382 }
2383 else {
2384 /* No globals -- use standard builtins, and fake globals */
2385 PyErr_Clear();
2386
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002387 builtins = PyImport_ImportModuleEx("__builtin__",
2388 NULL, NULL, NULL);
2389 if (builtins == NULL)
2390 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002391 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2392 if (globals == NULL)
2393 goto err;
2394 }
2395
2396 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002398 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399 if (import == NULL)
2400 PyErr_SetObject(PyExc_KeyError, import_str);
2401 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002402 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002403 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002404 if (import == NULL)
2405 goto err;
2406
2407 /* Call the _import__ function with the proper argument list */
2408 r = PyObject_CallFunction(import, "OOOO",
2409 module_name, globals, globals, silly_list);
2410
2411 err:
2412 Py_XDECREF(globals);
2413 Py_XDECREF(builtins);
2414 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002415
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002416 return r;
2417}
2418
2419
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002420/* Module 'imp' provides Python access to the primitives used for
2421 importing modules.
2422*/
2423
Guido van Rossum79f25d91997-04-29 20:08:16 +00002424static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002425imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002426{
2427 char buf[4];
2428
Guido van Rossum96774c12000-05-01 20:19:08 +00002429 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2430 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2431 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2432 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002433
Guido van Rossum79f25d91997-04-29 20:08:16 +00002434 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002435}
2436
Guido van Rossum79f25d91997-04-29 20:08:16 +00002437static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002438imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002439{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002440 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002441 struct filedescr *fdp;
2442
Guido van Rossum79f25d91997-04-29 20:08:16 +00002443 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002444 if (list == NULL)
2445 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002446 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2447 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002448 fdp->suffix, fdp->mode, fdp->type);
2449 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002450 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002451 return NULL;
2452 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002453 if (PyList_Append(list, item) < 0) {
2454 Py_DECREF(list);
2455 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002456 return NULL;
2457 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002458 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002459 }
2460 return list;
2461}
2462
Guido van Rossum79f25d91997-04-29 20:08:16 +00002463static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002464call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002465{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002466 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002467 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002468 struct filedescr *fdp;
2469 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002470 FILE *fp = NULL;
2471
2472 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002473 if (path == Py_None)
2474 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002475 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002476 if (fdp == NULL)
2477 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002478 if (fp != NULL) {
2479 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2480 if (fob == NULL) {
2481 fclose(fp);
2482 return NULL;
2483 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002484 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002485 else {
2486 fob = Py_None;
2487 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002488 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002489 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002490 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002491 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002492 return ret;
2493}
2494
Guido van Rossum79f25d91997-04-29 20:08:16 +00002495static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002496imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002497{
2498 char *name;
2499 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002500 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002501 return NULL;
2502 return call_find_module(name, path);
2503}
2504
2505static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002506imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002507{
2508 char *name;
2509 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002510 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002511 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002512 return NULL;
2513 ret = init_builtin(name);
2514 if (ret < 0)
2515 return NULL;
2516 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002517 Py_INCREF(Py_None);
2518 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002519 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002520 m = PyImport_AddModule(name);
2521 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002522 return m;
2523}
2524
Guido van Rossum79f25d91997-04-29 20:08:16 +00002525static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002526imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002527{
2528 char *name;
2529 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002530 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002531 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002532 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002533 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002534 if (ret < 0)
2535 return NULL;
2536 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002537 Py_INCREF(Py_None);
2538 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002539 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002540 m = PyImport_AddModule(name);
2541 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002542 return m;
2543}
2544
Guido van Rossum79f25d91997-04-29 20:08:16 +00002545static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002546imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002547{
2548 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002549
Guido van Rossum43713e52000-02-29 13:59:29 +00002550 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002551 return NULL;
2552 return get_frozen_object(name);
2553}
2554
Guido van Rossum79f25d91997-04-29 20:08:16 +00002555static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002556imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002557{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002558 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002559 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002560 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002561 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002562}
2563
Guido van Rossum79f25d91997-04-29 20:08:16 +00002564static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002565imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002566{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002567 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002568 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002569 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002570 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002571 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002572 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002573}
2574
2575static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002576get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002577{
2578 FILE *fp;
2579 if (fob == NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002580 if (mode[0] == 'U')
2581 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002582 fp = fopen(pathname, mode);
2583 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002584 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002585 }
2586 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002587 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002588 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002589 PyErr_SetString(PyExc_ValueError,
2590 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002591 }
2592 return fp;
2593}
2594
Guido van Rossum79f25d91997-04-29 20:08:16 +00002595static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002596imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002597{
2598 char *name;
2599 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002600 PyObject *fob = NULL;
2601 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002602 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002603 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002604 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002605 return NULL;
2606 fp = get_file(pathname, fob, "rb");
2607 if (fp == NULL)
2608 return NULL;
2609 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002610 if (fob == NULL)
2611 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002612 return m;
2613}
2614
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002615#ifdef HAVE_DYNAMIC_LOADING
2616
Guido van Rossum79f25d91997-04-29 20:08:16 +00002617static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002618imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002619{
2620 char *name;
2621 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002622 PyObject *fob = NULL;
2623 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002624 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002625 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002626 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002627 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002628 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002629 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002630 if (fp == NULL)
2631 return NULL;
2632 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002633 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002634 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002635}
2636
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002637#endif /* HAVE_DYNAMIC_LOADING */
2638
Guido van Rossum79f25d91997-04-29 20:08:16 +00002639static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002640imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002641{
2642 char *name;
2643 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002644 PyObject *fob = NULL;
2645 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002646 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002647 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002648 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002649 return NULL;
2650 fp = get_file(pathname, fob, "r");
2651 if (fp == NULL)
2652 return NULL;
2653 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002654 if (fob == NULL)
2655 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002656 return m;
2657}
2658
Jack Jansen9c96a921995-02-15 22:57:06 +00002659#ifdef macintosh
Guido van Rossum79f25d91997-04-29 20:08:16 +00002660static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002661imp_load_resource(PyObject *self, PyObject *args)
Jack Jansen9c96a921995-02-15 22:57:06 +00002662{
2663 char *name;
2664 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002665 PyObject *m;
Jack Jansen9c96a921995-02-15 22:57:06 +00002666
Guido van Rossum43713e52000-02-29 13:59:29 +00002667 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
Jack Jansen9c96a921995-02-15 22:57:06 +00002668 return NULL;
2669 m = PyMac_LoadResourceModule(name, pathname);
2670 return m;
2671}
2672#endif /* macintosh */
2673
Guido van Rossum79f25d91997-04-29 20:08:16 +00002674static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002675imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002676{
2677 char *name;
2678 PyObject *fob;
2679 char *pathname;
2680 char *suffix; /* Unused */
2681 char *mode;
2682 int type;
2683 FILE *fp;
2684
Guido van Rossum43713e52000-02-29 13:59:29 +00002685 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002686 &name, &fob, &pathname,
2687 &suffix, &mode, &type))
2688 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002689 if (*mode) {
2690 /* Mode must start with 'r' or 'U' and must not contain '+'.
2691 Implicit in this test is the assumption that the mode
2692 may contain other modifiers like 'b' or 't'. */
2693
2694 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002695 PyErr_Format(PyExc_ValueError,
2696 "invalid file open mode %.200s", mode);
2697 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002698 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002699 }
2700 if (fob == Py_None)
2701 fp = NULL;
2702 else {
2703 if (!PyFile_Check(fob)) {
2704 PyErr_SetString(PyExc_ValueError,
2705 "load_module arg#2 should be a file or None");
2706 return NULL;
2707 }
2708 fp = get_file(pathname, fob, mode);
2709 if (fp == NULL)
2710 return NULL;
2711 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002712 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002713}
2714
2715static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002716imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002717{
2718 char *name;
2719 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002720 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002721 return NULL;
2722 return load_package(name, pathname);
2723}
2724
2725static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002726imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002727{
2728 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002729 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002730 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002731 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002732}
2733
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002734/* Doc strings */
2735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002736PyDoc_STRVAR(doc_imp,
2737"This module provides the components needed to build your own\n\
2738__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002740PyDoc_STRVAR(doc_find_module,
2741"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002742Search for a module. If path is omitted or None, search for a\n\
2743built-in, frozen or special module and continue search in sys.path.\n\
2744The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002745package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002747PyDoc_STRVAR(doc_load_module,
2748"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002749Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002750The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002752PyDoc_STRVAR(doc_get_magic,
2753"get_magic() -> string\n\
2754Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002756PyDoc_STRVAR(doc_get_suffixes,
2757"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002758Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002759that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002761PyDoc_STRVAR(doc_new_module,
2762"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002763Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002764The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002766PyDoc_STRVAR(doc_lock_held,
2767"lock_held() -> 0 or 1\n\
Tim Peters69232342001-08-30 05:16:13 +00002768Return 1 if the import lock is currently held.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002769On platforms without threads, return 0.");
Tim Peters69232342001-08-30 05:16:13 +00002770
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002771PyDoc_STRVAR(doc_acquire_lock,
2772"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002773Acquires the interpreter's import lock for the current thread.\n\
2774This lock should be used by import hooks to ensure thread-safety\n\
2775when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002776On platforms without threads, this function does nothing.");
2777
2778PyDoc_STRVAR(doc_release_lock,
2779"release_lock() -> None\n\
2780Release the interpreter's import lock.\n\
2781On platforms without threads, this function does nothing.");
2782
Guido van Rossum79f25d91997-04-29 20:08:16 +00002783static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002784 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2785 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2786 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2787 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2788 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2789 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2790 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2791 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002792 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002793 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2794 {"init_builtin", imp_init_builtin, METH_VARARGS},
2795 {"init_frozen", imp_init_frozen, METH_VARARGS},
2796 {"is_builtin", imp_is_builtin, METH_VARARGS},
2797 {"is_frozen", imp_is_frozen, METH_VARARGS},
2798 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002799#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002800 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002801#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002802 {"load_package", imp_load_package, METH_VARARGS},
Jack Jansen9c96a921995-02-15 22:57:06 +00002803#ifdef macintosh
Neal Norwitz031829d2002-03-31 14:37:44 +00002804 {"load_resource", imp_load_resource, METH_VARARGS},
Jack Jansen9c96a921995-02-15 22:57:06 +00002805#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002806 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002807 {NULL, NULL} /* sentinel */
2808};
2809
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002810static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002811setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002812{
2813 PyObject *v;
2814 int err;
2815
2816 v = PyInt_FromLong((long)value);
2817 err = PyDict_SetItemString(d, name, v);
2818 Py_XDECREF(v);
2819 return err;
2820}
2821
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002822void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002823initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002824{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002825 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002826
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002827 m = Py_InitModule4("imp", imp_methods, doc_imp,
2828 NULL, PYTHON_API_VERSION);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002829 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002830
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002831 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2832 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2833 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2834 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2835 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2836 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2837 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2838 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002839 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00002840 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002841
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002842 failure:
2843 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002844}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002845
2846
Guido van Rossumb18618d2000-05-03 23:44:39 +00002847/* API for embedding applications that want to add their own entries
2848 to the table of built-in modules. This should normally be called
2849 *before* Py_Initialize(). When the table resize fails, -1 is
2850 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002851
2852 After a similar function by Just van Rossum. */
2853
2854int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002855PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002856{
2857 static struct _inittab *our_copy = NULL;
2858 struct _inittab *p;
2859 int i, n;
2860
2861 /* Count the number of entries in both tables */
2862 for (n = 0; newtab[n].name != NULL; n++)
2863 ;
2864 if (n == 0)
2865 return 0; /* Nothing to do */
2866 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2867 ;
2868
2869 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002870 p = our_copy;
2871 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002872 if (p == NULL)
2873 return -1;
2874
2875 /* Copy the tables into the new memory */
2876 if (our_copy != PyImport_Inittab)
2877 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2878 PyImport_Inittab = our_copy = p;
2879 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2880
2881 return 0;
2882}
2883
2884/* Shorthand to add a single entry given a name and a function */
2885
2886int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002887PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002888{
2889 struct _inittab newtab[2];
2890
2891 memset(newtab, '\0', sizeof newtab);
2892
2893 newtab[0].name = name;
2894 newtab[0].initfunc = initfunc;
2895
2896 return PyImport_ExtendInittab(newtab);
2897}