import.c revision 36515e28ed1c0b6170c4972761ca4a96d4af0075
1
2/* Module definition and import implementation */
3
4#include "Python.h"
5
6#include "node.h"
7#include "token.h"
8#include "errcode.h"
9#include "marshal.h"
10#include "compile.h"
11#include "eval.h"
12#include "osdefs.h"
13#include "importdl.h"
14#ifdef macintosh
15#include "macglue.h"
16#endif
17
18#ifdef HAVE_UNISTD_H
19#include <unistd.h>
20#endif
21
22#ifdef HAVE_FCNTL_H
23#include <fcntl.h>
24#endif
25
26extern time_t PyOS_GetLastModificationTime(char *, FILE *);
27						/* In getmtime.c */
28
29/* Magic word to reject .pyc files generated by other Python versions */
30/* Change for each incompatible change */
31/* The value of CR and LF is incorporated so if you ever read or write
32   a .pyc file in text mode the magic number will be wrong; also, the
33   Apple MPW compiler swaps their values, botching string constants.
34   XXX That probably isn't important anymore.
35*/
36/* XXX Perhaps the magic number should be frozen and a version field
37   added to the .pyc file header? */
38/* New way to come up with the low 16 bits of the magic number:
39      (YEAR-1995) * 10000 +  MONTH * 100 + DAY
40   where MONTH and DAY are 1-based.
41   XXX Whatever the "old way" may have been isn't documented.
42   XXX This scheme breaks in 2002, as (2002-1995)*10000 = 70000 doesn't
43       fit in 16 bits.
44   XXX Later, sometimes 1 gets added to MAGIC in order to record that
45       the Unicode -U option is in use.  IMO (Tim's), that's a Bad Idea
46       (quite apart from that the -U option doesn't work so isn't used
47       anyway).
48*/
49#define MAGIC (60717 | ((long)'\r'<<16) | ((long)'\n'<<24))
50
51/* Magic word as global; note that _PyImport_Init() can change the
52   value of this global to accommodate for alterations of how the
53   compiler works which are enabled by command line switches. */
54static long pyc_magic = MAGIC;
55
56/* See _PyImport_FixupExtension() below */
57static PyObject *extensions = NULL;
58
59/* This table is defined in config.c: */
60extern struct _inittab _PyImport_Inittab[];
61
62struct _inittab *PyImport_Inittab = _PyImport_Inittab;
63
64/* these tables define the module suffixes that Python recognizes */
65struct filedescr * _PyImport_Filetab = NULL;
66
67#ifdef RISCOS
68static const struct filedescr _PyImport_StandardFiletab[] = {
69	{"/py", "r", PY_SOURCE},
70	{"/pyc", "rb", PY_COMPILED},
71	{0, 0}
72};
73#else
74static const struct filedescr _PyImport_StandardFiletab[] = {
75	{".py", "r", PY_SOURCE},
76#ifdef MS_WIN32
77	{".pyw", "r", PY_SOURCE},
78#endif
79	{".pyc", "rb", PY_COMPILED},
80	{0, 0}
81};
82#endif
83
84/* Initialize things */
85
86void
87_PyImport_Init(void)
88{
89	const struct filedescr *scan;
90	struct filedescr *filetab;
91	int countD = 0;
92	int countS = 0;
93
94	/* prepare _PyImport_Filetab: copy entries from
95	   _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
96	 */
97	for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
98		++countD;
99	for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
100		++countS;
101	filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
102	memcpy(filetab, _PyImport_DynLoadFiletab,
103	       countD * sizeof(struct filedescr));
104	memcpy(filetab + countD, _PyImport_StandardFiletab,
105	       countS * sizeof(struct filedescr));
106	filetab[countD + countS].suffix = NULL;
107
108	_PyImport_Filetab = filetab;
109
110	if (Py_OptimizeFlag) {
111		/* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
112		for (; filetab->suffix != NULL; filetab++) {
113#ifndef RISCOS
114			if (strcmp(filetab->suffix, ".pyc") == 0)
115				filetab->suffix = ".pyo";
116#else
117			if (strcmp(filetab->suffix, "/pyc") == 0)
118				filetab->suffix = "/pyo";
119#endif
120		}
121	}
122
123	if (Py_UnicodeFlag) {
124		/* Fix the pyc_magic so that byte compiled code created
125		   using the all-Unicode method doesn't interfere with
126		   code created in normal operation mode. */
127		pyc_magic = MAGIC + 1;
128	}
129}
130
131void
132_PyImport_Fini(void)
133{
134	Py_XDECREF(extensions);
135	extensions = NULL;
136	PyMem_DEL(_PyImport_Filetab);
137	_PyImport_Filetab = NULL;
138}
139
140
141/* Locking primitives to prevent parallel imports of the same module
142   in different threads to return with a partially loaded module.
143   These calls are serialized by the global interpreter lock. */
144
145#ifdef WITH_THREAD
146
147#include "pythread.h"
148
149static PyThread_type_lock import_lock = 0;
150static long import_lock_thread = -1;
151static int import_lock_level = 0;
152
153static void
154lock_import(void)
155{
156	long me = PyThread_get_thread_ident();
157	if (me == -1)
158		return; /* Too bad */
159	if (import_lock == NULL)
160		import_lock = PyThread_allocate_lock();
161	if (import_lock_thread == me) {
162		import_lock_level++;
163		return;
164	}
165	if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
166		PyThreadState *tstate = PyEval_SaveThread();
167		PyThread_acquire_lock(import_lock, 1);
168		PyEval_RestoreThread(tstate);
169	}
170	import_lock_thread = me;
171	import_lock_level = 1;
172}
173
174static void
175unlock_import(void)
176{
177	long me = PyThread_get_thread_ident();
178	if (me == -1)
179		return; /* Too bad */
180	if (import_lock_thread != me)
181		Py_FatalError("unlock_import: not holding the import lock");
182	import_lock_level--;
183	if (import_lock_level == 0) {
184		import_lock_thread = -1;
185		PyThread_release_lock(import_lock);
186	}
187}
188
189#else
190
191#define lock_import()
192#define unlock_import()
193
194#endif
195
196static PyObject *
197imp_lock_held(PyObject *self, PyObject *args)
198{
199	if (!PyArg_ParseTuple(args, ":lock_held"))
200		return NULL;
201#ifdef WITH_THREAD
202	return PyInt_FromLong(import_lock_thread != -1);
203#else
204	return PyInt_FromLong(0);
205#endif
206}
207
208/* Helper for sys */
209
210PyObject *
211PyImport_GetModuleDict(void)
212{
213	PyInterpreterState *interp = PyThreadState_Get()->interp;
214	if (interp->modules == NULL)
215		Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
216	return interp->modules;
217}
218
219
220/* List of names to clear in sys */
221static char* sys_deletes[] = {
222	"path", "argv", "ps1", "ps2", "exitfunc",
223	"exc_type", "exc_value", "exc_traceback",
224	"last_type", "last_value", "last_traceback",
225	NULL
226};
227
228static char* sys_files[] = {
229	"stdin", "__stdin__",
230	"stdout", "__stdout__",
231	"stderr", "__stderr__",
232	NULL
233};
234
235
236/* Un-initialize things, as good as we can */
237
238void
239PyImport_Cleanup(void)
240{
241	int pos, ndone;
242	char *name;
243	PyObject *key, *value, *dict;
244	PyInterpreterState *interp = PyThreadState_Get()->interp;
245	PyObject *modules = interp->modules;
246
247	if (modules == NULL)
248		return; /* Already done */
249
250	/* Delete some special variables first.  These are common
251	   places where user values hide and people complain when their
252	   destructors fail.  Since the modules containing them are
253	   deleted *last* of all, they would come too late in the normal
254	   destruction order.  Sigh. */
255
256	value = PyDict_GetItemString(modules, "__builtin__");
257	if (value != NULL && PyModule_Check(value)) {
258		dict = PyModule_GetDict(value);
259		if (Py_VerboseFlag)
260			PySys_WriteStderr("# clear __builtin__._\n");
261		PyDict_SetItemString(dict, "_", Py_None);
262	}
263	value = PyDict_GetItemString(modules, "sys");
264	if (value != NULL && PyModule_Check(value)) {
265		char **p;
266		PyObject *v;
267		dict = PyModule_GetDict(value);
268		for (p = sys_deletes; *p != NULL; p++) {
269			if (Py_VerboseFlag)
270				PySys_WriteStderr("# clear sys.%s\n", *p);
271			PyDict_SetItemString(dict, *p, Py_None);
272		}
273		for (p = sys_files; *p != NULL; p+=2) {
274			if (Py_VerboseFlag)
275				PySys_WriteStderr("# restore sys.%s\n", *p);
276			v = PyDict_GetItemString(dict, *(p+1));
277			if (v == NULL)
278				v = Py_None;
279			PyDict_SetItemString(dict, *p, v);
280		}
281	}
282
283	/* First, delete __main__ */
284	value = PyDict_GetItemString(modules, "__main__");
285	if (value != NULL && PyModule_Check(value)) {
286		if (Py_VerboseFlag)
287			PySys_WriteStderr("# cleanup __main__\n");
288		_PyModule_Clear(value);
289		PyDict_SetItemString(modules, "__main__", Py_None);
290	}
291
292	/* The special treatment of __builtin__ here is because even
293	   when it's not referenced as a module, its dictionary is
294	   referenced by almost every module's __builtins__.  Since
295	   deleting a module clears its dictionary (even if there are
296	   references left to it), we need to delete the __builtin__
297	   module last.  Likewise, we don't delete sys until the very
298	   end because it is implicitly referenced (e.g. by print).
299
300	   Also note that we 'delete' modules by replacing their entry
301	   in the modules dict with None, rather than really deleting
302	   them; this avoids a rehash of the modules dictionary and
303	   also marks them as "non existent" so they won't be
304	   re-imported. */
305
306	/* Next, repeatedly delete modules with a reference count of
307	   one (skipping __builtin__ and sys) and delete them */
308	do {
309		ndone = 0;
310		pos = 0;
311		while (PyDict_Next(modules, &pos, &key, &value)) {
312			if (value->ob_refcnt != 1)
313				continue;
314			if (PyString_Check(key) && PyModule_Check(value)) {
315				name = PyString_AS_STRING(key);
316				if (strcmp(name, "__builtin__") == 0)
317					continue;
318				if (strcmp(name, "sys") == 0)
319					continue;
320				if (Py_VerboseFlag)
321					PySys_WriteStderr(
322						"# cleanup[1] %s\n", name);
323				_PyModule_Clear(value);
324				PyDict_SetItem(modules, key, Py_None);
325				ndone++;
326			}
327		}
328	} while (ndone > 0);
329
330	/* Next, delete all modules (still skipping __builtin__ and sys) */
331	pos = 0;
332	while (PyDict_Next(modules, &pos, &key, &value)) {
333		if (PyString_Check(key) && PyModule_Check(value)) {
334			name = PyString_AS_STRING(key);
335			if (strcmp(name, "__builtin__") == 0)
336				continue;
337			if (strcmp(name, "sys") == 0)
338				continue;
339			if (Py_VerboseFlag)
340				PySys_WriteStderr("# cleanup[2] %s\n", name);
341			_PyModule_Clear(value);
342			PyDict_SetItem(modules, key, Py_None);
343		}
344	}
345
346	/* Next, delete sys and __builtin__ (in that order) */
347	value = PyDict_GetItemString(modules, "sys");
348	if (value != NULL && PyModule_Check(value)) {
349		if (Py_VerboseFlag)
350			PySys_WriteStderr("# cleanup sys\n");
351		_PyModule_Clear(value);
352		PyDict_SetItemString(modules, "sys", Py_None);
353	}
354	value = PyDict_GetItemString(modules, "__builtin__");
355	if (value != NULL && PyModule_Check(value)) {
356		if (Py_VerboseFlag)
357			PySys_WriteStderr("# cleanup __builtin__\n");
358		_PyModule_Clear(value);
359		PyDict_SetItemString(modules, "__builtin__", Py_None);
360	}
361
362	/* Finally, clear and delete the modules directory */
363	PyDict_Clear(modules);
364	interp->modules = NULL;
365	Py_DECREF(modules);
366}
367
368
369/* Helper for pythonrun.c -- return magic number */
370
371long
372PyImport_GetMagicNumber(void)
373{
374	return pyc_magic;
375}
376
377
378/* Magic for extension modules (built-in as well as dynamically
379   loaded).  To prevent initializing an extension module more than
380   once, we keep a static dictionary 'extensions' keyed by module name
381   (for built-in modules) or by filename (for dynamically loaded
382   modules), containing these modules.  A copy of the module's
383   dictionary is stored by calling _PyImport_FixupExtension()
384   immediately after the module initialization function succeeds.  A
385   copy can be retrieved from there by calling
386   _PyImport_FindExtension(). */
387
388PyObject *
389_PyImport_FixupExtension(char *name, char *filename)
390{
391	PyObject *modules, *mod, *dict, *copy;
392	if (extensions == NULL) {
393		extensions = PyDict_New();
394		if (extensions == NULL)
395			return NULL;
396	}
397	modules = PyImport_GetModuleDict();
398	mod = PyDict_GetItemString(modules, name);
399	if (mod == NULL || !PyModule_Check(mod)) {
400		PyErr_Format(PyExc_SystemError,
401		  "_PyImport_FixupExtension: module %.200s not loaded", name);
402		return NULL;
403	}
404	dict = PyModule_GetDict(mod);
405	if (dict == NULL)
406		return NULL;
407	copy = PyDict_Copy(dict);
408	if (copy == NULL)
409		return NULL;
410	PyDict_SetItemString(extensions, filename, copy);
411	Py_DECREF(copy);
412	return copy;
413}
414
415PyObject *
416_PyImport_FindExtension(char *name, char *filename)
417{
418	PyObject *dict, *mod, *mdict;
419	if (extensions == NULL)
420		return NULL;
421	dict = PyDict_GetItemString(extensions, filename);
422	if (dict == NULL)
423		return NULL;
424	mod = PyImport_AddModule(name);
425	if (mod == NULL)
426		return NULL;
427	mdict = PyModule_GetDict(mod);
428	if (mdict == NULL)
429		return NULL;
430	if (PyDict_Update(mdict, dict))
431		return NULL;
432	if (Py_VerboseFlag)
433		PySys_WriteStderr("import %s # previously loaded (%s)\n",
434			name, filename);
435	return mod;
436}
437
438
439/* Get the module object corresponding to a module name.
440   First check the modules dictionary if there's one there,
441   if not, create a new one and insert in in the modules dictionary.
442   Because the former action is most common, THIS DOES NOT RETURN A
443   'NEW' REFERENCE! */
444
445PyObject *
446PyImport_AddModule(char *name)
447{
448	PyObject *modules = PyImport_GetModuleDict();
449	PyObject *m;
450
451	if ((m = PyDict_GetItemString(modules, name)) != NULL &&
452	    PyModule_Check(m))
453		return m;
454	m = PyModule_New(name);
455	if (m == NULL)
456		return NULL;
457	if (PyDict_SetItemString(modules, name, m) != 0) {
458		Py_DECREF(m);
459		return NULL;
460	}
461	Py_DECREF(m); /* Yes, it still exists, in modules! */
462
463	return m;
464}
465
466
467/* Execute a code object in a module and return the module object
468   WITH INCREMENTED REFERENCE COUNT */
469
470PyObject *
471PyImport_ExecCodeModule(char *name, PyObject *co)
472{
473	return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
474}
475
476PyObject *
477PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
478{
479	PyObject *modules = PyImport_GetModuleDict();
480	PyObject *m, *d, *v;
481
482	m = PyImport_AddModule(name);
483	if (m == NULL)
484		return NULL;
485	d = PyModule_GetDict(m);
486	if (PyDict_GetItemString(d, "__builtins__") == NULL) {
487		if (PyDict_SetItemString(d, "__builtins__",
488					 PyEval_GetBuiltins()) != 0)
489			return NULL;
490	}
491	/* Remember the filename as the __file__ attribute */
492	v = NULL;
493	if (pathname != NULL) {
494		v = PyString_FromString(pathname);
495		if (v == NULL)
496			PyErr_Clear();
497	}
498	if (v == NULL) {
499		v = ((PyCodeObject *)co)->co_filename;
500		Py_INCREF(v);
501	}
502	if (PyDict_SetItemString(d, "__file__", v) != 0)
503		PyErr_Clear(); /* Not important enough to report */
504	Py_DECREF(v);
505
506	v = PyEval_EvalCode((PyCodeObject *)co, d, d);
507	if (v == NULL)
508		return NULL;
509	Py_DECREF(v);
510
511	if ((m = PyDict_GetItemString(modules, name)) == NULL) {
512		PyErr_Format(PyExc_ImportError,
513			     "Loaded module %.200s not found in sys.modules",
514			     name);
515		return NULL;
516	}
517
518	Py_INCREF(m);
519
520	return m;
521}
522
523
524/* Given a pathname for a Python source file, fill a buffer with the
525   pathname for the corresponding compiled file.  Return the pathname
526   for the compiled file, or NULL if there's no space in the buffer.
527   Doesn't set an exception. */
528
529static char *
530make_compiled_pathname(char *pathname, char *buf, size_t buflen)
531{
532	size_t len = strlen(pathname);
533	if (len+2 > buflen)
534		return NULL;
535
536#ifdef MS_WIN32
537	/* Treat .pyw as if it were .py.  The case of ".pyw" must match
538	   that used in _PyImport_StandardFiletab. */
539	if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
540		--len;	/* pretend 'w' isn't there */
541#endif
542	memcpy(buf, pathname, len);
543	buf[len] = Py_OptimizeFlag ? 'o' : 'c';
544	buf[len+1] = '\0';
545
546	return buf;
547}
548
549
550/* Given a pathname for a Python source file, its time of last
551   modification, and a pathname for a compiled file, check whether the
552   compiled file represents the same version of the source.  If so,
553   return a FILE pointer for the compiled file, positioned just after
554   the header; if not, return NULL.
555   Doesn't set an exception. */
556
557static FILE *
558check_compiled_module(char *pathname, long mtime, char *cpathname)
559{
560	FILE *fp;
561	long magic;
562	long pyc_mtime;
563
564	fp = fopen(cpathname, "rb");
565	if (fp == NULL)
566		return NULL;
567	magic = PyMarshal_ReadLongFromFile(fp);
568	if (magic != pyc_magic) {
569		if (Py_VerboseFlag)
570			PySys_WriteStderr("# %s has bad magic\n", cpathname);
571		fclose(fp);
572		return NULL;
573	}
574	pyc_mtime = PyMarshal_ReadLongFromFile(fp);
575	if (pyc_mtime != mtime) {
576		if (Py_VerboseFlag)
577			PySys_WriteStderr("# %s has bad mtime\n", cpathname);
578		fclose(fp);
579		return NULL;
580	}
581	if (Py_VerboseFlag)
582		PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
583	return fp;
584}
585
586
587/* Read a code object from a file and check it for validity */
588
589static PyCodeObject *
590read_compiled_module(char *cpathname, FILE *fp)
591{
592	PyObject *co;
593
594	co = PyMarshal_ReadLastObjectFromFile(fp);
595	/* Ugly: rd_object() may return NULL with or without error */
596	if (co == NULL || !PyCode_Check(co)) {
597		if (!PyErr_Occurred())
598			PyErr_Format(PyExc_ImportError,
599			    "Non-code object in %.200s", cpathname);
600		Py_XDECREF(co);
601		return NULL;
602	}
603	return (PyCodeObject *)co;
604}
605
606
607/* Load a module from a compiled file, execute it, and return its
608   module object WITH INCREMENTED REFERENCE COUNT */
609
610static PyObject *
611load_compiled_module(char *name, char *cpathname, FILE *fp)
612{
613	long magic;
614	PyCodeObject *co;
615	PyObject *m;
616
617	magic = PyMarshal_ReadLongFromFile(fp);
618	if (magic != pyc_magic) {
619		PyErr_Format(PyExc_ImportError,
620			     "Bad magic number in %.200s", cpathname);
621		return NULL;
622	}
623	(void) PyMarshal_ReadLongFromFile(fp);
624	co = read_compiled_module(cpathname, fp);
625	if (co == NULL)
626		return NULL;
627	if (Py_VerboseFlag)
628		PySys_WriteStderr("import %s # precompiled from %s\n",
629			name, cpathname);
630	m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
631	Py_DECREF(co);
632
633	return m;
634}
635
636/* Parse a source file and return the corresponding code object */
637
638static PyCodeObject *
639parse_source_module(char *pathname, FILE *fp)
640{
641	PyCodeObject *co;
642	node *n;
643
644	n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
645	if (n == NULL)
646		return NULL;
647	co = PyNode_Compile(n, pathname);
648	PyNode_Free(n);
649
650	return co;
651}
652
653
654/* Helper to open a bytecode file for writing in exclusive mode */
655
656static FILE *
657open_exclusive(char *filename)
658{
659#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
660	/* Use O_EXCL to avoid a race condition when another process tries to
661	   write the same file.  When that happens, our open() call fails,
662	   which is just fine (since it's only a cache).
663	   XXX If the file exists and is writable but the directory is not
664	   writable, the file will never be written.  Oh well.
665	*/
666	int fd;
667	(void) unlink(filename);
668	fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
669#ifdef O_BINARY
670				|O_BINARY   /* necessary for Windows */
671#endif
672
673			, 0666);
674	if (fd < 0)
675		return NULL;
676	return fdopen(fd, "wb");
677#else
678	/* Best we can do -- on Windows this can't happen anyway */
679	return fopen(filename, "wb");
680#endif
681}
682
683
684/* Write a compiled module to a file, placing the time of last
685   modification of its source into the header.
686   Errors are ignored, if a write error occurs an attempt is made to
687   remove the file. */
688
689static void
690write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
691{
692	FILE *fp;
693
694	fp = open_exclusive(cpathname);
695	if (fp == NULL) {
696		if (Py_VerboseFlag)
697			PySys_WriteStderr(
698				"# can't create %s\n", cpathname);
699		return;
700	}
701	PyMarshal_WriteLongToFile(pyc_magic, fp);
702	/* First write a 0 for mtime */
703	PyMarshal_WriteLongToFile(0L, fp);
704	PyMarshal_WriteObjectToFile((PyObject *)co, fp);
705	if (ferror(fp)) {
706		if (Py_VerboseFlag)
707			PySys_WriteStderr("# can't write %s\n", cpathname);
708		/* Don't keep partial file */
709		fclose(fp);
710		(void) unlink(cpathname);
711		return;
712	}
713	/* Now write the true mtime */
714	fseek(fp, 4L, 0);
715	PyMarshal_WriteLongToFile(mtime, fp);
716	fflush(fp);
717	fclose(fp);
718	if (Py_VerboseFlag)
719		PySys_WriteStderr("# wrote %s\n", cpathname);
720#ifdef macintosh
721	PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
722#endif
723}
724
725
726/* Load a source module from a given file and return its module
727   object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
728   byte-compiled file, use that instead. */
729
730static PyObject *
731load_source_module(char *name, char *pathname, FILE *fp)
732{
733	time_t mtime;
734	FILE *fpc;
735	char buf[MAXPATHLEN+1];
736	char *cpathname;
737	PyCodeObject *co;
738	PyObject *m;
739
740	mtime = PyOS_GetLastModificationTime(pathname, fp);
741	if (mtime == (time_t)(-1))
742		return NULL;
743#if SIZEOF_TIME_T > 4
744	/* Python's .pyc timestamp handling presumes that the timestamp fits
745	   in 4 bytes. This will be fine until sometime in the year 2038,
746	   when a 4-byte signed time_t will overflow.
747	 */
748	if (mtime >> 32) {
749		PyErr_SetString(PyExc_OverflowError,
750			"modification time overflows a 4 byte field");
751		return NULL;
752	}
753#endif
754	cpathname = make_compiled_pathname(pathname, buf,
755					   (size_t)MAXPATHLEN + 1);
756	if (cpathname != NULL &&
757	    (fpc = check_compiled_module(pathname, mtime, cpathname))) {
758		co = read_compiled_module(cpathname, fpc);
759		fclose(fpc);
760		if (co == NULL)
761			return NULL;
762		if (Py_VerboseFlag)
763			PySys_WriteStderr("import %s # precompiled from %s\n",
764				name, cpathname);
765		pathname = cpathname;
766	}
767	else {
768		co = parse_source_module(pathname, fp);
769		if (co == NULL)
770			return NULL;
771		if (Py_VerboseFlag)
772			PySys_WriteStderr("import %s # from %s\n",
773				name, pathname);
774		write_compiled_module(co, cpathname, mtime);
775	}
776	m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
777	Py_DECREF(co);
778
779	return m;
780}
781
782
783/* Forward */
784static PyObject *load_module(char *, FILE *, char *, int);
785static struct filedescr *find_module(char *, PyObject *,
786				     char *, size_t, FILE **);
787static struct _frozen *find_frozen(char *name);
788
789/* Load a package and return its module object WITH INCREMENTED
790   REFERENCE COUNT */
791
792static PyObject *
793load_package(char *name, char *pathname)
794{
795	PyObject *m, *d, *file, *path;
796	int err;
797	char buf[MAXPATHLEN+1];
798	FILE *fp = NULL;
799	struct filedescr *fdp;
800
801	m = PyImport_AddModule(name);
802	if (m == NULL)
803		return NULL;
804	if (Py_VerboseFlag)
805		PySys_WriteStderr("import %s # directory %s\n",
806			name, pathname);
807	d = PyModule_GetDict(m);
808	file = PyString_FromString(pathname);
809	if (file == NULL)
810		return NULL;
811	path = Py_BuildValue("[O]", file);
812	if (path == NULL) {
813		Py_DECREF(file);
814		return NULL;
815	}
816	err = PyDict_SetItemString(d, "__file__", file);
817	if (err == 0)
818		err = PyDict_SetItemString(d, "__path__", path);
819	if (err != 0) {
820		m = NULL;
821		goto cleanup;
822	}
823	buf[0] = '\0';
824	fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
825	if (fdp == NULL) {
826		if (PyErr_ExceptionMatches(PyExc_ImportError)) {
827			PyErr_Clear();
828		}
829		else
830			m = NULL;
831		goto cleanup;
832	}
833	m = load_module(name, fp, buf, fdp->type);
834	if (fp != NULL)
835		fclose(fp);
836  cleanup:
837	Py_XDECREF(path);
838	Py_XDECREF(file);
839	return m;
840}
841
842
843/* Helper to test for built-in module */
844
845static int
846is_builtin(char *name)
847{
848	int i;
849	for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
850		if (strcmp(name, PyImport_Inittab[i].name) == 0) {
851			if (PyImport_Inittab[i].initfunc == NULL)
852				return -1;
853			else
854				return 1;
855		}
856	}
857	return 0;
858}
859
860
861/* Search the path (default sys.path) for a module.  Return the
862   corresponding filedescr struct, and (via return arguments) the
863   pathname and an open file.  Return NULL if the module is not found. */
864
865#ifdef MS_COREDLL
866extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
867					char *, int);
868#endif
869
870static int case_ok(char *, int, int, char *);
871static int find_init_module(char *); /* Forward */
872
873static struct filedescr *
874find_module(char *realname, PyObject *path, char *buf, size_t buflen,
875	    FILE **p_fp)
876{
877	int i, npath;
878	size_t len, namelen;
879	struct filedescr *fdp = NULL;
880	FILE *fp = NULL;
881#ifndef RISCOS
882	struct stat statbuf;
883#endif
884	static struct filedescr fd_frozen = {"", "", PY_FROZEN};
885	static struct filedescr fd_builtin = {"", "", C_BUILTIN};
886	static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
887	char name[MAXPATHLEN+1];
888
889	if (strlen(realname) > MAXPATHLEN) {
890		PyErr_SetString(PyExc_OverflowError,
891				"module name is too long");
892		return NULL;
893	}
894	strcpy(name, realname);
895
896	if (path != NULL && PyString_Check(path)) {
897		/* The only type of submodule allowed inside a "frozen"
898		   package are other frozen modules or packages. */
899		if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
900			PyErr_SetString(PyExc_ImportError,
901					"full frozen module name too long");
902			return NULL;
903		}
904		strcpy(buf, PyString_AsString(path));
905		strcat(buf, ".");
906		strcat(buf, name);
907		strcpy(name, buf);
908#ifdef macintosh
909		/* Freezing on the mac works different, and the modules are
910		** actually on sys.path. So we don't take the quick exit but
911		** continue with the normal flow.
912		*/
913		path = NULL;
914#else
915		if (find_frozen(name) != NULL) {
916			strcpy(buf, name);
917			return &fd_frozen;
918		}
919		PyErr_Format(PyExc_ImportError,
920			     "No frozen submodule named %.200s", name);
921		return NULL;
922#endif
923	}
924	if (path == NULL) {
925		if (is_builtin(name)) {
926			strcpy(buf, name);
927			return &fd_builtin;
928		}
929		if ((find_frozen(name)) != NULL) {
930			strcpy(buf, name);
931			return &fd_frozen;
932		}
933
934#ifdef MS_COREDLL
935		fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
936		if (fp != NULL) {
937			*p_fp = fp;
938			return fdp;
939		}
940#endif
941		path = PySys_GetObject("path");
942	}
943	if (path == NULL || !PyList_Check(path)) {
944		PyErr_SetString(PyExc_ImportError,
945				"sys.path must be a list of directory names");
946		return NULL;
947	}
948	npath = PyList_Size(path);
949	namelen = strlen(name);
950	for (i = 0; i < npath; i++) {
951		PyObject *v = PyList_GetItem(path, i);
952		if (!PyString_Check(v))
953			continue;
954		len = PyString_Size(v);
955		if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen)
956			continue; /* Too long */
957		strcpy(buf, PyString_AsString(v));
958		if (strlen(buf) != len)
959			continue; /* v contains '\0' */
960#ifdef macintosh
961#ifdef INTERN_STRINGS
962		/*
963		** Speedup: each sys.path item is interned, and
964		** FindResourceModule remembers which items refer to
965		** folders (so we don't have to bother trying to look
966		** into them for resources).
967		*/
968		PyString_InternInPlace(&PyList_GET_ITEM(path, i));
969		v = PyList_GET_ITEM(path, i);
970#endif
971		if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
972			static struct filedescr resfiledescr =
973				{"", "", PY_RESOURCE};
974
975			return &resfiledescr;
976		}
977		if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
978			static struct filedescr resfiledescr =
979				{"", "", PY_CODERESOURCE};
980
981			return &resfiledescr;
982		}
983#endif
984		if (len > 0 && buf[len-1] != SEP
985#ifdef ALTSEP
986		    && buf[len-1] != ALTSEP
987#endif
988		    )
989			buf[len++] = SEP;
990		strcpy(buf+len, name);
991		len += namelen;
992
993		/* Check for package import (buf holds a directory name,
994		   and there's an __init__ module in that directory */
995#ifdef HAVE_STAT
996		if (stat(buf, &statbuf) == 0 &&       /* it exists */
997		    S_ISDIR(statbuf.st_mode) &&       /* it's a directory */
998		    find_init_module(buf) &&          /* it has __init__.py */
999		    case_ok(buf, len, namelen, name)) /* and case matches */
1000			return &fd_package;
1001#else
1002		/* XXX How are you going to test for directories? */
1003#ifdef RISCOS
1004		if (isdir(buf) &&
1005		    find_init_module(buf) &&
1006		    case_ok(buf, len, namelen, name))
1007			return &fd_package;
1008#endif
1009#endif
1010#ifdef macintosh
1011		fdp = PyMac_FindModuleExtension(buf, &len, name);
1012		if (fdp) {
1013#else
1014		for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1015			strcpy(buf+len, fdp->suffix);
1016			if (Py_VerboseFlag > 1)
1017				PySys_WriteStderr("# trying %s\n", buf);
1018#endif /* !macintosh */
1019			fp = fopen(buf, fdp->mode);
1020			if (fp != NULL) {
1021				if (case_ok(buf, len, namelen, name))
1022					break;
1023				else {	 /* continue search */
1024					fclose(fp);
1025					fp = NULL;
1026				}
1027			}
1028		}
1029		if (fp != NULL)
1030			break;
1031	}
1032	if (fp == NULL) {
1033		PyErr_Format(PyExc_ImportError,
1034			     "No module named %.200s", name);
1035		return NULL;
1036	}
1037	*p_fp = fp;
1038	return fdp;
1039}
1040
1041/* case_ok(char* buf, int len, int namelen, char* name)
1042 * The arguments here are tricky, best shown by example:
1043 *    /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1044 *    ^                      ^                   ^    ^
1045 *    |--------------------- buf ---------------------|
1046 *    |------------------- len ------------------|
1047 *                           |------ name -------|
1048 *                           |----- namelen -----|
1049 * buf is the full path, but len only counts up to (& exclusive of) the
1050 * extension.  name is the module name, also exclusive of extension.
1051 *
1052 * We've already done a successful stat() or fopen() on buf, so know that
1053 * there's some match, possibly case-insensitive.
1054 *
1055 * case_ok() is to return 1 if there's a case-sensitive match for
1056 * name, else 0.  case_ok() is also to return 1 if envar PYTHONCASEOK
1057 * exists.
1058 *
1059 * case_ok() is used to implement case-sensitive import semantics even
1060 * on platforms with case-insensitive filesystems.  It's trivial to implement
1061 * for case-sensitive filesystems.  It's pretty much a cross-platform
1062 * nightmare for systems with case-insensitive filesystems.
1063 */
1064
1065/* First we may need a pile of platform-specific header files; the sequence
1066 * of #if's here should match the sequence in the body of case_ok().
1067 */
1068#if defined(MS_WIN32) || defined(__CYGWIN__)
1069#include <windows.h>
1070#ifdef __CYGWIN__
1071#include <sys/cygwin.h>
1072#endif
1073
1074#elif defined(DJGPP)
1075#include <dir.h>
1076
1077#elif defined(macintosh)
1078#include <TextUtils.h>
1079#ifdef USE_GUSI1
1080#include "TFileSpec.h"		/* for Path2FSSpec() */
1081#endif
1082
1083#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1084#include <sys/types.h>
1085#include <dirent.h>
1086
1087#elif defined(RISCOS)
1088#include "oslib/osfscontrol.h"
1089#endif
1090
1091static int
1092case_ok(char *buf, int len, int namelen, char *name)
1093{
1094/* Pick a platform-specific implementation; the sequence of #if's here should
1095 * match the sequence just above.
1096 */
1097
1098/* MS_WIN32 || __CYGWIN__ */
1099#if defined(MS_WIN32) || defined(__CYGWIN__)
1100	WIN32_FIND_DATA data;
1101	HANDLE h;
1102#ifdef __CYGWIN__
1103	char tempbuf[MAX_PATH];
1104#endif
1105
1106	if (Py_GETENV("PYTHONCASEOK") != NULL)
1107		return 1;
1108
1109#ifdef __CYGWIN__
1110	cygwin32_conv_to_win32_path(buf, tempbuf);
1111	h = FindFirstFile(tempbuf, &data);
1112#else
1113	h = FindFirstFile(buf, &data);
1114#endif
1115	if (h == INVALID_HANDLE_VALUE) {
1116		PyErr_Format(PyExc_NameError,
1117		  "Can't find file for module %.100s\n(filename %.300s)",
1118		  name, buf);
1119		return 0;
1120	}
1121	FindClose(h);
1122	return strncmp(data.cFileName, name, namelen) == 0;
1123
1124/* DJGPP */
1125#elif defined(DJGPP)
1126	struct ffblk ffblk;
1127	int done;
1128
1129	if (Py_GETENV("PYTHONCASEOK") != NULL)
1130		return 1;
1131
1132	done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1133	if (done) {
1134		PyErr_Format(PyExc_NameError,
1135		  "Can't find file for module %.100s\n(filename %.300s)",
1136		  name, buf);
1137		return 0;
1138	}
1139	return strncmp(ffblk.ff_name, name, namelen) == 0;
1140
1141/* macintosh */
1142#elif defined(macintosh)
1143	FSSpec fss;
1144	OSErr err;
1145
1146	if (Py_GETENV("PYTHONCASEOK") != NULL)
1147		return 1;
1148
1149#ifndef USE_GUSI1
1150	err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
1151#else
1152	/* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1153	   the way, which is fine for all directories, but here we need
1154	   the original name of the alias file (say, Dlg.ppc.slb, not
1155	   toolboxmodules.ppc.slb). */
1156	char *colon;
1157	err = Path2FSSpec(buf, &fss);
1158	if (err == noErr) {
1159		colon = strrchr(buf, ':'); /* find filename */
1160		if (colon != NULL)
1161			err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1162					   Pstring(colon+1), &fss);
1163		else
1164			err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1165					   fss.name, &fss);
1166	}
1167#endif
1168	if (err) {
1169		PyErr_Format(PyExc_NameError,
1170		     "Can't find file for module %.100s\n(filename %.300s)",
1171		     name, buf);
1172		return 0;
1173	}
1174	return fss.name[0] >= namelen &&
1175	       strncmp(name, (char *)fss.name+1, namelen) == 0;
1176
1177/* new-fangled macintosh (macosx) */
1178#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1179	DIR *dirp;
1180	struct dirent *dp;
1181	char dirname[MAXPATHLEN + 1];
1182	const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1183
1184	if (Py_GETENV("PYTHONCASEOK") != NULL)
1185		return 1;
1186
1187	/* Copy the dir component into dirname; substitute "." if empty */
1188	if (dirlen <= 0) {
1189		dirname[0] = '.';
1190		dirname[1] = '\0';
1191	}
1192	else {
1193		assert(dirlen <= MAXPATHLEN);
1194		memcpy(dirname, buf, dirlen);
1195		dirname[dirlen] = '\0';
1196	}
1197	/* Open the directory and search the entries for an exact match. */
1198	dirp = opendir(dirname);
1199	if (dirp) {
1200		char *nameWithExt = buf + len - namelen;
1201		while ((dp = readdir(dirp)) != NULL) {
1202			const int thislen =
1203#ifdef _DIRENT_HAVE_D_NAMELEN
1204						dp->d_namlen;
1205#else
1206						strlen(dp->d_name);
1207#endif
1208			if (thislen >= namelen &&
1209			    strcmp(dp->d_name, nameWithExt) == 0) {
1210				(void)closedir(dirp);
1211				return 1; /* Found */
1212			}
1213		}
1214		(void)closedir(dirp);
1215	}
1216	return 0 ; /* Not found */
1217
1218/* RISC OS */
1219#elif defined(RISCOS)
1220	char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1221	char buf2[MAXPATHLEN+2];
1222	char *nameWithExt = buf+len-namelen;
1223	int canonlen;
1224	os_error *e;
1225
1226	if (Py_GETENV("PYTHONCASEOK") != NULL)
1227		return 1;
1228
1229	/* workaround:
1230	   append wildcard, otherwise case of filename wouldn't be touched */
1231	strcpy(buf2, buf);
1232	strcat(buf2, "*");
1233
1234	e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1235	canonlen = MAXPATHLEN+1-canonlen;
1236	if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1237		return 0;
1238	if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1239		return 1; /* match */
1240
1241	return 0;
1242
1243/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1244#else
1245	return 1;
1246
1247#endif
1248}
1249
1250
1251#ifdef HAVE_STAT
1252/* Helper to look for __init__.py or __init__.py[co] in potential package */
1253static int
1254find_init_module(char *buf)
1255{
1256	const size_t save_len = strlen(buf);
1257	size_t i = save_len;
1258	char *pname;  /* pointer to start of __init__ */
1259	struct stat statbuf;
1260
1261/*	For calling case_ok(buf, len, namelen, name):
1262 *	/a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1263 *	^                      ^                   ^    ^
1264 *	|--------------------- buf ---------------------|
1265 *	|------------------- len ------------------|
1266 *	                       |------ name -------|
1267 *	                       |----- namelen -----|
1268 */
1269	if (save_len + 13 >= MAXPATHLEN)
1270		return 0;
1271	buf[i++] = SEP;
1272	pname = buf + i;
1273	strcpy(pname, "__init__.py");
1274	if (stat(buf, &statbuf) == 0) {
1275		if (case_ok(buf,
1276			    save_len + 9,	/* len("/__init__") */
1277		            8,   		/* len("__init__") */
1278		            pname)) {
1279			buf[save_len] = '\0';
1280			return 1;
1281		}
1282	}
1283	i += strlen(pname);
1284	strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1285	if (stat(buf, &statbuf) == 0) {
1286		if (case_ok(buf,
1287			    save_len + 9,	/* len("/__init__") */
1288		            8,   		/* len("__init__") */
1289		            pname)) {
1290			buf[save_len] = '\0';
1291			return 1;
1292		}
1293	}
1294	buf[save_len] = '\0';
1295	return 0;
1296}
1297
1298#else
1299
1300#ifdef RISCOS
1301static int
1302find_init_module(buf)
1303	char *buf;
1304{
1305	int save_len = strlen(buf);
1306	int i = save_len;
1307
1308	if (save_len + 13 >= MAXPATHLEN)
1309		return 0;
1310	buf[i++] = SEP;
1311	strcpy(buf+i, "__init__/py");
1312	if (isfile(buf)) {
1313		buf[save_len] = '\0';
1314		return 1;
1315	}
1316
1317	if (Py_OptimizeFlag)
1318		strcpy(buf+i, "o");
1319	else
1320		strcpy(buf+i, "c");
1321	if (isfile(buf)) {
1322		buf[save_len] = '\0';
1323		return 1;
1324	}
1325	buf[save_len] = '\0';
1326	return 0;
1327}
1328#endif /*RISCOS*/
1329
1330#endif /* HAVE_STAT */
1331
1332
1333static int init_builtin(char *); /* Forward */
1334
1335/* Load an external module using the default search path and return
1336   its module object WITH INCREMENTED REFERENCE COUNT */
1337
1338static PyObject *
1339load_module(char *name, FILE *fp, char *buf, int type)
1340{
1341	PyObject *modules;
1342	PyObject *m;
1343	int err;
1344
1345	/* First check that there's an open file (if we need one)  */
1346	switch (type) {
1347	case PY_SOURCE:
1348	case PY_COMPILED:
1349		if (fp == NULL) {
1350			PyErr_Format(PyExc_ValueError,
1351			   "file object required for import (type code %d)",
1352				     type);
1353			return NULL;
1354		}
1355	}
1356
1357	switch (type) {
1358
1359	case PY_SOURCE:
1360		m = load_source_module(name, buf, fp);
1361		break;
1362
1363	case PY_COMPILED:
1364		m = load_compiled_module(name, buf, fp);
1365		break;
1366
1367#ifdef HAVE_DYNAMIC_LOADING
1368	case C_EXTENSION:
1369		m = _PyImport_LoadDynamicModule(name, buf, fp);
1370		break;
1371#endif
1372
1373#ifdef macintosh
1374	case PY_RESOURCE:
1375		m = PyMac_LoadResourceModule(name, buf);
1376		break;
1377	case PY_CODERESOURCE:
1378		m = PyMac_LoadCodeResourceModule(name, buf);
1379		break;
1380#endif
1381
1382	case PKG_DIRECTORY:
1383		m = load_package(name, buf);
1384		break;
1385
1386	case C_BUILTIN:
1387	case PY_FROZEN:
1388		if (buf != NULL && buf[0] != '\0')
1389			name = buf;
1390		if (type == C_BUILTIN)
1391			err = init_builtin(name);
1392		else
1393			err = PyImport_ImportFrozenModule(name);
1394		if (err < 0)
1395			return NULL;
1396		if (err == 0) {
1397			PyErr_Format(PyExc_ImportError,
1398				     "Purported %s module %.200s not found",
1399				     type == C_BUILTIN ?
1400						"builtin" : "frozen",
1401				     name);
1402			return NULL;
1403		}
1404		modules = PyImport_GetModuleDict();
1405		m = PyDict_GetItemString(modules, name);
1406		if (m == NULL) {
1407			PyErr_Format(
1408				PyExc_ImportError,
1409				"%s module %.200s not properly initialized",
1410				type == C_BUILTIN ?
1411					"builtin" : "frozen",
1412				name);
1413			return NULL;
1414		}
1415		Py_INCREF(m);
1416		break;
1417
1418	default:
1419		PyErr_Format(PyExc_ImportError,
1420			     "Don't know how to import %.200s (type code %d)",
1421			      name, type);
1422		m = NULL;
1423
1424	}
1425
1426	return m;
1427}
1428
1429
1430/* Initialize a built-in module.
1431   Return 1 for succes, 0 if the module is not found, and -1 with
1432   an exception set if the initialization failed. */
1433
1434static int
1435init_builtin(char *name)
1436{
1437	struct _inittab *p;
1438
1439	if (_PyImport_FindExtension(name, name) != NULL)
1440		return 1;
1441
1442	for (p = PyImport_Inittab; p->name != NULL; p++) {
1443		if (strcmp(name, p->name) == 0) {
1444			if (p->initfunc == NULL) {
1445				PyErr_Format(PyExc_ImportError,
1446				    "Cannot re-init internal module %.200s",
1447				    name);
1448				return -1;
1449			}
1450			if (Py_VerboseFlag)
1451				PySys_WriteStderr("import %s # builtin\n", name);
1452			(*p->initfunc)();
1453			if (PyErr_Occurred())
1454				return -1;
1455			if (_PyImport_FixupExtension(name, name) == NULL)
1456				return -1;
1457			return 1;
1458		}
1459	}
1460	return 0;
1461}
1462
1463
1464/* Frozen modules */
1465
1466static struct _frozen *
1467find_frozen(char *name)
1468{
1469	struct _frozen *p;
1470
1471	for (p = PyImport_FrozenModules; ; p++) {
1472		if (p->name == NULL)
1473			return NULL;
1474		if (strcmp(p->name, name) == 0)
1475			break;
1476	}
1477	return p;
1478}
1479
1480static PyObject *
1481get_frozen_object(char *name)
1482{
1483	struct _frozen *p = find_frozen(name);
1484	int size;
1485
1486	if (p == NULL) {
1487		PyErr_Format(PyExc_ImportError,
1488			     "No such frozen object named %.200s",
1489			     name);
1490		return NULL;
1491	}
1492	if (p->code == NULL) {
1493		PyErr_Format(PyExc_ImportError,
1494			     "Excluded frozen object named %.200s",
1495			     name);
1496		return NULL;
1497	}
1498	size = p->size;
1499	if (size < 0)
1500		size = -size;
1501	return PyMarshal_ReadObjectFromString((char *)p->code, size);
1502}
1503
1504/* Initialize a frozen module.
1505   Return 1 for succes, 0 if the module is not found, and -1 with
1506   an exception set if the initialization failed.
1507   This function is also used from frozenmain.c */
1508
1509int
1510PyImport_ImportFrozenModule(char *name)
1511{
1512	struct _frozen *p = find_frozen(name);
1513	PyObject *co;
1514	PyObject *m;
1515	int ispackage;
1516	int size;
1517
1518	if (p == NULL)
1519		return 0;
1520	if (p->code == NULL) {
1521		PyErr_Format(PyExc_ImportError,
1522			     "Excluded frozen object named %.200s",
1523			     name);
1524		return -1;
1525	}
1526	size = p->size;
1527	ispackage = (size < 0);
1528	if (ispackage)
1529		size = -size;
1530	if (Py_VerboseFlag)
1531		PySys_WriteStderr("import %s # frozen%s\n",
1532			name, ispackage ? " package" : "");
1533	co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1534	if (co == NULL)
1535		return -1;
1536	if (!PyCode_Check(co)) {
1537		Py_DECREF(co);
1538		PyErr_Format(PyExc_TypeError,
1539			     "frozen object %.200s is not a code object",
1540			     name);
1541		return -1;
1542	}
1543	if (ispackage) {
1544		/* Set __path__ to the package name */
1545		PyObject *d, *s;
1546		int err;
1547		m = PyImport_AddModule(name);
1548		if (m == NULL)
1549			return -1;
1550		d = PyModule_GetDict(m);
1551		s = PyString_InternFromString(name);
1552		if (s == NULL)
1553			return -1;
1554		err = PyDict_SetItemString(d, "__path__", s);
1555		Py_DECREF(s);
1556		if (err != 0)
1557			return err;
1558	}
1559	m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1560	Py_DECREF(co);
1561	if (m == NULL)
1562		return -1;
1563	Py_DECREF(m);
1564	return 1;
1565}
1566
1567
1568/* Import a module, either built-in, frozen, or external, and return
1569   its module object WITH INCREMENTED REFERENCE COUNT */
1570
1571PyObject *
1572PyImport_ImportModule(char *name)
1573{
1574	PyObject *pname;
1575	PyObject *result;
1576
1577	pname = PyString_FromString(name);
1578	result = PyImport_Import(pname);
1579	Py_DECREF(pname);
1580	return result;
1581}
1582
1583/* Forward declarations for helper routines */
1584static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1585static PyObject *load_next(PyObject *mod, PyObject *altmod,
1586			   char **p_name, char *buf, int *p_buflen);
1587static int mark_miss(char *name);
1588static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1589			   char *buf, int buflen, int recursive);
1590static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1591
1592/* The Magnum Opus of dotted-name import :-) */
1593
1594static PyObject *
1595import_module_ex(char *name, PyObject *globals, PyObject *locals,
1596		 PyObject *fromlist)
1597{
1598	char buf[MAXPATHLEN+1];
1599	int buflen = 0;
1600	PyObject *parent, *head, *next, *tail;
1601
1602	parent = get_parent(globals, buf, &buflen);
1603	if (parent == NULL)
1604		return NULL;
1605
1606	head = load_next(parent, Py_None, &name, buf, &buflen);
1607	if (head == NULL)
1608		return NULL;
1609
1610	tail = head;
1611	Py_INCREF(tail);
1612	while (name) {
1613		next = load_next(tail, tail, &name, buf, &buflen);
1614		Py_DECREF(tail);
1615		if (next == NULL) {
1616			Py_DECREF(head);
1617			return NULL;
1618		}
1619		tail = next;
1620	}
1621
1622	if (fromlist != NULL) {
1623		if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1624			fromlist = NULL;
1625	}
1626
1627	if (fromlist == NULL) {
1628		Py_DECREF(tail);
1629		return head;
1630	}
1631
1632	Py_DECREF(head);
1633	if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
1634		Py_DECREF(tail);
1635		return NULL;
1636	}
1637
1638	return tail;
1639}
1640
1641PyObject *
1642PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1643			PyObject *fromlist)
1644{
1645	PyObject *result;
1646	lock_import();
1647	result = import_module_ex(name, globals, locals, fromlist);
1648	unlock_import();
1649	return result;
1650}
1651
1652static PyObject *
1653get_parent(PyObject *globals, char *buf, int *p_buflen)
1654{
1655	static PyObject *namestr = NULL;
1656	static PyObject *pathstr = NULL;
1657	PyObject *modname, *modpath, *modules, *parent;
1658
1659	if (globals == NULL || !PyDict_Check(globals))
1660		return Py_None;
1661
1662	if (namestr == NULL) {
1663		namestr = PyString_InternFromString("__name__");
1664		if (namestr == NULL)
1665			return NULL;
1666	}
1667	if (pathstr == NULL) {
1668		pathstr = PyString_InternFromString("__path__");
1669		if (pathstr == NULL)
1670			return NULL;
1671	}
1672
1673	*buf = '\0';
1674	*p_buflen = 0;
1675	modname = PyDict_GetItem(globals, namestr);
1676	if (modname == NULL || !PyString_Check(modname))
1677		return Py_None;
1678
1679	modpath = PyDict_GetItem(globals, pathstr);
1680	if (modpath != NULL) {
1681		int len = PyString_GET_SIZE(modname);
1682		if (len > MAXPATHLEN) {
1683			PyErr_SetString(PyExc_ValueError,
1684					"Module name too long");
1685			return NULL;
1686		}
1687		strcpy(buf, PyString_AS_STRING(modname));
1688		*p_buflen = len;
1689	}
1690	else {
1691		char *start = PyString_AS_STRING(modname);
1692		char *lastdot = strrchr(start, '.');
1693		size_t len;
1694		if (lastdot == NULL)
1695			return Py_None;
1696		len = lastdot - start;
1697		if (len >= MAXPATHLEN) {
1698			PyErr_SetString(PyExc_ValueError,
1699					"Module name too long");
1700			return NULL;
1701		}
1702		strncpy(buf, start, len);
1703		buf[len] = '\0';
1704		*p_buflen = len;
1705	}
1706
1707	modules = PyImport_GetModuleDict();
1708	parent = PyDict_GetItemString(modules, buf);
1709	if (parent == NULL)
1710		parent = Py_None;
1711	return parent;
1712	/* We expect, but can't guarantee, if parent != None, that:
1713	   - parent.__name__ == buf
1714	   - parent.__dict__ is globals
1715	   If this is violated...  Who cares? */
1716}
1717
1718/* altmod is either None or same as mod */
1719static PyObject *
1720load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
1721	  int *p_buflen)
1722{
1723	char *name = *p_name;
1724	char *dot = strchr(name, '.');
1725	size_t len;
1726	char *p;
1727	PyObject *result;
1728
1729	if (dot == NULL) {
1730		*p_name = NULL;
1731		len = strlen(name);
1732	}
1733	else {
1734		*p_name = dot+1;
1735		len = dot-name;
1736	}
1737	if (len == 0) {
1738		PyErr_SetString(PyExc_ValueError,
1739				"Empty module name");
1740		return NULL;
1741	}
1742
1743	p = buf + *p_buflen;
1744	if (p != buf)
1745		*p++ = '.';
1746	if (p+len-buf >= MAXPATHLEN) {
1747		PyErr_SetString(PyExc_ValueError,
1748				"Module name too long");
1749		return NULL;
1750	}
1751	strncpy(p, name, len);
1752	p[len] = '\0';
1753	*p_buflen = p+len-buf;
1754
1755	result = import_submodule(mod, p, buf);
1756	if (result == Py_None && altmod != mod) {
1757		Py_DECREF(result);
1758		/* Here, altmod must be None and mod must not be None */
1759		result = import_submodule(altmod, p, p);
1760		if (result != NULL && result != Py_None) {
1761			if (mark_miss(buf) != 0) {
1762				Py_DECREF(result);
1763				return NULL;
1764			}
1765			strncpy(buf, name, len);
1766			buf[len] = '\0';
1767			*p_buflen = len;
1768		}
1769	}
1770	if (result == NULL)
1771		return NULL;
1772
1773	if (result == Py_None) {
1774		Py_DECREF(result);
1775		PyErr_Format(PyExc_ImportError,
1776			     "No module named %.200s", name);
1777		return NULL;
1778	}
1779
1780	return result;
1781}
1782
1783static int
1784mark_miss(char *name)
1785{
1786	PyObject *modules = PyImport_GetModuleDict();
1787	return PyDict_SetItemString(modules, name, Py_None);
1788}
1789
1790static int
1791ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
1792		int recursive)
1793{
1794	int i;
1795
1796	if (!PyObject_HasAttrString(mod, "__path__"))
1797		return 1;
1798
1799	for (i = 0; ; i++) {
1800		PyObject *item = PySequence_GetItem(fromlist, i);
1801		int hasit;
1802		if (item == NULL) {
1803			if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1804				PyErr_Clear();
1805				return 1;
1806			}
1807			return 0;
1808		}
1809		if (!PyString_Check(item)) {
1810			PyErr_SetString(PyExc_TypeError,
1811					"Item in ``from list'' not a string");
1812			Py_DECREF(item);
1813			return 0;
1814		}
1815		if (PyString_AS_STRING(item)[0] == '*') {
1816			PyObject *all;
1817			Py_DECREF(item);
1818			/* See if the package defines __all__ */
1819			if (recursive)
1820				continue; /* Avoid endless recursion */
1821			all = PyObject_GetAttrString(mod, "__all__");
1822			if (all == NULL)
1823				PyErr_Clear();
1824			else {
1825				if (!ensure_fromlist(mod, all, buf, buflen, 1))
1826					return 0;
1827				Py_DECREF(all);
1828			}
1829			continue;
1830		}
1831		hasit = PyObject_HasAttr(mod, item);
1832		if (!hasit) {
1833			char *subname = PyString_AS_STRING(item);
1834			PyObject *submod;
1835			char *p;
1836			if (buflen + strlen(subname) >= MAXPATHLEN) {
1837				PyErr_SetString(PyExc_ValueError,
1838						"Module name too long");
1839				Py_DECREF(item);
1840				return 0;
1841			}
1842			p = buf + buflen;
1843			*p++ = '.';
1844			strcpy(p, subname);
1845			submod = import_submodule(mod, subname, buf);
1846			Py_XDECREF(submod);
1847			if (submod == NULL) {
1848				Py_DECREF(item);
1849				return 0;
1850			}
1851		}
1852		Py_DECREF(item);
1853	}
1854
1855	/* NOTREACHED */
1856}
1857
1858static PyObject *
1859import_submodule(PyObject *mod, char *subname, char *fullname)
1860{
1861	PyObject *modules = PyImport_GetModuleDict();
1862	PyObject *m, *res = NULL;
1863
1864	/* Require:
1865	   if mod == None: subname == fullname
1866	   else: mod.__name__ + "." + subname == fullname
1867	*/
1868
1869	if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
1870		Py_INCREF(m);
1871	}
1872	else {
1873		PyObject *path;
1874		char buf[MAXPATHLEN+1];
1875		struct filedescr *fdp;
1876		FILE *fp = NULL;
1877
1878		if (mod == Py_None)
1879			path = NULL;
1880		else {
1881			path = PyObject_GetAttrString(mod, "__path__");
1882			if (path == NULL) {
1883				PyErr_Clear();
1884				Py_INCREF(Py_None);
1885				return Py_None;
1886			}
1887		}
1888
1889		buf[0] = '\0';
1890		fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1891		Py_XDECREF(path);
1892		if (fdp == NULL) {
1893			if (!PyErr_ExceptionMatches(PyExc_ImportError))
1894				return NULL;
1895			PyErr_Clear();
1896			Py_INCREF(Py_None);
1897			return Py_None;
1898		}
1899		m = load_module(fullname, fp, buf, fdp->type);
1900		if (fp)
1901			fclose(fp);
1902		if (mod != Py_None) {
1903			/* Irrespective of the success of this load, make a
1904			   reference to it in the parent package module.
1905			   A copy gets saved in the modules dictionary
1906			   under the full name, so get a reference from
1907			   there, if need be.  (The exception is when
1908			   the load failed with a SyntaxError -- then
1909			   there's no trace in sys.modules.  In that case,
1910			   of course, do nothing extra.) */
1911			res = m;
1912			if (res == NULL)
1913				res = PyDict_GetItemString(modules, fullname);
1914			if (res != NULL &&
1915			    PyObject_SetAttrString(mod, subname, res) < 0) {
1916				Py_XDECREF(m);
1917				m = NULL;
1918			}
1919		}
1920	}
1921
1922	return m;
1923}
1924
1925
1926/* Re-import a module of any kind and return its module object, WITH
1927   INCREMENTED REFERENCE COUNT */
1928
1929PyObject *
1930PyImport_ReloadModule(PyObject *m)
1931{
1932	PyObject *modules = PyImport_GetModuleDict();
1933	PyObject *path = NULL;
1934	char *name, *subname;
1935	char buf[MAXPATHLEN+1];
1936	struct filedescr *fdp;
1937	FILE *fp = NULL;
1938
1939	if (m == NULL || !PyModule_Check(m)) {
1940		PyErr_SetString(PyExc_TypeError,
1941				"reload() argument must be module");
1942		return NULL;
1943	}
1944	name = PyModule_GetName(m);
1945	if (name == NULL)
1946		return NULL;
1947	if (m != PyDict_GetItemString(modules, name)) {
1948		PyErr_Format(PyExc_ImportError,
1949			     "reload(): module %.200s not in sys.modules",
1950			     name);
1951		return NULL;
1952	}
1953	subname = strrchr(name, '.');
1954	if (subname == NULL)
1955		subname = name;
1956	else {
1957		PyObject *parentname, *parent;
1958		parentname = PyString_FromStringAndSize(name, (subname-name));
1959		if (parentname == NULL)
1960			return NULL;
1961		parent = PyDict_GetItem(modules, parentname);
1962		Py_DECREF(parentname);
1963		if (parent == NULL) {
1964			PyErr_Format(PyExc_ImportError,
1965			    "reload(): parent %.200s not in sys.modules",
1966			    name);
1967			return NULL;
1968		}
1969		subname++;
1970		path = PyObject_GetAttrString(parent, "__path__");
1971		if (path == NULL)
1972			PyErr_Clear();
1973	}
1974	buf[0] = '\0';
1975	fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1976	Py_XDECREF(path);
1977	if (fdp == NULL)
1978		return NULL;
1979	m = load_module(name, fp, buf, fdp->type);
1980	if (fp)
1981		fclose(fp);
1982	return m;
1983}
1984
1985
1986/* Higher-level import emulator which emulates the "import" statement
1987   more accurately -- it invokes the __import__() function from the
1988   builtins of the current globals.  This means that the import is
1989   done using whatever import hooks are installed in the current
1990   environment, e.g. by "rexec".
1991   A dummy list ["__doc__"] is passed as the 4th argument so that
1992   e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1993   will return <module "gencache"> instead of <module "win32com">. */
1994
1995PyObject *
1996PyImport_Import(PyObject *module_name)
1997{
1998	static PyObject *silly_list = NULL;
1999	static PyObject *builtins_str = NULL;
2000	static PyObject *import_str = NULL;
2001	PyObject *globals = NULL;
2002	PyObject *import = NULL;
2003	PyObject *builtins = NULL;
2004	PyObject *r = NULL;
2005
2006	/* Initialize constant string objects */
2007	if (silly_list == NULL) {
2008		import_str = PyString_InternFromString("__import__");
2009		if (import_str == NULL)
2010			return NULL;
2011		builtins_str = PyString_InternFromString("__builtins__");
2012		if (builtins_str == NULL)
2013			return NULL;
2014		silly_list = Py_BuildValue("[s]", "__doc__");
2015		if (silly_list == NULL)
2016			return NULL;
2017	}
2018
2019	/* Get the builtins from current globals */
2020	globals = PyEval_GetGlobals();
2021	if (globals != NULL) {
2022	        Py_INCREF(globals);
2023		builtins = PyObject_GetItem(globals, builtins_str);
2024		if (builtins == NULL)
2025			goto err;
2026	}
2027	else {
2028		/* No globals -- use standard builtins, and fake globals */
2029		PyErr_Clear();
2030
2031		builtins = PyImport_ImportModuleEx("__builtin__",
2032						   NULL, NULL, NULL);
2033		if (builtins == NULL)
2034			return NULL;
2035		globals = Py_BuildValue("{OO}", builtins_str, builtins);
2036		if (globals == NULL)
2037			goto err;
2038	}
2039
2040	/* Get the __import__ function from the builtins */
2041	if (PyDict_Check(builtins)) {
2042		import = PyObject_GetItem(builtins, import_str);
2043		if (import == NULL)
2044			PyErr_SetObject(PyExc_KeyError, import_str);
2045	}
2046	else
2047		import = PyObject_GetAttr(builtins, import_str);
2048	if (import == NULL)
2049		goto err;
2050
2051	/* Call the _import__ function with the proper argument list */
2052	r = PyObject_CallFunction(import, "OOOO",
2053				  module_name, globals, globals, silly_list);
2054
2055  err:
2056	Py_XDECREF(globals);
2057	Py_XDECREF(builtins);
2058	Py_XDECREF(import);
2059
2060	return r;
2061}
2062
2063
2064/* Module 'imp' provides Python access to the primitives used for
2065   importing modules.
2066*/
2067
2068static PyObject *
2069imp_get_magic(PyObject *self, PyObject *args)
2070{
2071	char buf[4];
2072
2073	if (!PyArg_ParseTuple(args, ":get_magic"))
2074		return NULL;
2075	buf[0] = (char) ((pyc_magic >>  0) & 0xff);
2076	buf[1] = (char) ((pyc_magic >>  8) & 0xff);
2077	buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2078	buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2079
2080	return PyString_FromStringAndSize(buf, 4);
2081}
2082
2083static PyObject *
2084imp_get_suffixes(PyObject *self, PyObject *args)
2085{
2086	PyObject *list;
2087	struct filedescr *fdp;
2088
2089	if (!PyArg_ParseTuple(args, ":get_suffixes"))
2090		return NULL;
2091	list = PyList_New(0);
2092	if (list == NULL)
2093		return NULL;
2094	for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2095		PyObject *item = Py_BuildValue("ssi",
2096				       fdp->suffix, fdp->mode, fdp->type);
2097		if (item == NULL) {
2098			Py_DECREF(list);
2099			return NULL;
2100		}
2101		if (PyList_Append(list, item) < 0) {
2102			Py_DECREF(list);
2103			Py_DECREF(item);
2104			return NULL;
2105		}
2106		Py_DECREF(item);
2107	}
2108	return list;
2109}
2110
2111static PyObject *
2112call_find_module(char *name, PyObject *path)
2113{
2114	extern int fclose(FILE *);
2115	PyObject *fob, *ret;
2116	struct filedescr *fdp;
2117	char pathname[MAXPATHLEN+1];
2118	FILE *fp = NULL;
2119
2120	pathname[0] = '\0';
2121	if (path == Py_None)
2122		path = NULL;
2123	fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
2124	if (fdp == NULL)
2125		return NULL;
2126	if (fp != NULL) {
2127		fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2128		if (fob == NULL) {
2129			fclose(fp);
2130			return NULL;
2131		}
2132	}
2133	else {
2134		fob = Py_None;
2135		Py_INCREF(fob);
2136	}
2137	ret = Py_BuildValue("Os(ssi)",
2138		      fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2139	Py_DECREF(fob);
2140	return ret;
2141}
2142
2143static PyObject *
2144imp_find_module(PyObject *self, PyObject *args)
2145{
2146	char *name;
2147	PyObject *path = NULL;
2148	if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2149		return NULL;
2150	return call_find_module(name, path);
2151}
2152
2153static PyObject *
2154imp_init_builtin(PyObject *self, PyObject *args)
2155{
2156	char *name;
2157	int ret;
2158	PyObject *m;
2159	if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2160		return NULL;
2161	ret = init_builtin(name);
2162	if (ret < 0)
2163		return NULL;
2164	if (ret == 0) {
2165		Py_INCREF(Py_None);
2166		return Py_None;
2167	}
2168	m = PyImport_AddModule(name);
2169	Py_XINCREF(m);
2170	return m;
2171}
2172
2173static PyObject *
2174imp_init_frozen(PyObject *self, PyObject *args)
2175{
2176	char *name;
2177	int ret;
2178	PyObject *m;
2179	if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2180		return NULL;
2181	ret = PyImport_ImportFrozenModule(name);
2182	if (ret < 0)
2183		return NULL;
2184	if (ret == 0) {
2185		Py_INCREF(Py_None);
2186		return Py_None;
2187	}
2188	m = PyImport_AddModule(name);
2189	Py_XINCREF(m);
2190	return m;
2191}
2192
2193static PyObject *
2194imp_get_frozen_object(PyObject *self, PyObject *args)
2195{
2196	char *name;
2197
2198	if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2199		return NULL;
2200	return get_frozen_object(name);
2201}
2202
2203static PyObject *
2204imp_is_builtin(PyObject *self, PyObject *args)
2205{
2206	char *name;
2207	if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2208		return NULL;
2209	return PyInt_FromLong(is_builtin(name));
2210}
2211
2212static PyObject *
2213imp_is_frozen(PyObject *self, PyObject *args)
2214{
2215	char *name;
2216	struct _frozen *p;
2217	if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2218		return NULL;
2219	p = find_frozen(name);
2220	return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
2221}
2222
2223static FILE *
2224get_file(char *pathname, PyObject *fob, char *mode)
2225{
2226	FILE *fp;
2227	if (fob == NULL) {
2228		fp = fopen(pathname, mode);
2229		if (fp == NULL)
2230			PyErr_SetFromErrno(PyExc_IOError);
2231	}
2232	else {
2233		fp = PyFile_AsFile(fob);
2234		if (fp == NULL)
2235			PyErr_SetString(PyExc_ValueError,
2236					"bad/closed file object");
2237	}
2238	return fp;
2239}
2240
2241static PyObject *
2242imp_load_compiled(PyObject *self, PyObject *args)
2243{
2244	char *name;
2245	char *pathname;
2246	PyObject *fob = NULL;
2247	PyObject *m;
2248	FILE *fp;
2249	if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2250			      &PyFile_Type, &fob))
2251		return NULL;
2252	fp = get_file(pathname, fob, "rb");
2253	if (fp == NULL)
2254		return NULL;
2255	m = load_compiled_module(name, pathname, fp);
2256	if (fob == NULL)
2257		fclose(fp);
2258	return m;
2259}
2260
2261#ifdef HAVE_DYNAMIC_LOADING
2262
2263static PyObject *
2264imp_load_dynamic(PyObject *self, PyObject *args)
2265{
2266	char *name;
2267	char *pathname;
2268	PyObject *fob = NULL;
2269	PyObject *m;
2270	FILE *fp = NULL;
2271	if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2272			      &PyFile_Type, &fob))
2273		return NULL;
2274	if (fob) {
2275		fp = get_file(pathname, fob, "r");
2276		if (fp == NULL)
2277			return NULL;
2278	}
2279	m = _PyImport_LoadDynamicModule(name, pathname, fp);
2280	return m;
2281}
2282
2283#endif /* HAVE_DYNAMIC_LOADING */
2284
2285static PyObject *
2286imp_load_source(PyObject *self, PyObject *args)
2287{
2288	char *name;
2289	char *pathname;
2290	PyObject *fob = NULL;
2291	PyObject *m;
2292	FILE *fp;
2293	if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2294			      &PyFile_Type, &fob))
2295		return NULL;
2296	fp = get_file(pathname, fob, "r");
2297	if (fp == NULL)
2298		return NULL;
2299	m = load_source_module(name, pathname, fp);
2300	if (fob == NULL)
2301		fclose(fp);
2302	return m;
2303}
2304
2305#ifdef macintosh
2306static PyObject *
2307imp_load_resource(PyObject *self, PyObject *args)
2308{
2309	char *name;
2310	char *pathname;
2311	PyObject *m;
2312
2313	if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
2314		return NULL;
2315	m = PyMac_LoadResourceModule(name, pathname);
2316	return m;
2317}
2318#endif /* macintosh */
2319
2320static PyObject *
2321imp_load_module(PyObject *self, PyObject *args)
2322{
2323	char *name;
2324	PyObject *fob;
2325	char *pathname;
2326	char *suffix; /* Unused */
2327	char *mode;
2328	int type;
2329	FILE *fp;
2330
2331	if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2332			      &name, &fob, &pathname,
2333			      &suffix, &mode, &type))
2334		return NULL;
2335	if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
2336		PyErr_Format(PyExc_ValueError,
2337			     "invalid file open mode %.200s", mode);
2338		return NULL;
2339	}
2340	if (fob == Py_None)
2341		fp = NULL;
2342	else {
2343		if (!PyFile_Check(fob)) {
2344			PyErr_SetString(PyExc_ValueError,
2345				"load_module arg#2 should be a file or None");
2346			return NULL;
2347		}
2348		fp = get_file(pathname, fob, mode);
2349		if (fp == NULL)
2350			return NULL;
2351	}
2352	return load_module(name, fp, pathname, type);
2353}
2354
2355static PyObject *
2356imp_load_package(PyObject *self, PyObject *args)
2357{
2358	char *name;
2359	char *pathname;
2360	if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2361		return NULL;
2362	return load_package(name, pathname);
2363}
2364
2365static PyObject *
2366imp_new_module(PyObject *self, PyObject *args)
2367{
2368	char *name;
2369	if (!PyArg_ParseTuple(args, "s:new_module", &name))
2370		return NULL;
2371	return PyModule_New(name);
2372}
2373
2374/* Doc strings */
2375
2376static char doc_imp[] = "\
2377This module provides the components needed to build your own\n\
2378__import__ function.  Undocumented functions are obsolete.\n\
2379";
2380
2381static char doc_find_module[] = "\
2382find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2383Search for a module.  If path is omitted or None, search for a\n\
2384built-in, frozen or special module and continue search in sys.path.\n\
2385The module name cannot contain '.'; to search for a submodule of a\n\
2386package, pass the submodule name and the package's __path__.\
2387";
2388
2389static char doc_load_module[] = "\
2390load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2391Load a module, given information returned by find_module().\n\
2392The module name must include the full package name, if any.\
2393";
2394
2395static char doc_get_magic[] = "\
2396get_magic() -> string\n\
2397Return the magic number for .pyc or .pyo files.\
2398";
2399
2400static char doc_get_suffixes[] = "\
2401get_suffixes() -> [(suffix, mode, type), ...]\n\
2402Return a list of (suffix, mode, type) tuples describing the files\n\
2403that find_module() looks for.\
2404";
2405
2406static char doc_new_module[] = "\
2407new_module(name) -> module\n\
2408Create a new module.  Do not enter it in sys.modules.\n\
2409The module name must include the full package name, if any.\
2410";
2411
2412static char doc_lock_held[] = "\
2413lock_held() -> 0 or 1\n\
2414Return 1 if the import lock is currently held.\n\
2415On platforms without threads, return 0.\
2416";
2417
2418static PyMethodDef imp_methods[] = {
2419	{"find_module",		imp_find_module,	1, doc_find_module},
2420	{"get_magic",		imp_get_magic,		1, doc_get_magic},
2421	{"get_suffixes",	imp_get_suffixes,	1, doc_get_suffixes},
2422	{"load_module",		imp_load_module,	1, doc_load_module},
2423	{"new_module",		imp_new_module,		1, doc_new_module},
2424	{"lock_held",		imp_lock_held,		1, doc_lock_held},
2425	/* The rest are obsolete */
2426	{"get_frozen_object",	imp_get_frozen_object,	1},
2427	{"init_builtin",	imp_init_builtin,	1},
2428	{"init_frozen",		imp_init_frozen,	1},
2429	{"is_builtin",		imp_is_builtin,		1},
2430	{"is_frozen",		imp_is_frozen,		1},
2431	{"load_compiled",	imp_load_compiled,	1},
2432#ifdef HAVE_DYNAMIC_LOADING
2433	{"load_dynamic",	imp_load_dynamic,	1},
2434#endif
2435	{"load_package",	imp_load_package,	1},
2436#ifdef macintosh
2437	{"load_resource",	imp_load_resource,	1},
2438#endif
2439	{"load_source",		imp_load_source,	1},
2440	{NULL,			NULL}		/* sentinel */
2441};
2442
2443static int
2444setint(PyObject *d, char *name, int value)
2445{
2446	PyObject *v;
2447	int err;
2448
2449	v = PyInt_FromLong((long)value);
2450	err = PyDict_SetItemString(d, name, v);
2451	Py_XDECREF(v);
2452	return err;
2453}
2454
2455void
2456initimp(void)
2457{
2458	PyObject *m, *d;
2459
2460	m = Py_InitModule4("imp", imp_methods, doc_imp,
2461			   NULL, PYTHON_API_VERSION);
2462	d = PyModule_GetDict(m);
2463
2464	if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2465	if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2466	if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2467	if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2468	if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2469	if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2470	if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2471	if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2472	if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2473
2474  failure:
2475	;
2476}
2477
2478
2479/* API for embedding applications that want to add their own entries
2480   to the table of built-in modules.  This should normally be called
2481   *before* Py_Initialize().  When the table resize fails, -1 is
2482   returned and the existing table is unchanged.
2483
2484   After a similar function by Just van Rossum. */
2485
2486int
2487PyImport_ExtendInittab(struct _inittab *newtab)
2488{
2489	static struct _inittab *our_copy = NULL;
2490	struct _inittab *p;
2491	int i, n;
2492
2493	/* Count the number of entries in both tables */
2494	for (n = 0; newtab[n].name != NULL; n++)
2495		;
2496	if (n == 0)
2497		return 0; /* Nothing to do */
2498	for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2499		;
2500
2501	/* Allocate new memory for the combined table */
2502	p = our_copy;
2503	PyMem_RESIZE(p, struct _inittab, i+n+1);
2504	if (p == NULL)
2505		return -1;
2506
2507	/* Copy the tables into the new memory */
2508	if (our_copy != PyImport_Inittab)
2509		memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2510	PyImport_Inittab = our_copy = p;
2511	memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2512
2513	return 0;
2514}
2515
2516/* Shorthand to add a single entry given a name and a function */
2517
2518int
2519PyImport_AppendInittab(char *name, void (*initfunc)(void))
2520{
2521	struct _inittab newtab[2];
2522
2523	memset(newtab, '\0', sizeof newtab);
2524
2525	newtab[0].name = name;
2526	newtab[0].initfunc = initfunc;
2527
2528	return PyImport_ExtendInittab(newtab);
2529}
2530