blob: d921d74405343e083367a918e658be26cc39be2c [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
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000156_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000157{
158 Py_XDECREF(extensions);
159 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000160 PyMem_DEL(_PyImport_Filetab);
161 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000162}
163
164
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000165/* Locking primitives to prevent parallel imports of the same module
166 in different threads to return with a partially loaded module.
167 These calls are serialized by the global interpreter lock. */
168
169#ifdef WITH_THREAD
170
Guido van Rossum49b56061998-10-01 20:42:43 +0000171#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000172
Guido van Rossum65d5b571998-12-21 19:32:43 +0000173static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000174static long import_lock_thread = -1;
175static int import_lock_level = 0;
176
177static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000178lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000179{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000180 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000181 if (me == -1)
182 return; /* Too bad */
183 if (import_lock == NULL)
Guido van Rossum65d5b571998-12-21 19:32:43 +0000184 import_lock = PyThread_allocate_lock();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000185 if (import_lock_thread == me) {
186 import_lock_level++;
187 return;
188 }
Guido van Rossum65d5b571998-12-21 19:32:43 +0000189 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000190 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000191 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000192 PyEval_RestoreThread(tstate);
193 }
194 import_lock_thread = me;
195 import_lock_level = 1;
196}
197
198static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000199unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000200{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000201 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000202 if (me == -1)
203 return; /* Too bad */
204 if (import_lock_thread != me)
205 Py_FatalError("unlock_import: not holding the import lock");
206 import_lock_level--;
207 if (import_lock_level == 0) {
208 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000209 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000210 }
211}
212
213#else
214
215#define lock_import()
216#define unlock_import()
217
218#endif
219
Tim Peters69232342001-08-30 05:16:13 +0000220static PyObject *
221imp_lock_held(PyObject *self, PyObject *args)
222{
223 if (!PyArg_ParseTuple(args, ":lock_held"))
224 return NULL;
225#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000226 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000227#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000228 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000229#endif
230}
231
Guido van Rossum25ce5661997-08-02 03:10:38 +0000232/* Helper for sys */
233
234PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000235PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000236{
237 PyInterpreterState *interp = PyThreadState_Get()->interp;
238 if (interp->modules == NULL)
239 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
240 return interp->modules;
241}
242
Guido van Rossum3f5da241990-12-20 15:06:42 +0000243
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000244/* List of names to clear in sys */
245static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000246 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000247 "exc_type", "exc_value", "exc_traceback",
248 "last_type", "last_value", "last_traceback",
249 NULL
250};
251
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000252static char* sys_files[] = {
253 "stdin", "__stdin__",
254 "stdout", "__stdout__",
255 "stderr", "__stderr__",
256 NULL
257};
258
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000259
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000260/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000261
Guido van Rossum3f5da241990-12-20 15:06:42 +0000262void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000263PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000264{
Guido van Rossum758eec01998-01-19 21:58:26 +0000265 int pos, ndone;
266 char *name;
267 PyObject *key, *value, *dict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268 PyInterpreterState *interp = PyThreadState_Get()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000269 PyObject *modules = interp->modules;
270
271 if (modules == NULL)
272 return; /* Already done */
273
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000274 /* Delete some special variables first. These are common
275 places where user values hide and people complain when their
276 destructors fail. Since the modules containing them are
277 deleted *last* of all, they would come too late in the normal
278 destruction order. Sigh. */
279
280 value = PyDict_GetItemString(modules, "__builtin__");
281 if (value != NULL && PyModule_Check(value)) {
282 dict = PyModule_GetDict(value);
283 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000284 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000285 PyDict_SetItemString(dict, "_", Py_None);
286 }
287 value = PyDict_GetItemString(modules, "sys");
288 if (value != NULL && PyModule_Check(value)) {
289 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000290 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000291 dict = PyModule_GetDict(value);
292 for (p = sys_deletes; *p != NULL; p++) {
293 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000294 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000295 PyDict_SetItemString(dict, *p, Py_None);
296 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000297 for (p = sys_files; *p != NULL; p+=2) {
298 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000299 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000300 v = PyDict_GetItemString(dict, *(p+1));
301 if (v == NULL)
302 v = Py_None;
303 PyDict_SetItemString(dict, *p, v);
304 }
305 }
306
307 /* First, delete __main__ */
308 value = PyDict_GetItemString(modules, "__main__");
309 if (value != NULL && PyModule_Check(value)) {
310 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000311 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000312 _PyModule_Clear(value);
313 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000314 }
315
Guido van Rossum758eec01998-01-19 21:58:26 +0000316 /* The special treatment of __builtin__ here is because even
317 when it's not referenced as a module, its dictionary is
318 referenced by almost every module's __builtins__. Since
319 deleting a module clears its dictionary (even if there are
320 references left to it), we need to delete the __builtin__
321 module last. Likewise, we don't delete sys until the very
322 end because it is implicitly referenced (e.g. by print).
323
324 Also note that we 'delete' modules by replacing their entry
325 in the modules dict with None, rather than really deleting
326 them; this avoids a rehash of the modules dictionary and
327 also marks them as "non existent" so they won't be
328 re-imported. */
329
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000330 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000331 one (skipping __builtin__ and sys) and delete them */
332 do {
333 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000334 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000335 while (PyDict_Next(modules, &pos, &key, &value)) {
336 if (value->ob_refcnt != 1)
337 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000338 if (PyString_Check(key) && PyModule_Check(value)) {
339 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000340 if (strcmp(name, "__builtin__") == 0)
341 continue;
342 if (strcmp(name, "sys") == 0)
343 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000344 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000345 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000346 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000347 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000348 PyDict_SetItem(modules, key, Py_None);
349 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000350 }
351 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000352 } while (ndone > 0);
353
Guido van Rossum758eec01998-01-19 21:58:26 +0000354 /* Next, delete all modules (still skipping __builtin__ and sys) */
355 pos = 0;
356 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000357 if (PyString_Check(key) && PyModule_Check(value)) {
358 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000359 if (strcmp(name, "__builtin__") == 0)
360 continue;
361 if (strcmp(name, "sys") == 0)
362 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000363 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000364 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000365 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000366 PyDict_SetItem(modules, key, Py_None);
367 }
368 }
369
370 /* Next, delete sys and __builtin__ (in that order) */
371 value = PyDict_GetItemString(modules, "sys");
372 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000373 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000374 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000375 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000376 PyDict_SetItemString(modules, "sys", Py_None);
377 }
378 value = PyDict_GetItemString(modules, "__builtin__");
379 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000380 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000381 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000382 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000383 PyDict_SetItemString(modules, "__builtin__", Py_None);
384 }
385
386 /* Finally, clear and delete the modules directory */
387 PyDict_Clear(modules);
388 interp->modules = NULL;
389 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000390}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000391
392
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000393/* Helper for pythonrun.c -- return magic number */
394
395long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000396PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000397{
Guido van Rossum96774c12000-05-01 20:19:08 +0000398 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000399}
400
401
Guido van Rossum25ce5661997-08-02 03:10:38 +0000402/* Magic for extension modules (built-in as well as dynamically
403 loaded). To prevent initializing an extension module more than
404 once, we keep a static dictionary 'extensions' keyed by module name
405 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000406 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000407 dictionary is stored by calling _PyImport_FixupExtension()
408 immediately after the module initialization function succeeds. A
409 copy can be retrieved from there by calling
410 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000411
Guido van Rossum79f25d91997-04-29 20:08:16 +0000412PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000413_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000414{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000415 PyObject *modules, *mod, *dict, *copy;
416 if (extensions == NULL) {
417 extensions = PyDict_New();
418 if (extensions == NULL)
419 return NULL;
420 }
421 modules = PyImport_GetModuleDict();
422 mod = PyDict_GetItemString(modules, name);
423 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000424 PyErr_Format(PyExc_SystemError,
425 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000426 return NULL;
427 }
428 dict = PyModule_GetDict(mod);
429 if (dict == NULL)
430 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000431 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000432 if (copy == NULL)
433 return NULL;
434 PyDict_SetItemString(extensions, filename, copy);
435 Py_DECREF(copy);
436 return copy;
437}
438
439PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000440_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000441{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000442 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000443 if (extensions == NULL)
444 return NULL;
445 dict = PyDict_GetItemString(extensions, filename);
446 if (dict == NULL)
447 return NULL;
448 mod = PyImport_AddModule(name);
449 if (mod == NULL)
450 return NULL;
451 mdict = PyModule_GetDict(mod);
452 if (mdict == NULL)
453 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000454 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000455 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000456 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000457 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000458 name, filename);
459 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000460}
461
462
463/* Get the module object corresponding to a module name.
464 First check the modules dictionary if there's one there,
465 if not, create a new one and insert in in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000466 Because the former action is most common, THIS DOES NOT RETURN A
467 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000468
Guido van Rossum79f25d91997-04-29 20:08:16 +0000469PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000470PyImport_AddModule(char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000471{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000472 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000473 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000474
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000476 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000477 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000478 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000479 if (m == NULL)
480 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000482 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000483 return NULL;
484 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000485 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000486
487 return m;
488}
489
490
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000491/* Execute a code object in a module and return the module object
492 WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000493
Guido van Rossum79f25d91997-04-29 20:08:16 +0000494PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000495PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000496{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000497 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
498}
499
500PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000501PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000502{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000503 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000504 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000505
Guido van Rossum79f25d91997-04-29 20:08:16 +0000506 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000507 if (m == NULL)
508 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000509 d = PyModule_GetDict(m);
510 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
511 if (PyDict_SetItemString(d, "__builtins__",
512 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000513 return NULL;
514 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000515 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000516 v = NULL;
517 if (pathname != NULL) {
518 v = PyString_FromString(pathname);
519 if (v == NULL)
520 PyErr_Clear();
521 }
522 if (v == NULL) {
523 v = ((PyCodeObject *)co)->co_filename;
524 Py_INCREF(v);
525 }
526 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000527 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000528 Py_DECREF(v);
529
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000530 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000531 if (v == NULL)
532 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000533 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000534
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000536 PyErr_Format(PyExc_ImportError,
537 "Loaded module %.200s not found in sys.modules",
538 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000539 return NULL;
540 }
541
Guido van Rossum79f25d91997-04-29 20:08:16 +0000542 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000543
544 return m;
545}
546
547
548/* Given a pathname for a Python source file, fill a buffer with the
549 pathname for the corresponding compiled file. Return the pathname
550 for the compiled file, or NULL if there's no space in the buffer.
551 Doesn't set an exception. */
552
553static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000554make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000555{
Tim Petersc1731372001-08-04 08:12:36 +0000556 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000557 if (len+2 > buflen)
558 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000559
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000560#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000561 /* Treat .pyw as if it were .py. The case of ".pyw" must match
562 that used in _PyImport_StandardFiletab. */
563 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
564 --len; /* pretend 'w' isn't there */
565#endif
566 memcpy(buf, pathname, len);
567 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
568 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000569
570 return buf;
571}
572
573
574/* Given a pathname for a Python source file, its time of last
575 modification, and a pathname for a compiled file, check whether the
576 compiled file represents the same version of the source. If so,
577 return a FILE pointer for the compiled file, positioned just after
578 the header; if not, return NULL.
579 Doesn't set an exception. */
580
581static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000582check_compiled_module(char *pathname, long mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000583{
584 FILE *fp;
585 long magic;
586 long pyc_mtime;
587
588 fp = fopen(cpathname, "rb");
589 if (fp == NULL)
590 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000591 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000592 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000593 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000594 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000595 fclose(fp);
596 return NULL;
597 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000598 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000599 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000600 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000601 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000602 fclose(fp);
603 return NULL;
604 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000605 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000606 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000607 return fp;
608}
609
610
611/* Read a code object from a file and check it for validity */
612
Guido van Rossum79f25d91997-04-29 20:08:16 +0000613static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000614read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000615{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000617
Tim Petersd9b9ac82001-01-28 00:27:39 +0000618 co = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000619 /* Ugly: rd_object() may return NULL with or without error */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000620 if (co == NULL || !PyCode_Check(co)) {
621 if (!PyErr_Occurred())
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000622 PyErr_Format(PyExc_ImportError,
623 "Non-code object in %.200s", cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000624 Py_XDECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000625 return NULL;
626 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000627 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000628}
629
630
631/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000632 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000633
Guido van Rossum79f25d91997-04-29 20:08:16 +0000634static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000635load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000636{
637 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000638 PyCodeObject *co;
639 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000640
Guido van Rossum79f25d91997-04-29 20:08:16 +0000641 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000642 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000643 PyErr_Format(PyExc_ImportError,
644 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000645 return NULL;
646 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000647 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000648 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000649 if (co == NULL)
650 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000651 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000652 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000653 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000654 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656
657 return m;
658}
659
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000660/* Parse a source file and return the corresponding code object */
661
Guido van Rossum79f25d91997-04-29 20:08:16 +0000662static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000663parse_source_module(char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000664{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000665 PyCodeObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000666 node *n;
667
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000668 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000669 if (n == NULL)
670 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000671 co = PyNode_Compile(n, pathname);
672 PyNode_Free(n);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000673
674 return co;
675}
676
677
Guido van Rossum55a83382000-09-20 20:31:38 +0000678/* Helper to open a bytecode file for writing in exclusive mode */
679
680static FILE *
681open_exclusive(char *filename)
682{
683#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
684 /* Use O_EXCL to avoid a race condition when another process tries to
685 write the same file. When that happens, our open() call fails,
686 which is just fine (since it's only a cache).
687 XXX If the file exists and is writable but the directory is not
688 writable, the file will never be written. Oh well.
689 */
690 int fd;
691 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000692 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
693#ifdef O_BINARY
694 |O_BINARY /* necessary for Windows */
695#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000696#ifdef __VMS
697 , 0666, "ctxt=bin", "shr=nil");
698#else
699 , 0666);
700#endif
Guido van Rossum55a83382000-09-20 20:31:38 +0000701 if (fd < 0)
702 return NULL;
703 return fdopen(fd, "wb");
704#else
705 /* Best we can do -- on Windows this can't happen anyway */
706 return fopen(filename, "wb");
707#endif
708}
709
710
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000711/* Write a compiled module to a file, placing the time of last
712 modification of its source into the header.
713 Errors are ignored, if a write error occurs an attempt is made to
714 remove the file. */
715
716static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000717write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718{
719 FILE *fp;
720
Guido van Rossum55a83382000-09-20 20:31:38 +0000721 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000722 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000723 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000724 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000725 "# can't create %s\n", cpathname);
726 return;
727 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000728 PyMarshal_WriteLongToFile(pyc_magic, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000729 /* First write a 0 for mtime */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000730 PyMarshal_WriteLongToFile(0L, fp);
731 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000732 if (ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000733 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000734 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735 /* Don't keep partial file */
736 fclose(fp);
737 (void) unlink(cpathname);
738 return;
739 }
740 /* Now write the true mtime */
741 fseek(fp, 4L, 0);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000742 PyMarshal_WriteLongToFile(mtime, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743 fflush(fp);
744 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000745 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000746 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747#ifdef macintosh
Jack Jansencbf630f2000-07-11 21:59:16 +0000748 PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000749#endif
750}
751
752
753/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000754 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
755 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000756
Guido van Rossum79f25d91997-04-29 20:08:16 +0000757static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000758load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759{
Fred Drake4c82b232000-06-30 16:18:57 +0000760 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000761 FILE *fpc;
762 char buf[MAXPATHLEN+1];
763 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000764 PyCodeObject *co;
765 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000766
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000767 mtime = PyOS_GetLastModificationTime(pathname, fp);
Fred Drakec63d3e92001-03-01 06:33:32 +0000768 if (mtime == (time_t)(-1))
Fred Drake4c82b232000-06-30 16:18:57 +0000769 return NULL;
770#if SIZEOF_TIME_T > 4
771 /* Python's .pyc timestamp handling presumes that the timestamp fits
772 in 4 bytes. This will be fine until sometime in the year 2038,
773 when a 4-byte signed time_t will overflow.
774 */
775 if (mtime >> 32) {
776 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000777 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000778 return NULL;
779 }
780#endif
Tim Peters36515e22001-11-18 04:06:29 +0000781 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000782 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783 if (cpathname != NULL &&
784 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000785 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000786 fclose(fpc);
787 if (co == NULL)
788 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000789 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000790 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000791 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000792 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793 }
794 else {
795 co = parse_source_module(pathname, fp);
796 if (co == NULL)
797 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000798 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000799 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000800 name, pathname);
801 write_compiled_module(co, cpathname, mtime);
802 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000803 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000804 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000805
806 return m;
807}
808
809
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000810/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000811static PyObject *load_module(char *, FILE *, char *, int);
812static struct filedescr *find_module(char *, PyObject *,
813 char *, size_t, FILE **);
814static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000815
816/* Load a package and return its module object WITH INCREMENTED
817 REFERENCE COUNT */
818
819static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000820load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000821{
822 PyObject *m, *d, *file, *path;
823 int err;
824 char buf[MAXPATHLEN+1];
825 FILE *fp = NULL;
826 struct filedescr *fdp;
827
828 m = PyImport_AddModule(name);
829 if (m == NULL)
830 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000831 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000832 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000833 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000834 d = PyModule_GetDict(m);
835 file = PyString_FromString(pathname);
836 if (file == NULL)
837 return NULL;
838 path = Py_BuildValue("[O]", file);
839 if (path == NULL) {
840 Py_DECREF(file);
841 return NULL;
842 }
843 err = PyDict_SetItemString(d, "__file__", file);
844 if (err == 0)
845 err = PyDict_SetItemString(d, "__path__", path);
846 if (err != 0) {
847 m = NULL;
848 goto cleanup;
849 }
850 buf[0] = '\0';
851 fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
852 if (fdp == NULL) {
853 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
854 PyErr_Clear();
855 }
856 else
857 m = NULL;
858 goto cleanup;
859 }
860 m = load_module(name, fp, buf, fdp->type);
861 if (fp != NULL)
862 fclose(fp);
863 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000864 Py_XDECREF(path);
865 Py_XDECREF(file);
866 return m;
867}
868
869
870/* Helper to test for built-in module */
871
872static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000873is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000874{
875 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +0000876 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
877 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
878 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000879 return -1;
880 else
881 return 1;
882 }
883 }
884 return 0;
885}
886
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000887
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000888/* Search the path (default sys.path) for a module. Return the
889 corresponding filedescr struct, and (via return arguments) the
890 pathname and an open file. Return NULL if the module is not found. */
891
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000892#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +0000893extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
894 char *, int);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000895#endif
896
Tim Peters50d8d372001-02-28 05:34:27 +0000897static int case_ok(char *, int, int, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000898static int find_init_module(char *); /* Forward */
Guido van Rossum197346f1997-10-31 18:38:52 +0000899
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000900static struct filedescr *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000901find_module(char *realname, PyObject *path, char *buf, size_t buflen,
902 FILE **p_fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000903{
Fred Drake4c82b232000-06-30 16:18:57 +0000904 int i, npath;
905 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +0000906 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +0000907 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000908 FILE *fp = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000909#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000910 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000911#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +0000912 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
913 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
914 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +0000915 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +0000916#if defined(PYOS_OS2)
917 size_t saved_len;
918 size_t saved_namelen;
919 char *saved_buf = NULL;
920#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000921
Fred Drake4c82b232000-06-30 16:18:57 +0000922 if (strlen(realname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +0000923 PyErr_SetString(PyExc_OverflowError,
924 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +0000925 return NULL;
926 }
Guido van Rossum0506a431998-08-11 15:07:39 +0000927 strcpy(name, realname);
928
929 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +0000930 /* The only type of submodule allowed inside a "frozen"
931 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +0000932 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
933 PyErr_SetString(PyExc_ImportError,
934 "full frozen module name too long");
935 return NULL;
936 }
937 strcpy(buf, PyString_AsString(path));
938 strcat(buf, ".");
939 strcat(buf, name);
940 strcpy(name, buf);
Jack Jansen550fdae2001-10-30 13:08:39 +0000941#ifdef macintosh
942 /* Freezing on the mac works different, and the modules are
943 ** actually on sys.path. So we don't take the quick exit but
944 ** continue with the normal flow.
945 */
946 path = NULL;
947#else
Guido van Rossum8f4d3312001-10-18 18:54:11 +0000948 if (find_frozen(name) != NULL) {
949 strcpy(buf, name);
950 return &fd_frozen;
951 }
952 PyErr_Format(PyExc_ImportError,
953 "No frozen submodule named %.200s", name);
954 return NULL;
Jack Jansen550fdae2001-10-30 13:08:39 +0000955#endif
Guido van Rossum0506a431998-08-11 15:07:39 +0000956 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000957 if (path == NULL) {
958 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +0000959 strcpy(buf, name);
960 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000961 }
Greg Ward201baee2001-10-04 14:52:06 +0000962 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +0000963 strcpy(buf, name);
964 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000965 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000966
Guido van Rossumac279101996-08-22 23:10:58 +0000967#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000968 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
969 if (fp != NULL) {
970 *p_fp = fp;
971 return fdp;
972 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +0000973#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +0000974 path = PySys_GetObject("path");
975 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000976 if (path == NULL || !PyList_Check(path)) {
977 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +0000978 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000979 return NULL;
980 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000981 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000982 namelen = strlen(name);
983 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +0000984 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000985 PyObject *v = PyList_GetItem(path, i);
Walter Dörwald3430d702002-06-17 10:43:59 +0000986#ifdef Py_USING_UNICODE
987 if (PyUnicode_Check(v)) {
988 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
989 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
990 if (copy == NULL)
991 return NULL;
992 v = copy;
993 }
994 else
995#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +0000996 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000997 continue;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000998 len = PyString_Size(v);
Walter Dörwald3430d702002-06-17 10:43:59 +0000999 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1000 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001001 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001002 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001003 strcpy(buf, PyString_AsString(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001004 if (strlen(buf) != len) {
1005 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001006 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001007 }
Jack Jansen9c96a921995-02-15 22:57:06 +00001008#ifdef macintosh
Tim Peters50d8d372001-02-28 05:34:27 +00001009 /*
Guido van Rossum741689d1997-08-12 14:53:39 +00001010 ** Speedup: each sys.path item is interned, and
1011 ** FindResourceModule remembers which items refer to
1012 ** folders (so we don't have to bother trying to look
Tim Peters50d8d372001-02-28 05:34:27 +00001013 ** into them for resources).
Guido van Rossum741689d1997-08-12 14:53:39 +00001014 */
1015 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
1016 v = PyList_GET_ITEM(path, i);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001018 static struct filedescr resfiledescr =
1019 {"", "", PY_RESOURCE};
Tim Peters50d8d372001-02-28 05:34:27 +00001020
Walter Dörwald3430d702002-06-17 10:43:59 +00001021 Py_XDECREF(copy);
Jack Jansen9c96a921995-02-15 22:57:06 +00001022 return &resfiledescr;
1023 }
Guido van Rossum0f84a341998-08-06 13:36:01 +00001024 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
1025 static struct filedescr resfiledescr =
1026 {"", "", PY_CODERESOURCE};
Tim Peters50d8d372001-02-28 05:34:27 +00001027
Walter Dörwald3430d702002-06-17 10:43:59 +00001028 Py_XDECREF(copy);
Guido van Rossum0f84a341998-08-06 13:36:01 +00001029 return &resfiledescr;
1030 }
Jack Jansen9c96a921995-02-15 22:57:06 +00001031#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001032 if (len > 0 && buf[len-1] != SEP
1033#ifdef ALTSEP
1034 && buf[len-1] != ALTSEP
1035#endif
1036 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001037 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001038 strcpy(buf+len, name);
1039 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001040
1041 /* Check for package import (buf holds a directory name,
1042 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001043#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001044 if (stat(buf, &statbuf) == 0 && /* it exists */
1045 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1046 find_init_module(buf) && /* it has __init__.py */
1047 case_ok(buf, len, namelen, name)) { /* and case matches */
1048 Py_XDECREF(copy);
Tim Peterscab3f682001-04-29 22:21:25 +00001049 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001050 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001051#else
1052 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001053#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001054 if (isdir(buf) &&
1055 find_init_module(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001056 case_ok(buf, len, namelen, name)) {
1057 Py_XDECREF(copy);
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001058 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001059 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001060#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001061#endif
Guido van Rossum9a61dc91997-10-08 15:25:08 +00001062#ifdef macintosh
1063 fdp = PyMac_FindModuleExtension(buf, &len, name);
Jack Jansen4df3c522001-03-20 23:09:54 +00001064 if (fdp) {
Guido van Rossum9a61dc91997-10-08 15:25:08 +00001065#else
Andrew MacIntyred9400542002-02-26 11:41:34 +00001066#if defined(PYOS_OS2)
1067 /* take a snapshot of the module spec for restoration
1068 * after the 8 character DLL hackery
1069 */
1070 saved_buf = strdup(buf);
1071 saved_len = len;
1072 saved_namelen = namelen;
1073#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001074 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001075#if defined(PYOS_OS2)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001076 /* OS/2 limits DLLs to 8 character names (w/o
1077 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001078 * so if the name is longer than that and its a
1079 * dynamically loaded module we're going to try,
1080 * truncate the name before trying
1081 */
1082 if (strlen(realname) > 8) {
1083 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001084 const struct filedescr *scan;
1085 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001086 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001087 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001088 break;
1089 else
1090 scan++;
1091 }
1092 if (scan->suffix != NULL) {
1093 /* yes, so truncate the name */
1094 namelen = 8;
1095 len -= strlen(realname) - namelen;
1096 buf[len] = '\0';
1097 }
1098 }
1099#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001101 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001102 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansen4df3c522001-03-20 23:09:54 +00001103#endif /* !macintosh */
Jack Jansenc88da1f2002-05-28 10:58:19 +00001104 filemode = fdp->mode;
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001105 if (filemode[0] == 'U')
1106 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001107 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001108 if (fp != NULL) {
1109 if (case_ok(buf, len, namelen, name))
1110 break;
1111 else { /* continue search */
1112 fclose(fp);
1113 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001114 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001115 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001116#if defined(PYOS_OS2)
1117 /* restore the saved snapshot */
1118 strcpy(buf, saved_buf);
1119 len = saved_len;
1120 namelen = saved_namelen;
1121#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001122 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001123#if defined(PYOS_OS2)
1124 /* don't need/want the module name snapshot anymore */
1125 if (saved_buf)
1126 {
1127 free(saved_buf);
1128 saved_buf = NULL;
1129 }
1130#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001131 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001132 if (fp != NULL)
1133 break;
1134 }
1135 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001136 PyErr_Format(PyExc_ImportError,
1137 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001138 return NULL;
1139 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001140 *p_fp = fp;
1141 return fdp;
1142}
1143
Tim Petersd1e87a82001-03-01 18:12:00 +00001144/* case_ok(char* buf, int len, int namelen, char* name)
1145 * The arguments here are tricky, best shown by example:
1146 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1147 * ^ ^ ^ ^
1148 * |--------------------- buf ---------------------|
1149 * |------------------- len ------------------|
1150 * |------ name -------|
1151 * |----- namelen -----|
1152 * buf is the full path, but len only counts up to (& exclusive of) the
1153 * extension. name is the module name, also exclusive of extension.
1154 *
1155 * We've already done a successful stat() or fopen() on buf, so know that
1156 * there's some match, possibly case-insensitive.
1157 *
Tim Peters50d8d372001-02-28 05:34:27 +00001158 * case_ok() is to return 1 if there's a case-sensitive match for
1159 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1160 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001161 *
Tim Peters50d8d372001-02-28 05:34:27 +00001162 * case_ok() is used to implement case-sensitive import semantics even
1163 * on platforms with case-insensitive filesystems. It's trivial to implement
1164 * for case-sensitive filesystems. It's pretty much a cross-platform
1165 * nightmare for systems with case-insensitive filesystems.
1166 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001167
Tim Peters50d8d372001-02-28 05:34:27 +00001168/* First we may need a pile of platform-specific header files; the sequence
1169 * of #if's here should match the sequence in the body of case_ok().
1170 */
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001171#if defined(MS_WINDOWS) || defined(__CYGWIN__)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001172#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001173#ifdef __CYGWIN__
1174#include <sys/cygwin.h>
1175#endif
1176
Tim Peters50d8d372001-02-28 05:34:27 +00001177#elif defined(DJGPP)
1178#include <dir.h>
1179
1180#elif defined(macintosh)
1181#include <TextUtils.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001182
Tim Petersd1e87a82001-03-01 18:12:00 +00001183#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001184#include <sys/types.h>
1185#include <dirent.h>
1186
Andrew MacIntyred9400542002-02-26 11:41:34 +00001187#elif defined(PYOS_OS2)
1188#define INCL_DOS
1189#define INCL_DOSERRORS
1190#define INCL_NOPMAPI
1191#include <os2.h>
1192
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001193#elif defined(RISCOS)
1194#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001195#endif
1196
Guido van Rossum0980bd91998-02-13 17:18:36 +00001197static int
Tim Peters50d8d372001-02-28 05:34:27 +00001198case_ok(char *buf, int len, int namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001199{
Tim Peters50d8d372001-02-28 05:34:27 +00001200/* Pick a platform-specific implementation; the sequence of #if's here should
1201 * match the sequence just above.
1202 */
1203
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001204/* MS_WINDOWS || __CYGWIN__ */
1205#if defined(MS_WINDOWS) || defined(__CYGWIN__)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001206 WIN32_FIND_DATA data;
1207 HANDLE h;
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001208#ifdef __CYGWIN__
1209 char tempbuf[MAX_PATH];
1210#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001211
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001212 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001213 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001214
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001215#ifdef __CYGWIN__
1216 cygwin32_conv_to_win32_path(buf, tempbuf);
1217 h = FindFirstFile(tempbuf, &data);
1218#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001219 h = FindFirstFile(buf, &data);
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001220#endif
Guido van Rossum0980bd91998-02-13 17:18:36 +00001221 if (h == INVALID_HANDLE_VALUE) {
1222 PyErr_Format(PyExc_NameError,
1223 "Can't find file for module %.100s\n(filename %.300s)",
1224 name, buf);
1225 return 0;
1226 }
1227 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001228 return strncmp(data.cFileName, name, namelen) == 0;
1229
1230/* DJGPP */
1231#elif defined(DJGPP)
1232 struct ffblk ffblk;
1233 int done;
1234
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001235 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001236 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001237
1238 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1239 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001240 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001241 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001242 name, buf);
1243 return 0;
1244 }
Tim Peters50d8d372001-02-28 05:34:27 +00001245 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001246
Tim Peters50d8d372001-02-28 05:34:27 +00001247/* macintosh */
1248#elif defined(macintosh)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001249 FSSpec fss;
1250 OSErr err;
Tim Peters50d8d372001-02-28 05:34:27 +00001251
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001252 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Peters50d8d372001-02-28 05:34:27 +00001253 return 1;
1254
Guido van Rossuma0f0a331998-09-14 13:40:53 +00001255 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
Guido van Rossum0980bd91998-02-13 17:18:36 +00001256 if (err) {
1257 PyErr_Format(PyExc_NameError,
Guido van Rossuma0f0a331998-09-14 13:40:53 +00001258 "Can't find file for module %.100s\n(filename %.300s)",
1259 name, buf);
Guido van Rossum0980bd91998-02-13 17:18:36 +00001260 return 0;
1261 }
Tim Peters50d8d372001-02-28 05:34:27 +00001262 return fss.name[0] >= namelen &&
1263 strncmp(name, (char *)fss.name+1, namelen) == 0;
1264
Tim Peters677898a2001-03-02 03:28:03 +00001265/* new-fangled macintosh (macosx) */
Tim Petersd1e87a82001-03-01 18:12:00 +00001266#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001267 DIR *dirp;
1268 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001269 char dirname[MAXPATHLEN + 1];
1270 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001271
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001272 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001273 return 1;
1274
Tim Petersd1e87a82001-03-01 18:12:00 +00001275 /* Copy the dir component into dirname; substitute "." if empty */
1276 if (dirlen <= 0) {
1277 dirname[0] = '.';
1278 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001279 }
1280 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001281 assert(dirlen <= MAXPATHLEN);
1282 memcpy(dirname, buf, dirlen);
1283 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001284 }
1285 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001286 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001287 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001288 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001289 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001290 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001291#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001292 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001293#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001294 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001295#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001296 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001297 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001298 (void)closedir(dirp);
1299 return 1; /* Found */
1300 }
1301 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001302 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001303 }
Tim Peters430f5d42001-03-01 01:30:56 +00001304 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001305
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001306/* RISC OS */
1307#elif defined(RISCOS)
1308 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1309 char buf2[MAXPATHLEN+2];
1310 char *nameWithExt = buf+len-namelen;
1311 int canonlen;
1312 os_error *e;
1313
1314 if (Py_GETENV("PYTHONCASEOK") != NULL)
1315 return 1;
1316
1317 /* workaround:
1318 append wildcard, otherwise case of filename wouldn't be touched */
1319 strcpy(buf2, buf);
1320 strcat(buf2, "*");
1321
1322 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1323 canonlen = MAXPATHLEN+1-canonlen;
1324 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1325 return 0;
1326 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1327 return 1; /* match */
1328
1329 return 0;
1330
Andrew MacIntyred9400542002-02-26 11:41:34 +00001331/* OS/2 */
1332#elif defined(PYOS_OS2)
1333 HDIR hdir = 1;
1334 ULONG srchcnt = 1;
1335 FILEFINDBUF3 ffbuf;
1336 APIRET rc;
1337
1338 if (getenv("PYTHONCASEOK") != NULL)
1339 return 1;
1340
1341 rc = DosFindFirst(buf,
1342 &hdir,
1343 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1344 &ffbuf, sizeof(ffbuf),
1345 &srchcnt,
1346 FIL_STANDARD);
1347 if (rc != NO_ERROR)
1348 return 0;
1349 return strncmp(ffbuf.achName, name, namelen) == 0;
1350
Tim Peters50d8d372001-02-28 05:34:27 +00001351/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1352#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001353 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001354
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001355#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001356}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001357
Guido van Rossum0980bd91998-02-13 17:18:36 +00001358
Guido van Rossum197346f1997-10-31 18:38:52 +00001359#ifdef HAVE_STAT
1360/* Helper to look for __init__.py or __init__.py[co] in potential package */
1361static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001362find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001363{
Tim Peters0f9431f2001-07-05 03:47:53 +00001364 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001365 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001366 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001367 struct stat statbuf;
1368
Tim Peters0f9431f2001-07-05 03:47:53 +00001369/* For calling case_ok(buf, len, namelen, name):
1370 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1371 * ^ ^ ^ ^
1372 * |--------------------- buf ---------------------|
1373 * |------------------- len ------------------|
1374 * |------ name -------|
1375 * |----- namelen -----|
1376 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001377 if (save_len + 13 >= MAXPATHLEN)
1378 return 0;
1379 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001380 pname = buf + i;
1381 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001382 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001383 if (case_ok(buf,
1384 save_len + 9, /* len("/__init__") */
1385 8, /* len("__init__") */
1386 pname)) {
1387 buf[save_len] = '\0';
1388 return 1;
1389 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001390 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001391 i += strlen(pname);
1392 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001393 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001394 if (case_ok(buf,
1395 save_len + 9, /* len("/__init__") */
1396 8, /* len("__init__") */
1397 pname)) {
1398 buf[save_len] = '\0';
1399 return 1;
1400 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001401 }
1402 buf[save_len] = '\0';
1403 return 0;
1404}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001405
1406#else
1407
1408#ifdef RISCOS
1409static int
1410find_init_module(buf)
1411 char *buf;
1412{
1413 int save_len = strlen(buf);
1414 int i = save_len;
1415
1416 if (save_len + 13 >= MAXPATHLEN)
1417 return 0;
1418 buf[i++] = SEP;
1419 strcpy(buf+i, "__init__/py");
1420 if (isfile(buf)) {
1421 buf[save_len] = '\0';
1422 return 1;
1423 }
1424
1425 if (Py_OptimizeFlag)
1426 strcpy(buf+i, "o");
1427 else
1428 strcpy(buf+i, "c");
1429 if (isfile(buf)) {
1430 buf[save_len] = '\0';
1431 return 1;
1432 }
1433 buf[save_len] = '\0';
1434 return 0;
1435}
1436#endif /*RISCOS*/
1437
Guido van Rossum197346f1997-10-31 18:38:52 +00001438#endif /* HAVE_STAT */
1439
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001440
Tim Petersdbd9ba62000-07-09 03:09:57 +00001441static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001442
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001443/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001444 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001445
Guido van Rossum79f25d91997-04-29 20:08:16 +00001446static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001447load_module(char *name, FILE *fp, char *buf, int type)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001448{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001449 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001450 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001451 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001452
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001453 /* First check that there's an open file (if we need one) */
1454 switch (type) {
1455 case PY_SOURCE:
1456 case PY_COMPILED:
1457 if (fp == NULL) {
1458 PyErr_Format(PyExc_ValueError,
1459 "file object required for import (type code %d)",
1460 type);
1461 return NULL;
1462 }
1463 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001464
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001465 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001466
1467 case PY_SOURCE:
1468 m = load_source_module(name, buf, fp);
1469 break;
1470
1471 case PY_COMPILED:
1472 m = load_compiled_module(name, buf, fp);
1473 break;
1474
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001475#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001476 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001477 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001478 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001479#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001480
Jack Jansen9c96a921995-02-15 22:57:06 +00001481#ifdef macintosh
1482 case PY_RESOURCE:
1483 m = PyMac_LoadResourceModule(name, buf);
1484 break;
Guido van Rossum0f84a341998-08-06 13:36:01 +00001485 case PY_CODERESOURCE:
1486 m = PyMac_LoadCodeResourceModule(name, buf);
1487 break;
Jack Jansen9c96a921995-02-15 22:57:06 +00001488#endif
1489
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001490 case PKG_DIRECTORY:
1491 m = load_package(name, buf);
1492 break;
1493
1494 case C_BUILTIN:
1495 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001496 if (buf != NULL && buf[0] != '\0')
1497 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001498 if (type == C_BUILTIN)
1499 err = init_builtin(name);
1500 else
1501 err = PyImport_ImportFrozenModule(name);
1502 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001503 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001504 if (err == 0) {
1505 PyErr_Format(PyExc_ImportError,
1506 "Purported %s module %.200s not found",
1507 type == C_BUILTIN ?
1508 "builtin" : "frozen",
1509 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001510 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001511 }
1512 modules = PyImport_GetModuleDict();
1513 m = PyDict_GetItemString(modules, name);
1514 if (m == NULL) {
1515 PyErr_Format(
1516 PyExc_ImportError,
1517 "%s module %.200s not properly initialized",
1518 type == C_BUILTIN ?
1519 "builtin" : "frozen",
1520 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001521 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001522 }
1523 Py_INCREF(m);
1524 break;
1525
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001526 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001527 PyErr_Format(PyExc_ImportError,
1528 "Don't know how to import %.200s (type code %d)",
1529 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001530 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001531
1532 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001533
1534 return m;
1535}
1536
1537
1538/* Initialize a built-in module.
1539 Return 1 for succes, 0 if the module is not found, and -1 with
1540 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001541
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001542static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001543init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001544{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001545 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001546
Greg Ward201baee2001-10-04 14:52:06 +00001547 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001548 return 1;
1549
Guido van Rossum771c6c81997-10-31 18:37:24 +00001550 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001551 if (strcmp(name, p->name) == 0) {
1552 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001553 PyErr_Format(PyExc_ImportError,
1554 "Cannot re-init internal module %.200s",
1555 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001556 return -1;
1557 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001558 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001559 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001560 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001561 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001562 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001563 if (_PyImport_FixupExtension(name, name) == NULL)
1564 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001565 return 1;
1566 }
1567 }
1568 return 0;
1569}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001570
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001571
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001572/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001573
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001574static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001575find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001576{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001577 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001578
Guido van Rossum79f25d91997-04-29 20:08:16 +00001579 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001580 if (p->name == NULL)
1581 return NULL;
1582 if (strcmp(p->name, name) == 0)
1583 break;
1584 }
1585 return p;
1586}
1587
Guido van Rossum79f25d91997-04-29 20:08:16 +00001588static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001589get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001590{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001591 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001592 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001593
1594 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001595 PyErr_Format(PyExc_ImportError,
1596 "No such frozen object named %.200s",
1597 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001598 return NULL;
1599 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001600 if (p->code == NULL) {
1601 PyErr_Format(PyExc_ImportError,
1602 "Excluded frozen object named %.200s",
1603 name);
1604 return NULL;
1605 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001606 size = p->size;
1607 if (size < 0)
1608 size = -size;
1609 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001610}
1611
1612/* Initialize a frozen module.
1613 Return 1 for succes, 0 if the module is not found, and -1 with
1614 an exception set if the initialization failed.
1615 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001616
1617int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001618PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001619{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001620 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001621 PyObject *co;
1622 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001623 int ispackage;
1624 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001625
1626 if (p == NULL)
1627 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001628 if (p->code == NULL) {
1629 PyErr_Format(PyExc_ImportError,
1630 "Excluded frozen object named %.200s",
1631 name);
1632 return -1;
1633 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001634 size = p->size;
1635 ispackage = (size < 0);
1636 if (ispackage)
1637 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001638 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001639 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001640 name, ispackage ? " package" : "");
1641 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001642 if (co == NULL)
1643 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001644 if (!PyCode_Check(co)) {
1645 Py_DECREF(co);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001646 PyErr_Format(PyExc_TypeError,
1647 "frozen object %.200s is not a code object",
1648 name);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001649 return -1;
1650 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001651 if (ispackage) {
1652 /* Set __path__ to the package name */
1653 PyObject *d, *s;
1654 int err;
1655 m = PyImport_AddModule(name);
1656 if (m == NULL)
1657 return -1;
1658 d = PyModule_GetDict(m);
1659 s = PyString_InternFromString(name);
1660 if (s == NULL)
1661 return -1;
1662 err = PyDict_SetItemString(d, "__path__", s);
1663 Py_DECREF(s);
1664 if (err != 0)
1665 return err;
1666 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001667 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum79f25d91997-04-29 20:08:16 +00001668 Py_DECREF(co);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001669 if (m == NULL)
1670 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001671 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001672 return 1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001673}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001674
1675
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001676/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001677 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001678
Guido van Rossum79f25d91997-04-29 20:08:16 +00001679PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001680PyImport_ImportModule(char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001681{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001682 PyObject *pname;
1683 PyObject *result;
1684
1685 pname = PyString_FromString(name);
1686 result = PyImport_Import(pname);
1687 Py_DECREF(pname);
1688 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001689}
1690
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001691/* Forward declarations for helper routines */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001692static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1693static PyObject *load_next(PyObject *mod, PyObject *altmod,
1694 char **p_name, char *buf, int *p_buflen);
1695static int mark_miss(char *name);
1696static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1697 char *buf, int buflen, int recursive);
1698static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001699
1700/* The Magnum Opus of dotted-name import :-) */
1701
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001702static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001703import_module_ex(char *name, PyObject *globals, PyObject *locals,
1704 PyObject *fromlist)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001705{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001706 char buf[MAXPATHLEN+1];
1707 int buflen = 0;
1708 PyObject *parent, *head, *next, *tail;
1709
1710 parent = get_parent(globals, buf, &buflen);
1711 if (parent == NULL)
1712 return NULL;
1713
1714 head = load_next(parent, Py_None, &name, buf, &buflen);
1715 if (head == NULL)
1716 return NULL;
1717
1718 tail = head;
1719 Py_INCREF(tail);
1720 while (name) {
1721 next = load_next(tail, tail, &name, buf, &buflen);
1722 Py_DECREF(tail);
1723 if (next == NULL) {
1724 Py_DECREF(head);
1725 return NULL;
1726 }
1727 tail = next;
1728 }
1729
1730 if (fromlist != NULL) {
1731 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1732 fromlist = NULL;
1733 }
1734
1735 if (fromlist == NULL) {
1736 Py_DECREF(tail);
1737 return head;
1738 }
1739
1740 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001741 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001742 Py_DECREF(tail);
1743 return NULL;
1744 }
1745
1746 return tail;
1747}
1748
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001749PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001750PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1751 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001752{
1753 PyObject *result;
1754 lock_import();
Guido van Rossumd65911b1998-03-03 22:33:27 +00001755 result = import_module_ex(name, globals, locals, fromlist);
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001756 unlock_import();
1757 return result;
1758}
1759
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001760static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001761get_parent(PyObject *globals, char *buf, int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001762{
1763 static PyObject *namestr = NULL;
1764 static PyObject *pathstr = NULL;
1765 PyObject *modname, *modpath, *modules, *parent;
1766
1767 if (globals == NULL || !PyDict_Check(globals))
1768 return Py_None;
1769
1770 if (namestr == NULL) {
1771 namestr = PyString_InternFromString("__name__");
1772 if (namestr == NULL)
1773 return NULL;
1774 }
1775 if (pathstr == NULL) {
1776 pathstr = PyString_InternFromString("__path__");
1777 if (pathstr == NULL)
1778 return NULL;
1779 }
1780
1781 *buf = '\0';
1782 *p_buflen = 0;
1783 modname = PyDict_GetItem(globals, namestr);
1784 if (modname == NULL || !PyString_Check(modname))
1785 return Py_None;
1786
1787 modpath = PyDict_GetItem(globals, pathstr);
1788 if (modpath != NULL) {
1789 int len = PyString_GET_SIZE(modname);
1790 if (len > MAXPATHLEN) {
1791 PyErr_SetString(PyExc_ValueError,
1792 "Module name too long");
1793 return NULL;
1794 }
1795 strcpy(buf, PyString_AS_STRING(modname));
1796 *p_buflen = len;
1797 }
1798 else {
1799 char *start = PyString_AS_STRING(modname);
1800 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00001801 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001802 if (lastdot == NULL)
1803 return Py_None;
1804 len = lastdot - start;
1805 if (len >= MAXPATHLEN) {
1806 PyErr_SetString(PyExc_ValueError,
1807 "Module name too long");
1808 return NULL;
1809 }
1810 strncpy(buf, start, len);
1811 buf[len] = '\0';
1812 *p_buflen = len;
1813 }
1814
1815 modules = PyImport_GetModuleDict();
1816 parent = PyDict_GetItemString(modules, buf);
1817 if (parent == NULL)
1818 parent = Py_None;
1819 return parent;
1820 /* We expect, but can't guarantee, if parent != None, that:
1821 - parent.__name__ == buf
1822 - parent.__dict__ is globals
1823 If this is violated... Who cares? */
1824}
1825
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001826/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001827static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001828load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
1829 int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001830{
1831 char *name = *p_name;
1832 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00001833 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001834 char *p;
1835 PyObject *result;
1836
1837 if (dot == NULL) {
1838 *p_name = NULL;
1839 len = strlen(name);
1840 }
1841 else {
1842 *p_name = dot+1;
1843 len = dot-name;
1844 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00001845 if (len == 0) {
1846 PyErr_SetString(PyExc_ValueError,
1847 "Empty module name");
1848 return NULL;
1849 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001850
1851 p = buf + *p_buflen;
1852 if (p != buf)
1853 *p++ = '.';
1854 if (p+len-buf >= MAXPATHLEN) {
1855 PyErr_SetString(PyExc_ValueError,
1856 "Module name too long");
1857 return NULL;
1858 }
1859 strncpy(p, name, len);
1860 p[len] = '\0';
1861 *p_buflen = p+len-buf;
1862
1863 result = import_submodule(mod, p, buf);
1864 if (result == Py_None && altmod != mod) {
1865 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001866 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00001867 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001868 if (result != NULL && result != Py_None) {
1869 if (mark_miss(buf) != 0) {
1870 Py_DECREF(result);
1871 return NULL;
1872 }
1873 strncpy(buf, name, len);
1874 buf[len] = '\0';
1875 *p_buflen = len;
1876 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001877 }
1878 if (result == NULL)
1879 return NULL;
1880
1881 if (result == Py_None) {
1882 Py_DECREF(result);
1883 PyErr_Format(PyExc_ImportError,
1884 "No module named %.200s", name);
1885 return NULL;
1886 }
1887
1888 return result;
1889}
1890
1891static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001892mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001893{
1894 PyObject *modules = PyImport_GetModuleDict();
1895 return PyDict_SetItemString(modules, name, Py_None);
1896}
1897
1898static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001899ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
1900 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001901{
1902 int i;
1903
1904 if (!PyObject_HasAttrString(mod, "__path__"))
1905 return 1;
1906
1907 for (i = 0; ; i++) {
1908 PyObject *item = PySequence_GetItem(fromlist, i);
1909 int hasit;
1910 if (item == NULL) {
1911 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1912 PyErr_Clear();
1913 return 1;
1914 }
1915 return 0;
1916 }
1917 if (!PyString_Check(item)) {
1918 PyErr_SetString(PyExc_TypeError,
1919 "Item in ``from list'' not a string");
1920 Py_DECREF(item);
1921 return 0;
1922 }
1923 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00001924 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001925 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001926 /* See if the package defines __all__ */
1927 if (recursive)
1928 continue; /* Avoid endless recursion */
1929 all = PyObject_GetAttrString(mod, "__all__");
1930 if (all == NULL)
1931 PyErr_Clear();
1932 else {
1933 if (!ensure_fromlist(mod, all, buf, buflen, 1))
1934 return 0;
1935 Py_DECREF(all);
1936 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001937 continue;
1938 }
1939 hasit = PyObject_HasAttr(mod, item);
1940 if (!hasit) {
1941 char *subname = PyString_AS_STRING(item);
1942 PyObject *submod;
1943 char *p;
1944 if (buflen + strlen(subname) >= MAXPATHLEN) {
1945 PyErr_SetString(PyExc_ValueError,
1946 "Module name too long");
1947 Py_DECREF(item);
1948 return 0;
1949 }
1950 p = buf + buflen;
1951 *p++ = '.';
1952 strcpy(p, subname);
1953 submod = import_submodule(mod, subname, buf);
1954 Py_XDECREF(submod);
1955 if (submod == NULL) {
1956 Py_DECREF(item);
1957 return 0;
1958 }
1959 }
1960 Py_DECREF(item);
1961 }
1962
Guido van Rossuma7f2e811997-10-03 15:33:32 +00001963 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001964}
1965
1966static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001967import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001968{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001969 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossumf48f11c2001-07-23 13:27:49 +00001970 PyObject *m, *res = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00001971
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001972 /* Require:
1973 if mod == None: subname == fullname
1974 else: mod.__name__ + "." + subname == fullname
1975 */
1976
Tim Peters50d8d372001-02-28 05:34:27 +00001977 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001978 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001979 }
1980 else {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001981 PyObject *path;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001982 char buf[MAXPATHLEN+1];
1983 struct filedescr *fdp;
1984 FILE *fp = NULL;
1985
Guido van Rossum9c0afe51998-05-19 15:09:05 +00001986 if (mod == Py_None)
1987 path = NULL;
1988 else {
1989 path = PyObject_GetAttrString(mod, "__path__");
1990 if (path == NULL) {
1991 PyErr_Clear();
1992 Py_INCREF(Py_None);
1993 return Py_None;
1994 }
1995 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001996
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001997 buf[0] = '\0';
Guido van Rossumb68cd421998-07-01 17:36:26 +00001998 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1999 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002000 if (fdp == NULL) {
2001 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2002 return NULL;
2003 PyErr_Clear();
2004 Py_INCREF(Py_None);
2005 return Py_None;
2006 }
2007 m = load_module(fullname, fp, buf, fdp->type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002008 if (fp)
2009 fclose(fp);
Guido van Rossumf48f11c2001-07-23 13:27:49 +00002010 if (mod != Py_None) {
2011 /* Irrespective of the success of this load, make a
2012 reference to it in the parent package module.
2013 A copy gets saved in the modules dictionary
2014 under the full name, so get a reference from
2015 there, if need be. (The exception is when
2016 the load failed with a SyntaxError -- then
2017 there's no trace in sys.modules. In that case,
2018 of course, do nothing extra.) */
2019 res = m;
2020 if (res == NULL)
2021 res = PyDict_GetItemString(modules, fullname);
2022 if (res != NULL &&
2023 PyObject_SetAttrString(mod, subname, res) < 0) {
2024 Py_XDECREF(m);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002025 m = NULL;
2026 }
2027 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002028 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002029
2030 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002031}
2032
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002033
2034/* Re-import a module of any kind and return its module object, WITH
2035 INCREMENTED REFERENCE COUNT */
2036
Guido van Rossum79f25d91997-04-29 20:08:16 +00002037PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002038PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002039{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002040 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum222ef561997-09-06 19:41:09 +00002041 PyObject *path = NULL;
2042 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002043 char buf[MAXPATHLEN+1];
2044 struct filedescr *fdp;
2045 FILE *fp = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002046
Guido van Rossum79f25d91997-04-29 20:08:16 +00002047 if (m == NULL || !PyModule_Check(m)) {
2048 PyErr_SetString(PyExc_TypeError,
2049 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002050 return NULL;
2051 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002052 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002053 if (name == NULL)
2054 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002055 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002056 PyErr_Format(PyExc_ImportError,
2057 "reload(): module %.200s not in sys.modules",
2058 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002059 return NULL;
2060 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002061 subname = strrchr(name, '.');
2062 if (subname == NULL)
2063 subname = name;
2064 else {
2065 PyObject *parentname, *parent;
2066 parentname = PyString_FromStringAndSize(name, (subname-name));
2067 if (parentname == NULL)
2068 return NULL;
2069 parent = PyDict_GetItem(modules, parentname);
Barry Warsaw38793331999-01-27 17:54:20 +00002070 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002071 if (parent == NULL) {
2072 PyErr_Format(PyExc_ImportError,
2073 "reload(): parent %.200s not in sys.modules",
2074 name);
2075 return NULL;
2076 }
2077 subname++;
2078 path = PyObject_GetAttrString(parent, "__path__");
2079 if (path == NULL)
2080 PyErr_Clear();
2081 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002082 buf[0] = '\0';
Guido van Rossum222ef561997-09-06 19:41:09 +00002083 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
2084 Py_XDECREF(path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002085 if (fdp == NULL)
2086 return NULL;
2087 m = load_module(name, fp, buf, fdp->type);
2088 if (fp)
2089 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002090 return m;
2091}
2092
2093
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002094/* Higher-level import emulator which emulates the "import" statement
2095 more accurately -- it invokes the __import__() function from the
2096 builtins of the current globals. This means that the import is
2097 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002098 environment, e.g. by "rexec".
2099 A dummy list ["__doc__"] is passed as the 4th argument so that
2100 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2101 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002102
2103PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002104PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002105{
2106 static PyObject *silly_list = NULL;
2107 static PyObject *builtins_str = NULL;
2108 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002109 PyObject *globals = NULL;
2110 PyObject *import = NULL;
2111 PyObject *builtins = NULL;
2112 PyObject *r = NULL;
2113
2114 /* Initialize constant string objects */
2115 if (silly_list == NULL) {
2116 import_str = PyString_InternFromString("__import__");
2117 if (import_str == NULL)
2118 return NULL;
2119 builtins_str = PyString_InternFromString("__builtins__");
2120 if (builtins_str == NULL)
2121 return NULL;
2122 silly_list = Py_BuildValue("[s]", "__doc__");
2123 if (silly_list == NULL)
2124 return NULL;
2125 }
2126
2127 /* Get the builtins from current globals */
2128 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002129 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002130 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002131 builtins = PyObject_GetItem(globals, builtins_str);
2132 if (builtins == NULL)
2133 goto err;
2134 }
2135 else {
2136 /* No globals -- use standard builtins, and fake globals */
2137 PyErr_Clear();
2138
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002139 builtins = PyImport_ImportModuleEx("__builtin__",
2140 NULL, NULL, NULL);
2141 if (builtins == NULL)
2142 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002143 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2144 if (globals == NULL)
2145 goto err;
2146 }
2147
2148 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002150 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 if (import == NULL)
2152 PyErr_SetObject(PyExc_KeyError, import_str);
2153 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002154 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002155 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002156 if (import == NULL)
2157 goto err;
2158
2159 /* Call the _import__ function with the proper argument list */
2160 r = PyObject_CallFunction(import, "OOOO",
2161 module_name, globals, globals, silly_list);
2162
2163 err:
2164 Py_XDECREF(globals);
2165 Py_XDECREF(builtins);
2166 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002167
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002168 return r;
2169}
2170
2171
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002172/* Module 'imp' provides Python access to the primitives used for
2173 importing modules.
2174*/
2175
Guido van Rossum79f25d91997-04-29 20:08:16 +00002176static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002177imp_get_magic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002178{
2179 char buf[4];
2180
Guido van Rossum43713e52000-02-29 13:59:29 +00002181 if (!PyArg_ParseTuple(args, ":get_magic"))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002182 return NULL;
Guido van Rossum96774c12000-05-01 20:19:08 +00002183 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2184 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2185 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2186 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002187
Guido van Rossum79f25d91997-04-29 20:08:16 +00002188 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002189}
2190
Guido van Rossum79f25d91997-04-29 20:08:16 +00002191static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002192imp_get_suffixes(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002193{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002194 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002195 struct filedescr *fdp;
2196
Guido van Rossum43713e52000-02-29 13:59:29 +00002197 if (!PyArg_ParseTuple(args, ":get_suffixes"))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002198 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002199 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002200 if (list == NULL)
2201 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002202 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2203 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002204 fdp->suffix, fdp->mode, fdp->type);
2205 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002206 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002207 return NULL;
2208 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002209 if (PyList_Append(list, item) < 0) {
2210 Py_DECREF(list);
2211 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002212 return NULL;
2213 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002214 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002215 }
2216 return list;
2217}
2218
Guido van Rossum79f25d91997-04-29 20:08:16 +00002219static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002220call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002221{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002222 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002223 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002224 struct filedescr *fdp;
2225 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002226 FILE *fp = NULL;
2227
2228 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002229 if (path == Py_None)
2230 path = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002231 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
2232 if (fdp == NULL)
2233 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002234 if (fp != NULL) {
2235 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2236 if (fob == NULL) {
2237 fclose(fp);
2238 return NULL;
2239 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002240 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002241 else {
2242 fob = Py_None;
2243 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002244 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002245 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002246 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002247 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002248 return ret;
2249}
2250
Guido van Rossum79f25d91997-04-29 20:08:16 +00002251static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002252imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002253{
2254 char *name;
2255 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002256 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002257 return NULL;
2258 return call_find_module(name, path);
2259}
2260
2261static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002262imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002263{
2264 char *name;
2265 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002266 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002267 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002268 return NULL;
2269 ret = init_builtin(name);
2270 if (ret < 0)
2271 return NULL;
2272 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002273 Py_INCREF(Py_None);
2274 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002275 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002276 m = PyImport_AddModule(name);
2277 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002278 return m;
2279}
2280
Guido van Rossum79f25d91997-04-29 20:08:16 +00002281static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002282imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002283{
2284 char *name;
2285 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002286 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002287 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002288 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002289 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002290 if (ret < 0)
2291 return NULL;
2292 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002293 Py_INCREF(Py_None);
2294 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002295 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002296 m = PyImport_AddModule(name);
2297 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002298 return m;
2299}
2300
Just van Rossum3eb166b2002-11-29 20:47:40 +00002301/* Keep a reference to the tuple used to build PyImport_FrozenModules,
2302 as it points to the raw string data inside the tuple. */
2303static PyObject *frozenmodulestuple = NULL;
2304
2305static PyObject *
2306imp_set_frozenmodules(PyObject *self, PyObject *args)
2307{
2308 PyObject *t, *item, *name, *code, *ispkg;
2309 struct _frozen *frozenmodules;
2310 int n, i;
2311
2312 if (!PyArg_ParseTuple(args, "O:set_frozenmodules", &t))
2313 return NULL;
2314
2315 /* turn the argument into a tuple so we're sure our list
2316 isn't being tampered with behind our backs */
2317 t = PySequence_Tuple(t);
2318 if (t == NULL)
2319 return NULL;
2320
2321 n = PyTuple_Size(t);
2322 frozenmodules = PyMem_Malloc((n + 1)* sizeof(struct _frozen));
2323 if (frozenmodules == NULL) {
2324 PyErr_SetString(PyExc_MemoryError,
2325 "no memory to allocate frozen array");
2326 goto error;
2327 }
2328 for (i = 0; i < n; i++) {
2329 item = PyTuple_GetItem(t, i);
2330 if (item == NULL)
2331 goto error;
2332 if (!PyTuple_Check(item) || PyTuple_Size(item) != 3)
2333 goto typeerror;
2334 name = PyTuple_GetItem(item, 0);
2335 code = PyTuple_GetItem(item, 1);
2336 ispkg = PyTuple_GetItem(item, 2);
2337 if (!PyString_Check(name) || (PyObject_IsTrue(code) &&
2338 !PyString_Check(code)))
2339 goto typeerror;
2340 frozenmodules[i].name = PyString_AsString(name);
2341 if (PyObject_IsTrue(code)) {
2342 frozenmodules[i].code = PyString_AsString(code);
2343 frozenmodules[i].size = PyString_Size(code);
2344 } else {
2345 frozenmodules[i].code = NULL;
2346 frozenmodules[i].size = 0;
2347 }
2348 if (PyObject_IsTrue(ispkg))
2349 frozenmodules[i].size = -frozenmodules[i].size;
2350 }
2351 frozenmodules[n].name = NULL; /* sentinel */
2352 frozenmodules[n].code = NULL;
2353 frozenmodules[n].size = 0;
2354
2355 if (frozenmodulestuple != NULL) {
2356 Py_DECREF(frozenmodulestuple);
2357 PyMem_Free(PyImport_FrozenModules);
2358 } /* else we don't know how or if PyImport_FrozenModules were
2359 allocated, so we can't do anything. */
2360
2361 frozenmodulestuple = t;
2362 PyImport_FrozenModules = frozenmodules;
2363
2364 Py_INCREF(Py_None);
2365 return Py_None;
2366
2367typeerror:
2368 PyErr_SetString(PyExc_TypeError,
2369 "items must be tuples of length 3, "
2370 "containing two strings and a bool");
2371error:
2372 Py_DECREF(t);
2373 PyMem_Free(frozenmodules);
2374 return NULL;
2375}
2376
2377static PyObject *
2378imp_get_frozenmodules(PyObject *self, PyObject *args)
2379{
2380 PyObject *t, *item, *ob;
2381 int i;
2382 struct _frozen *p;
2383 if (!PyArg_ParseTuple(args, ":get_frozenmodules"))
2384 return NULL;
2385
2386 /* We could just return frozenmodulestuple if it isn't
2387 NULL, but it's possible a C extension stepped on
2388 PyImport_FrozenModules after us, so we always build
2389 a new tuple. */
2390
2391 for (p = PyImport_FrozenModules, i = 0; ; p++, i++) {
2392 if (p->name == NULL)
2393 break;
2394 }
2395 t = PyTuple_New(i);
2396 if (t == NULL)
2397 return NULL;
2398 for (p = PyImport_FrozenModules, i = 0; ; p++, i++) {
2399 if (p->name == NULL)
2400 break;
2401 item = PyTuple_New(3);
2402 if (item == NULL)
2403 goto error;
2404 ob = PyString_FromString(p->name);
2405 if (ob == NULL)
2406 goto error;
2407 Py_INCREF(ob);
2408 PyTuple_SET_ITEM(item, 0, ob);
2409 if (p->code != NULL) {
2410 ob = PyString_FromStringAndSize(p->code,
2411 p->size >= 0 ? p->size : -(p->size));
2412 if (ob == NULL)
2413 goto error;
2414 }
2415 else
2416 ob = Py_None;
2417 Py_INCREF(ob);
2418 PyTuple_SET_ITEM(item, 1, ob);
2419 ob = p->size >= 0 ? Py_False : Py_True;
2420 Py_INCREF(ob);
2421 PyTuple_SET_ITEM(item, 2, ob);
2422 PyTuple_SET_ITEM(t, i, item);
2423 }
2424 return t;
2425error:
2426 Py_DECREF(t);
2427 return NULL;
2428}
2429
Guido van Rossum79f25d91997-04-29 20:08:16 +00002430static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002431imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002432{
2433 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002434
Guido van Rossum43713e52000-02-29 13:59:29 +00002435 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002436 return NULL;
2437 return get_frozen_object(name);
2438}
2439
Guido van Rossum79f25d91997-04-29 20:08:16 +00002440static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002441imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002442{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002443 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002444 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002445 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002446 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002447}
2448
Guido van Rossum79f25d91997-04-29 20:08:16 +00002449static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002450imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002451{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002452 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002453 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002454 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002455 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002456 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002457 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002458}
2459
2460static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002461get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002462{
2463 FILE *fp;
2464 if (fob == NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002465 if (mode[0] == 'U')
2466 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002467 fp = fopen(pathname, mode);
2468 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002469 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002470 }
2471 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002472 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002473 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002474 PyErr_SetString(PyExc_ValueError,
2475 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002476 }
2477 return fp;
2478}
2479
Guido van Rossum79f25d91997-04-29 20:08:16 +00002480static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002481imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002482{
2483 char *name;
2484 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002485 PyObject *fob = NULL;
2486 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002487 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002488 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002489 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002490 return NULL;
2491 fp = get_file(pathname, fob, "rb");
2492 if (fp == NULL)
2493 return NULL;
2494 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002495 if (fob == NULL)
2496 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002497 return m;
2498}
2499
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002500#ifdef HAVE_DYNAMIC_LOADING
2501
Guido van Rossum79f25d91997-04-29 20:08:16 +00002502static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002503imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002504{
2505 char *name;
2506 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002507 PyObject *fob = NULL;
2508 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002509 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002510 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002511 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002512 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002513 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002514 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002515 if (fp == NULL)
2516 return NULL;
2517 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002518 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002519 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002520}
2521
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002522#endif /* HAVE_DYNAMIC_LOADING */
2523
Guido van Rossum79f25d91997-04-29 20:08:16 +00002524static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002525imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002526{
2527 char *name;
2528 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002529 PyObject *fob = NULL;
2530 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002531 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002532 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002533 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002534 return NULL;
2535 fp = get_file(pathname, fob, "r");
2536 if (fp == NULL)
2537 return NULL;
2538 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002539 if (fob == NULL)
2540 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002541 return m;
2542}
2543
Jack Jansen9c96a921995-02-15 22:57:06 +00002544#ifdef macintosh
Guido van Rossum79f25d91997-04-29 20:08:16 +00002545static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002546imp_load_resource(PyObject *self, PyObject *args)
Jack Jansen9c96a921995-02-15 22:57:06 +00002547{
2548 char *name;
2549 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002550 PyObject *m;
Jack Jansen9c96a921995-02-15 22:57:06 +00002551
Guido van Rossum43713e52000-02-29 13:59:29 +00002552 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
Jack Jansen9c96a921995-02-15 22:57:06 +00002553 return NULL;
2554 m = PyMac_LoadResourceModule(name, pathname);
2555 return m;
2556}
2557#endif /* macintosh */
2558
Guido van Rossum79f25d91997-04-29 20:08:16 +00002559static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002560imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002561{
2562 char *name;
2563 PyObject *fob;
2564 char *pathname;
2565 char *suffix; /* Unused */
2566 char *mode;
2567 int type;
2568 FILE *fp;
2569
Guido van Rossum43713e52000-02-29 13:59:29 +00002570 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002571 &name, &fob, &pathname,
2572 &suffix, &mode, &type))
2573 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002574 if (*mode) {
2575 /* Mode must start with 'r' or 'U' and must not contain '+'.
2576 Implicit in this test is the assumption that the mode
2577 may contain other modifiers like 'b' or 't'. */
2578
2579 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002580 PyErr_Format(PyExc_ValueError,
2581 "invalid file open mode %.200s", mode);
2582 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002583 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002584 }
2585 if (fob == Py_None)
2586 fp = NULL;
2587 else {
2588 if (!PyFile_Check(fob)) {
2589 PyErr_SetString(PyExc_ValueError,
2590 "load_module arg#2 should be a file or None");
2591 return NULL;
2592 }
2593 fp = get_file(pathname, fob, mode);
2594 if (fp == NULL)
2595 return NULL;
2596 }
2597 return load_module(name, fp, pathname, type);
2598}
2599
2600static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002601imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002602{
2603 char *name;
2604 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002605 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002606 return NULL;
2607 return load_package(name, pathname);
2608}
2609
2610static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002611imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002612{
2613 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002614 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002615 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002616 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002617}
2618
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002619/* Doc strings */
2620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002621PyDoc_STRVAR(doc_imp,
2622"This module provides the components needed to build your own\n\
2623__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002625PyDoc_STRVAR(doc_find_module,
2626"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002627Search for a module. If path is omitted or None, search for a\n\
2628built-in, frozen or special module and continue search in sys.path.\n\
2629The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002630package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002632PyDoc_STRVAR(doc_load_module,
2633"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002634Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002635The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002636
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002637PyDoc_STRVAR(doc_get_magic,
2638"get_magic() -> string\n\
2639Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002641PyDoc_STRVAR(doc_get_suffixes,
2642"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002643Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002644that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002646PyDoc_STRVAR(doc_new_module,
2647"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002648Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002649The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002651PyDoc_STRVAR(doc_lock_held,
2652"lock_held() -> 0 or 1\n\
Tim Peters69232342001-08-30 05:16:13 +00002653Return 1 if the import lock is currently held.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002654On platforms without threads, return 0.");
Tim Peters69232342001-08-30 05:16:13 +00002655
Just van Rossum3eb166b2002-11-29 20:47:40 +00002656PyDoc_STRVAR(doc_set_frozenmodules,
2657"set_frozenmodules(seq_of_tuples) -> None\n\
2658Set the global list of frozen modules.\n\
2659The single argument is a sequence of tuples of length 3:\n\
2660 (modulename, codedata, ispkg)\n\
2661'modulename' is the name of the frozen module (may contain dots).\n\
2662'codedata' is a marshalled code object. 'ispkg' is a boolean\n\
2663indicating whether the module is a package.");
2664
2665PyDoc_STRVAR(doc_get_frozenmodules,
2666"get_frozenmodules() -> tuple_of_tuples\n\
2667Return the global list of frozen modules as a tuple of tuples. See\n\
2668the set_frozenmodules() doc string for a description of its contents.");
2669
Guido van Rossum79f25d91997-04-29 20:08:16 +00002670static PyMethodDef imp_methods[] = {
Neal Norwitz031829d2002-03-31 14:37:44 +00002671 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2672 {"get_magic", imp_get_magic, METH_VARARGS, doc_get_magic},
2673 {"get_suffixes", imp_get_suffixes, METH_VARARGS, doc_get_suffixes},
2674 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2675 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2676 {"lock_held", imp_lock_held, METH_VARARGS, doc_lock_held},
Just van Rossum3eb166b2002-11-29 20:47:40 +00002677 {"set_frozenmodules", imp_set_frozenmodules, METH_VARARGS,
2678 doc_set_frozenmodules},
2679 {"get_frozenmodules", imp_get_frozenmodules, METH_VARARGS,
2680 doc_get_frozenmodules},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002681 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002682 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2683 {"init_builtin", imp_init_builtin, METH_VARARGS},
2684 {"init_frozen", imp_init_frozen, METH_VARARGS},
2685 {"is_builtin", imp_is_builtin, METH_VARARGS},
2686 {"is_frozen", imp_is_frozen, METH_VARARGS},
2687 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002688#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002689 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002690#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002691 {"load_package", imp_load_package, METH_VARARGS},
Jack Jansen9c96a921995-02-15 22:57:06 +00002692#ifdef macintosh
Neal Norwitz031829d2002-03-31 14:37:44 +00002693 {"load_resource", imp_load_resource, METH_VARARGS},
Jack Jansen9c96a921995-02-15 22:57:06 +00002694#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002695 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002696 {NULL, NULL} /* sentinel */
2697};
2698
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002699static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002700setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002701{
2702 PyObject *v;
2703 int err;
2704
2705 v = PyInt_FromLong((long)value);
2706 err = PyDict_SetItemString(d, name, v);
2707 Py_XDECREF(v);
2708 return err;
2709}
2710
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002711void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002712initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002713{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002714 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002715
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002716 m = Py_InitModule4("imp", imp_methods, doc_imp,
2717 NULL, PYTHON_API_VERSION);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002718 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002719
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002720 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2721 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2722 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2723 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2724 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2725 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2726 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2727 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002728 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002729
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002730 failure:
2731 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002732}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002733
2734
Guido van Rossumb18618d2000-05-03 23:44:39 +00002735/* API for embedding applications that want to add their own entries
2736 to the table of built-in modules. This should normally be called
2737 *before* Py_Initialize(). When the table resize fails, -1 is
2738 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002739
2740 After a similar function by Just van Rossum. */
2741
2742int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002743PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002744{
2745 static struct _inittab *our_copy = NULL;
2746 struct _inittab *p;
2747 int i, n;
2748
2749 /* Count the number of entries in both tables */
2750 for (n = 0; newtab[n].name != NULL; n++)
2751 ;
2752 if (n == 0)
2753 return 0; /* Nothing to do */
2754 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2755 ;
2756
2757 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002758 p = our_copy;
2759 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002760 if (p == NULL)
2761 return -1;
2762
2763 /* Copy the tables into the new memory */
2764 if (our_copy != PyImport_Inittab)
2765 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2766 PyImport_Inittab = our_copy = p;
2767 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2768
2769 return 0;
2770}
2771
2772/* Shorthand to add a single entry given a name and a function */
2773
2774int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002775PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002776{
2777 struct _inittab newtab[2];
2778
2779 memset(newtab, '\0', sizeof newtab);
2780
2781 newtab[0].name = name;
2782 newtab[0].initfunc = initfunc;
2783
2784 return PyImport_ExtendInittab(newtab);
2785}