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