Bump to 2.3.1 to pick up the missing file.
[python/dscho.git] / Python / import.c
blob52e6c05346ea755d46f2700e889ac3517c9a8524
2 /* Module definition and import implementation */
4 #include "Python.h"
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
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
22 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
23 /* In getmtime.c */
25 /* Magic word to reject .pyc files generated by other Python versions */
26 /* Change for each incompatible change */
27 /* The value of CR and LF is incorporated so if you ever read or write
28 a .pyc file in text mode the magic number will be wrong; also, the
29 Apple MPW compiler swaps their values, botching string constants.
30 XXX That probably isn't important anymore.
32 /* XXX Perhaps the magic number should be frozen and a version field
33 added to the .pyc file header? */
34 /* New way to come up with the low 16 bits of the magic number:
35 (YEAR-1995) * 10000 + MONTH * 100 + DAY
36 where MONTH and DAY are 1-based.
37 XXX Whatever the "old way" may have been isn't documented.
38 XXX This scheme breaks in 2002, as (2002-1995)*10000 = 70000 doesn't
39 fit in 16 bits.
40 XXX Later, sometimes 1 gets added to MAGIC in order to record that
41 the Unicode -U option is in use. IMO (Tim's), that's a Bad Idea
42 (quite apart from that the -U option doesn't work so isn't used
43 anyway).
45 XXX MAL, 2002-02-07: I had to modify the MAGIC due to a fix of the
46 UTF-8 encoder (it previously produced invalid UTF-8 for unpaired
47 high surrogates), so I simply bumped the month value to 20 (invalid
48 month) and set the day to 1. This should be recognizable by any
49 algorithm relying on the above scheme. Perhaps we should simply
50 start counting in increments of 10 from now on ?!
52 MWH, 2002-08-03: Removed SET_LINENO. Couldn't be bothered figuring
53 out the MAGIC schemes, so just incremented it by 10.
55 GvR, 2002-08-31: Because MWH changed the bytecode again, moved the
56 magic number *back* to 62011. This should get the snake-farm to
57 throw away its old .pyc files, amongst others.
59 Known values:
60 Python 1.5: 20121
61 Python 1.5.1: 20121
62 Python 1.5.2: 20121
63 Python 2.0: 50823
64 Python 2.0.1: 50823
65 Python 2.1: 60202
66 Python 2.1.1: 60202
67 Python 2.1.2: 60202
68 Python 2.2: 60717
69 Python 2.3a0: 62011
70 Python 2.3a0: 62021
71 Python 2.3a0: 62011 (!)
73 #define MAGIC (62011 | ((long)'\r'<<16) | ((long)'\n'<<24))
75 /* Magic word as global; note that _PyImport_Init() can change the
76 value of this global to accommodate for alterations of how the
77 compiler works which are enabled by command line switches. */
78 static long pyc_magic = MAGIC;
80 /* See _PyImport_FixupExtension() below */
81 static PyObject *extensions = NULL;
83 /* This table is defined in config.c: */
84 extern struct _inittab _PyImport_Inittab[];
86 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
88 /* these tables define the module suffixes that Python recognizes */
89 struct filedescr * _PyImport_Filetab = NULL;
91 #ifdef RISCOS
92 static const struct filedescr _PyImport_StandardFiletab[] = {
93 {"/py", "U", PY_SOURCE},
94 {"/pyc", "rb", PY_COMPILED},
95 {0, 0}
97 #else
98 static const struct filedescr _PyImport_StandardFiletab[] = {
99 {".py", "U", PY_SOURCE},
100 #ifdef MS_WINDOWS
101 {".pyw", "U", PY_SOURCE},
102 #endif
103 {".pyc", "rb", PY_COMPILED},
104 {0, 0}
106 #endif
108 /* Initialize things */
110 void
111 _PyImport_Init(void)
113 const struct filedescr *scan;
114 struct filedescr *filetab;
115 int countD = 0;
116 int countS = 0;
118 /* prepare _PyImport_Filetab: copy entries from
119 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
121 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
122 ++countD;
123 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
124 ++countS;
125 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
126 memcpy(filetab, _PyImport_DynLoadFiletab,
127 countD * sizeof(struct filedescr));
128 memcpy(filetab + countD, _PyImport_StandardFiletab,
129 countS * sizeof(struct filedescr));
130 filetab[countD + countS].suffix = NULL;
132 _PyImport_Filetab = filetab;
134 if (Py_OptimizeFlag) {
135 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
136 for (; filetab->suffix != NULL; filetab++) {
137 #ifndef RISCOS
138 if (strcmp(filetab->suffix, ".pyc") == 0)
139 filetab->suffix = ".pyo";
140 #else
141 if (strcmp(filetab->suffix, "/pyc") == 0)
142 filetab->suffix = "/pyo";
143 #endif
147 if (Py_UnicodeFlag) {
148 /* Fix the pyc_magic so that byte compiled code created
149 using the all-Unicode method doesn't interfere with
150 code created in normal operation mode. */
151 pyc_magic = MAGIC + 1;
155 void
156 _PyImport_Fini(void)
158 Py_XDECREF(extensions);
159 extensions = NULL;
160 PyMem_DEL(_PyImport_Filetab);
161 _PyImport_Filetab = NULL;
165 /* Locking primitives to prevent parallel imports of the same module
166 in different threads to return with a partially loaded module.
167 These calls are serialized by the global interpreter lock. */
169 #ifdef WITH_THREAD
171 #include "pythread.h"
173 static PyThread_type_lock import_lock = 0;
174 static long import_lock_thread = -1;
175 static int import_lock_level = 0;
177 static void
178 lock_import(void)
180 long me = PyThread_get_thread_ident();
181 if (me == -1)
182 return; /* Too bad */
183 if (import_lock == NULL)
184 import_lock = PyThread_allocate_lock();
185 if (import_lock_thread == me) {
186 import_lock_level++;
187 return;
189 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
190 PyThreadState *tstate = PyEval_SaveThread();
191 PyThread_acquire_lock(import_lock, 1);
192 PyEval_RestoreThread(tstate);
194 import_lock_thread = me;
195 import_lock_level = 1;
198 static void
199 unlock_import(void)
201 long me = PyThread_get_thread_ident();
202 if (me == -1)
203 return; /* Too bad */
204 if (import_lock_thread != me)
205 Py_FatalError("unlock_import: not holding the import lock");
206 import_lock_level--;
207 if (import_lock_level == 0) {
208 import_lock_thread = -1;
209 PyThread_release_lock(import_lock);
213 #else
215 #define lock_import()
216 #define unlock_import()
218 #endif
220 static PyObject *
221 imp_lock_held(PyObject *self, PyObject *args)
223 if (!PyArg_ParseTuple(args, ":lock_held"))
224 return NULL;
225 #ifdef WITH_THREAD
226 return PyBool_FromLong(import_lock_thread != -1);
227 #else
228 return PyBool_FromLong(0);
229 #endif
232 /* Helper for sys */
234 PyObject *
235 PyImport_GetModuleDict(void)
237 PyInterpreterState *interp = PyThreadState_Get()->interp;
238 if (interp->modules == NULL)
239 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
240 return interp->modules;
244 /* List of names to clear in sys */
245 static char* sys_deletes[] = {
246 "path", "argv", "ps1", "ps2", "exitfunc",
247 "exc_type", "exc_value", "exc_traceback",
248 "last_type", "last_value", "last_traceback",
249 NULL
252 static char* sys_files[] = {
253 "stdin", "__stdin__",
254 "stdout", "__stdout__",
255 "stderr", "__stderr__",
256 NULL
260 /* Un-initialize things, as good as we can */
262 void
263 PyImport_Cleanup(void)
265 int pos, ndone;
266 char *name;
267 PyObject *key, *value, *dict;
268 PyInterpreterState *interp = PyThreadState_Get()->interp;
269 PyObject *modules = interp->modules;
271 if (modules == NULL)
272 return; /* Already done */
274 /* Delete some special variables first. These are common
275 places where user values hide and people complain when their
276 destructors fail. Since the modules containing them are
277 deleted *last* of all, they would come too late in the normal
278 destruction order. Sigh. */
280 value = PyDict_GetItemString(modules, "__builtin__");
281 if (value != NULL && PyModule_Check(value)) {
282 dict = PyModule_GetDict(value);
283 if (Py_VerboseFlag)
284 PySys_WriteStderr("# clear __builtin__._\n");
285 PyDict_SetItemString(dict, "_", Py_None);
287 value = PyDict_GetItemString(modules, "sys");
288 if (value != NULL && PyModule_Check(value)) {
289 char **p;
290 PyObject *v;
291 dict = PyModule_GetDict(value);
292 for (p = sys_deletes; *p != NULL; p++) {
293 if (Py_VerboseFlag)
294 PySys_WriteStderr("# clear sys.%s\n", *p);
295 PyDict_SetItemString(dict, *p, Py_None);
297 for (p = sys_files; *p != NULL; p+=2) {
298 if (Py_VerboseFlag)
299 PySys_WriteStderr("# restore sys.%s\n", *p);
300 v = PyDict_GetItemString(dict, *(p+1));
301 if (v == NULL)
302 v = Py_None;
303 PyDict_SetItemString(dict, *p, v);
307 /* First, delete __main__ */
308 value = PyDict_GetItemString(modules, "__main__");
309 if (value != NULL && PyModule_Check(value)) {
310 if (Py_VerboseFlag)
311 PySys_WriteStderr("# cleanup __main__\n");
312 _PyModule_Clear(value);
313 PyDict_SetItemString(modules, "__main__", Py_None);
316 /* The special treatment of __builtin__ here is because even
317 when it's not referenced as a module, its dictionary is
318 referenced by almost every module's __builtins__. Since
319 deleting a module clears its dictionary (even if there are
320 references left to it), we need to delete the __builtin__
321 module last. Likewise, we don't delete sys until the very
322 end because it is implicitly referenced (e.g. by print).
324 Also note that we 'delete' modules by replacing their entry
325 in the modules dict with None, rather than really deleting
326 them; this avoids a rehash of the modules dictionary and
327 also marks them as "non existent" so they won't be
328 re-imported. */
330 /* Next, repeatedly delete modules with a reference count of
331 one (skipping __builtin__ and sys) and delete them */
332 do {
333 ndone = 0;
334 pos = 0;
335 while (PyDict_Next(modules, &pos, &key, &value)) {
336 if (value->ob_refcnt != 1)
337 continue;
338 if (PyString_Check(key) && PyModule_Check(value)) {
339 name = PyString_AS_STRING(key);
340 if (strcmp(name, "__builtin__") == 0)
341 continue;
342 if (strcmp(name, "sys") == 0)
343 continue;
344 if (Py_VerboseFlag)
345 PySys_WriteStderr(
346 "# cleanup[1] %s\n", name);
347 _PyModule_Clear(value);
348 PyDict_SetItem(modules, key, Py_None);
349 ndone++;
352 } while (ndone > 0);
354 /* Next, delete all modules (still skipping __builtin__ and sys) */
355 pos = 0;
356 while (PyDict_Next(modules, &pos, &key, &value)) {
357 if (PyString_Check(key) && PyModule_Check(value)) {
358 name = PyString_AS_STRING(key);
359 if (strcmp(name, "__builtin__") == 0)
360 continue;
361 if (strcmp(name, "sys") == 0)
362 continue;
363 if (Py_VerboseFlag)
364 PySys_WriteStderr("# cleanup[2] %s\n", name);
365 _PyModule_Clear(value);
366 PyDict_SetItem(modules, key, Py_None);
370 /* Next, delete sys and __builtin__ (in that order) */
371 value = PyDict_GetItemString(modules, "sys");
372 if (value != NULL && PyModule_Check(value)) {
373 if (Py_VerboseFlag)
374 PySys_WriteStderr("# cleanup sys\n");
375 _PyModule_Clear(value);
376 PyDict_SetItemString(modules, "sys", Py_None);
378 value = PyDict_GetItemString(modules, "__builtin__");
379 if (value != NULL && PyModule_Check(value)) {
380 if (Py_VerboseFlag)
381 PySys_WriteStderr("# cleanup __builtin__\n");
382 _PyModule_Clear(value);
383 PyDict_SetItemString(modules, "__builtin__", Py_None);
386 /* Finally, clear and delete the modules directory */
387 PyDict_Clear(modules);
388 interp->modules = NULL;
389 Py_DECREF(modules);
393 /* Helper for pythonrun.c -- return magic number */
395 long
396 PyImport_GetMagicNumber(void)
398 return pyc_magic;
402 /* Magic for extension modules (built-in as well as dynamically
403 loaded). To prevent initializing an extension module more than
404 once, we keep a static dictionary 'extensions' keyed by module name
405 (for built-in modules) or by filename (for dynamically loaded
406 modules), containing these modules. A copy of the module's
407 dictionary is stored by calling _PyImport_FixupExtension()
408 immediately after the module initialization function succeeds. A
409 copy can be retrieved from there by calling
410 _PyImport_FindExtension(). */
412 PyObject *
413 _PyImport_FixupExtension(char *name, char *filename)
415 PyObject *modules, *mod, *dict, *copy;
416 if (extensions == NULL) {
417 extensions = PyDict_New();
418 if (extensions == NULL)
419 return NULL;
421 modules = PyImport_GetModuleDict();
422 mod = PyDict_GetItemString(modules, name);
423 if (mod == NULL || !PyModule_Check(mod)) {
424 PyErr_Format(PyExc_SystemError,
425 "_PyImport_FixupExtension: module %.200s not loaded", name);
426 return NULL;
428 dict = PyModule_GetDict(mod);
429 if (dict == NULL)
430 return NULL;
431 copy = PyDict_Copy(dict);
432 if (copy == NULL)
433 return NULL;
434 PyDict_SetItemString(extensions, filename, copy);
435 Py_DECREF(copy);
436 return copy;
439 PyObject *
440 _PyImport_FindExtension(char *name, char *filename)
442 PyObject *dict, *mod, *mdict;
443 if (extensions == NULL)
444 return NULL;
445 dict = PyDict_GetItemString(extensions, filename);
446 if (dict == NULL)
447 return NULL;
448 mod = PyImport_AddModule(name);
449 if (mod == NULL)
450 return NULL;
451 mdict = PyModule_GetDict(mod);
452 if (mdict == NULL)
453 return NULL;
454 if (PyDict_Update(mdict, dict))
455 return NULL;
456 if (Py_VerboseFlag)
457 PySys_WriteStderr("import %s # previously loaded (%s)\n",
458 name, filename);
459 return mod;
463 /* Get the module object corresponding to a module name.
464 First check the modules dictionary if there's one there,
465 if not, create a new one and insert in in the modules dictionary.
466 Because the former action is most common, THIS DOES NOT RETURN A
467 'NEW' REFERENCE! */
469 PyObject *
470 PyImport_AddModule(char *name)
472 PyObject *modules = PyImport_GetModuleDict();
473 PyObject *m;
475 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
476 PyModule_Check(m))
477 return m;
478 m = PyModule_New(name);
479 if (m == NULL)
480 return NULL;
481 if (PyDict_SetItemString(modules, name, m) != 0) {
482 Py_DECREF(m);
483 return NULL;
485 Py_DECREF(m); /* Yes, it still exists, in modules! */
487 return m;
491 /* Execute a code object in a module and return the module object
492 WITH INCREMENTED REFERENCE COUNT */
494 PyObject *
495 PyImport_ExecCodeModule(char *name, PyObject *co)
497 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
500 PyObject *
501 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
503 PyObject *modules = PyImport_GetModuleDict();
504 PyObject *m, *d, *v;
506 m = PyImport_AddModule(name);
507 if (m == NULL)
508 return NULL;
509 d = PyModule_GetDict(m);
510 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
511 if (PyDict_SetItemString(d, "__builtins__",
512 PyEval_GetBuiltins()) != 0)
513 return NULL;
515 /* Remember the filename as the __file__ attribute */
516 v = NULL;
517 if (pathname != NULL) {
518 v = PyString_FromString(pathname);
519 if (v == NULL)
520 PyErr_Clear();
522 if (v == NULL) {
523 v = ((PyCodeObject *)co)->co_filename;
524 Py_INCREF(v);
526 if (PyDict_SetItemString(d, "__file__", v) != 0)
527 PyErr_Clear(); /* Not important enough to report */
528 Py_DECREF(v);
530 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
531 if (v == NULL)
532 return NULL;
533 Py_DECREF(v);
535 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
536 PyErr_Format(PyExc_ImportError,
537 "Loaded module %.200s not found in sys.modules",
538 name);
539 return NULL;
542 Py_INCREF(m);
544 return m;
548 /* Given a pathname for a Python source file, fill a buffer with the
549 pathname for the corresponding compiled file. Return the pathname
550 for the compiled file, or NULL if there's no space in the buffer.
551 Doesn't set an exception. */
553 static char *
554 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
556 size_t len = strlen(pathname);
557 if (len+2 > buflen)
558 return NULL;
560 #ifdef MS_WINDOWS
561 /* Treat .pyw as if it were .py. The case of ".pyw" must match
562 that used in _PyImport_StandardFiletab. */
563 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
564 --len; /* pretend 'w' isn't there */
565 #endif
566 memcpy(buf, pathname, len);
567 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
568 buf[len+1] = '\0';
570 return buf;
574 /* Given a pathname for a Python source file, its time of last
575 modification, and a pathname for a compiled file, check whether the
576 compiled file represents the same version of the source. If so,
577 return a FILE pointer for the compiled file, positioned just after
578 the header; if not, return NULL.
579 Doesn't set an exception. */
581 static FILE *
582 check_compiled_module(char *pathname, long mtime, char *cpathname)
584 FILE *fp;
585 long magic;
586 long pyc_mtime;
588 fp = fopen(cpathname, "rb");
589 if (fp == NULL)
590 return NULL;
591 magic = PyMarshal_ReadLongFromFile(fp);
592 if (magic != pyc_magic) {
593 if (Py_VerboseFlag)
594 PySys_WriteStderr("# %s has bad magic\n", cpathname);
595 fclose(fp);
596 return NULL;
598 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
599 if (pyc_mtime != mtime) {
600 if (Py_VerboseFlag)
601 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
602 fclose(fp);
603 return NULL;
605 if (Py_VerboseFlag)
606 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
607 return fp;
611 /* Read a code object from a file and check it for validity */
613 static PyCodeObject *
614 read_compiled_module(char *cpathname, FILE *fp)
616 PyObject *co;
618 co = PyMarshal_ReadLastObjectFromFile(fp);
619 /* Ugly: rd_object() may return NULL with or without error */
620 if (co == NULL || !PyCode_Check(co)) {
621 if (!PyErr_Occurred())
622 PyErr_Format(PyExc_ImportError,
623 "Non-code object in %.200s", cpathname);
624 Py_XDECREF(co);
625 return NULL;
627 return (PyCodeObject *)co;
631 /* Load a module from a compiled file, execute it, and return its
632 module object WITH INCREMENTED REFERENCE COUNT */
634 static PyObject *
635 load_compiled_module(char *name, char *cpathname, FILE *fp)
637 long magic;
638 PyCodeObject *co;
639 PyObject *m;
641 magic = PyMarshal_ReadLongFromFile(fp);
642 if (magic != pyc_magic) {
643 PyErr_Format(PyExc_ImportError,
644 "Bad magic number in %.200s", cpathname);
645 return NULL;
647 (void) PyMarshal_ReadLongFromFile(fp);
648 co = read_compiled_module(cpathname, fp);
649 if (co == NULL)
650 return NULL;
651 if (Py_VerboseFlag)
652 PySys_WriteStderr("import %s # precompiled from %s\n",
653 name, cpathname);
654 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
655 Py_DECREF(co);
657 return m;
660 /* Parse a source file and return the corresponding code object */
662 static PyCodeObject *
663 parse_source_module(char *pathname, FILE *fp)
665 PyCodeObject *co;
666 node *n;
668 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
669 if (n == NULL)
670 return NULL;
671 co = PyNode_Compile(n, pathname);
672 PyNode_Free(n);
674 return co;
678 /* Helper to open a bytecode file for writing in exclusive mode */
680 static FILE *
681 open_exclusive(char *filename)
683 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
684 /* Use O_EXCL to avoid a race condition when another process tries to
685 write the same file. When that happens, our open() call fails,
686 which is just fine (since it's only a cache).
687 XXX If the file exists and is writable but the directory is not
688 writable, the file will never be written. Oh well.
690 int fd;
691 (void) unlink(filename);
692 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
693 #ifdef O_BINARY
694 |O_BINARY /* necessary for Windows */
695 #endif
697 , 0666);
698 if (fd < 0)
699 return NULL;
700 return fdopen(fd, "wb");
701 #else
702 /* Best we can do -- on Windows this can't happen anyway */
703 return fopen(filename, "wb");
704 #endif
708 /* Write a compiled module to a file, placing the time of last
709 modification of its source into the header.
710 Errors are ignored, if a write error occurs an attempt is made to
711 remove the file. */
713 static void
714 write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
716 FILE *fp;
718 fp = open_exclusive(cpathname);
719 if (fp == NULL) {
720 if (Py_VerboseFlag)
721 PySys_WriteStderr(
722 "# can't create %s\n", cpathname);
723 return;
725 PyMarshal_WriteLongToFile(pyc_magic, fp);
726 /* First write a 0 for mtime */
727 PyMarshal_WriteLongToFile(0L, fp);
728 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
729 if (ferror(fp)) {
730 if (Py_VerboseFlag)
731 PySys_WriteStderr("# can't write %s\n", cpathname);
732 /* Don't keep partial file */
733 fclose(fp);
734 (void) unlink(cpathname);
735 return;
737 /* Now write the true mtime */
738 fseek(fp, 4L, 0);
739 PyMarshal_WriteLongToFile(mtime, fp);
740 fflush(fp);
741 fclose(fp);
742 if (Py_VerboseFlag)
743 PySys_WriteStderr("# wrote %s\n", cpathname);
744 #ifdef macintosh
745 PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
746 #endif
750 /* Load a source module from a given file and return its module
751 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
752 byte-compiled file, use that instead. */
754 static PyObject *
755 load_source_module(char *name, char *pathname, FILE *fp)
757 time_t mtime;
758 FILE *fpc;
759 char buf[MAXPATHLEN+1];
760 char *cpathname;
761 PyCodeObject *co;
762 PyObject *m;
764 mtime = PyOS_GetLastModificationTime(pathname, fp);
765 if (mtime == (time_t)(-1))
766 return NULL;
767 #if SIZEOF_TIME_T > 4
768 /* Python's .pyc timestamp handling presumes that the timestamp fits
769 in 4 bytes. This will be fine until sometime in the year 2038,
770 when a 4-byte signed time_t will overflow.
772 if (mtime >> 32) {
773 PyErr_SetString(PyExc_OverflowError,
774 "modification time overflows a 4 byte field");
775 return NULL;
777 #endif
778 cpathname = make_compiled_pathname(pathname, buf,
779 (size_t)MAXPATHLEN + 1);
780 if (cpathname != NULL &&
781 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
782 co = read_compiled_module(cpathname, fpc);
783 fclose(fpc);
784 if (co == NULL)
785 return NULL;
786 if (Py_VerboseFlag)
787 PySys_WriteStderr("import %s # precompiled from %s\n",
788 name, cpathname);
789 pathname = cpathname;
791 else {
792 co = parse_source_module(pathname, fp);
793 if (co == NULL)
794 return NULL;
795 if (Py_VerboseFlag)
796 PySys_WriteStderr("import %s # from %s\n",
797 name, pathname);
798 write_compiled_module(co, cpathname, mtime);
800 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
801 Py_DECREF(co);
803 return m;
807 /* Forward */
808 static PyObject *load_module(char *, FILE *, char *, int);
809 static struct filedescr *find_module(char *, PyObject *,
810 char *, size_t, FILE **);
811 static struct _frozen *find_frozen(char *name);
813 /* Load a package and return its module object WITH INCREMENTED
814 REFERENCE COUNT */
816 static PyObject *
817 load_package(char *name, char *pathname)
819 PyObject *m, *d, *file, *path;
820 int err;
821 char buf[MAXPATHLEN+1];
822 FILE *fp = NULL;
823 struct filedescr *fdp;
825 m = PyImport_AddModule(name);
826 if (m == NULL)
827 return NULL;
828 if (Py_VerboseFlag)
829 PySys_WriteStderr("import %s # directory %s\n",
830 name, pathname);
831 d = PyModule_GetDict(m);
832 file = PyString_FromString(pathname);
833 if (file == NULL)
834 return NULL;
835 path = Py_BuildValue("[O]", file);
836 if (path == NULL) {
837 Py_DECREF(file);
838 return NULL;
840 err = PyDict_SetItemString(d, "__file__", file);
841 if (err == 0)
842 err = PyDict_SetItemString(d, "__path__", path);
843 if (err != 0) {
844 m = NULL;
845 goto cleanup;
847 buf[0] = '\0';
848 fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
849 if (fdp == NULL) {
850 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
851 PyErr_Clear();
853 else
854 m = NULL;
855 goto cleanup;
857 m = load_module(name, fp, buf, fdp->type);
858 if (fp != NULL)
859 fclose(fp);
860 cleanup:
861 Py_XDECREF(path);
862 Py_XDECREF(file);
863 return m;
867 /* Helper to test for built-in module */
869 static int
870 is_builtin(char *name)
872 int i;
873 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
874 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
875 if (PyImport_Inittab[i].initfunc == NULL)
876 return -1;
877 else
878 return 1;
881 return 0;
885 /* Search the path (default sys.path) for a module. Return the
886 corresponding filedescr struct, and (via return arguments) the
887 pathname and an open file. Return NULL if the module is not found. */
889 #ifdef MS_COREDLL
890 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
891 char *, int);
892 #endif
894 static int case_ok(char *, int, int, char *);
895 static int find_init_module(char *); /* Forward */
897 static struct filedescr *
898 find_module(char *realname, PyObject *path, char *buf, size_t buflen,
899 FILE **p_fp)
901 int i, npath;
902 size_t len, namelen;
903 struct filedescr *fdp = NULL;
904 char *filemode;
905 FILE *fp = NULL;
906 #ifndef RISCOS
907 struct stat statbuf;
908 #endif
909 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
910 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
911 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
912 char name[MAXPATHLEN+1];
913 #if defined(PYOS_OS2)
914 size_t saved_len;
915 size_t saved_namelen;
916 char *saved_buf = NULL;
917 #endif
919 if (strlen(realname) > MAXPATHLEN) {
920 PyErr_SetString(PyExc_OverflowError,
921 "module name is too long");
922 return NULL;
924 strcpy(name, realname);
926 if (path != NULL && PyString_Check(path)) {
927 /* The only type of submodule allowed inside a "frozen"
928 package are other frozen modules or packages. */
929 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
930 PyErr_SetString(PyExc_ImportError,
931 "full frozen module name too long");
932 return NULL;
934 strcpy(buf, PyString_AsString(path));
935 strcat(buf, ".");
936 strcat(buf, name);
937 strcpy(name, buf);
938 #ifdef macintosh
939 /* Freezing on the mac works different, and the modules are
940 ** actually on sys.path. So we don't take the quick exit but
941 ** continue with the normal flow.
943 path = NULL;
944 #else
945 if (find_frozen(name) != NULL) {
946 strcpy(buf, name);
947 return &fd_frozen;
949 PyErr_Format(PyExc_ImportError,
950 "No frozen submodule named %.200s", name);
951 return NULL;
952 #endif
954 if (path == NULL) {
955 if (is_builtin(name)) {
956 strcpy(buf, name);
957 return &fd_builtin;
959 if ((find_frozen(name)) != NULL) {
960 strcpy(buf, name);
961 return &fd_frozen;
964 #ifdef MS_COREDLL
965 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
966 if (fp != NULL) {
967 *p_fp = fp;
968 return fdp;
970 #endif
971 path = PySys_GetObject("path");
973 if (path == NULL || !PyList_Check(path)) {
974 PyErr_SetString(PyExc_ImportError,
975 "sys.path must be a list of directory names");
976 return NULL;
978 npath = PyList_Size(path);
979 namelen = strlen(name);
980 for (i = 0; i < npath; i++) {
981 PyObject *copy = NULL;
982 PyObject *v = PyList_GetItem(path, i);
983 #ifdef Py_USING_UNICODE
984 if (PyUnicode_Check(v)) {
985 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
986 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
987 if (copy == NULL)
988 return NULL;
989 v = copy;
991 else
992 #endif
993 if (!PyString_Check(v))
994 continue;
995 len = PyString_Size(v);
996 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
997 Py_XDECREF(copy);
998 continue; /* Too long */
1000 strcpy(buf, PyString_AsString(v));
1001 if (strlen(buf) != len) {
1002 Py_XDECREF(copy);
1003 continue; /* v contains '\0' */
1005 #ifdef macintosh
1007 ** Speedup: each sys.path item is interned, and
1008 ** FindResourceModule remembers which items refer to
1009 ** folders (so we don't have to bother trying to look
1010 ** into them for resources).
1012 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
1013 v = PyList_GET_ITEM(path, i);
1014 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
1015 static struct filedescr resfiledescr =
1016 {"", "", PY_RESOURCE};
1018 Py_XDECREF(copy);
1019 return &resfiledescr;
1021 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
1022 static struct filedescr resfiledescr =
1023 {"", "", PY_CODERESOURCE};
1025 Py_XDECREF(copy);
1026 return &resfiledescr;
1028 #endif
1029 if (len > 0 && buf[len-1] != SEP
1030 #ifdef ALTSEP
1031 && buf[len-1] != ALTSEP
1032 #endif
1034 buf[len++] = SEP;
1035 strcpy(buf+len, name);
1036 len += namelen;
1038 /* Check for package import (buf holds a directory name,
1039 and there's an __init__ module in that directory */
1040 #ifdef HAVE_STAT
1041 if (stat(buf, &statbuf) == 0 && /* it exists */
1042 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1043 find_init_module(buf) && /* it has __init__.py */
1044 case_ok(buf, len, namelen, name)) { /* and case matches */
1045 Py_XDECREF(copy);
1046 return &fd_package;
1048 #else
1049 /* XXX How are you going to test for directories? */
1050 #ifdef RISCOS
1051 if (isdir(buf) &&
1052 find_init_module(buf) &&
1053 case_ok(buf, len, namelen, name)) {
1054 Py_XDECREF(copy);
1055 return &fd_package;
1057 #endif
1058 #endif
1059 #ifdef macintosh
1060 fdp = PyMac_FindModuleExtension(buf, &len, name);
1061 if (fdp) {
1062 #else
1063 #if defined(PYOS_OS2)
1064 /* take a snapshot of the module spec for restoration
1065 * after the 8 character DLL hackery
1067 saved_buf = strdup(buf);
1068 saved_len = len;
1069 saved_namelen = namelen;
1070 #endif /* PYOS_OS2 */
1071 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1072 #if defined(PYOS_OS2)
1073 /* OS/2 limits DLLs to 8 character names (w/o
1074 extension)
1075 * so if the name is longer than that and its a
1076 * dynamically loaded module we're going to try,
1077 * truncate the name before trying
1079 if (strlen(realname) > 8) {
1080 /* is this an attempt to load a C extension? */
1081 const struct filedescr *scan;
1082 scan = _PyImport_DynLoadFiletab;
1083 while (scan->suffix != NULL) {
1084 if (!strcmp(scan->suffix, fdp->suffix))
1085 break;
1086 else
1087 scan++;
1089 if (scan->suffix != NULL) {
1090 /* yes, so truncate the name */
1091 namelen = 8;
1092 len -= strlen(realname) - namelen;
1093 buf[len] = '\0';
1096 #endif /* PYOS_OS2 */
1097 strcpy(buf+len, fdp->suffix);
1098 if (Py_VerboseFlag > 1)
1099 PySys_WriteStderr("# trying %s\n", buf);
1100 #endif /* !macintosh */
1101 filemode = fdp->mode;
1102 if (filemode[0] == 'U')
1103 filemode = "r" PY_STDIOTEXTMODE;
1104 fp = fopen(buf, filemode);
1105 if (fp != NULL) {
1106 if (case_ok(buf, len, namelen, name))
1107 break;
1108 else { /* continue search */
1109 fclose(fp);
1110 fp = NULL;
1113 #if defined(PYOS_OS2)
1114 /* restore the saved snapshot */
1115 strcpy(buf, saved_buf);
1116 len = saved_len;
1117 namelen = saved_namelen;
1118 #endif
1120 #if defined(PYOS_OS2)
1121 /* don't need/want the module name snapshot anymore */
1122 if (saved_buf)
1124 free(saved_buf);
1125 saved_buf = NULL;
1127 #endif
1128 Py_XDECREF(copy);
1129 if (fp != NULL)
1130 break;
1132 if (fp == NULL) {
1133 PyErr_Format(PyExc_ImportError,
1134 "No module named %.200s", name);
1135 return NULL;
1137 *p_fp = fp;
1138 return fdp;
1141 /* case_ok(char* buf, int len, int namelen, char* name)
1142 * The arguments here are tricky, best shown by example:
1143 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1144 * ^ ^ ^ ^
1145 * |--------------------- buf ---------------------|
1146 * |------------------- len ------------------|
1147 * |------ name -------|
1148 * |----- namelen -----|
1149 * buf is the full path, but len only counts up to (& exclusive of) the
1150 * extension. name is the module name, also exclusive of extension.
1152 * We've already done a successful stat() or fopen() on buf, so know that
1153 * there's some match, possibly case-insensitive.
1155 * case_ok() is to return 1 if there's a case-sensitive match for
1156 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1157 * exists.
1159 * case_ok() is used to implement case-sensitive import semantics even
1160 * on platforms with case-insensitive filesystems. It's trivial to implement
1161 * for case-sensitive filesystems. It's pretty much a cross-platform
1162 * nightmare for systems with case-insensitive filesystems.
1165 /* First we may need a pile of platform-specific header files; the sequence
1166 * of #if's here should match the sequence in the body of case_ok().
1168 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1169 #include <windows.h>
1170 #ifdef __CYGWIN__
1171 #include <sys/cygwin.h>
1172 #endif
1174 #elif defined(DJGPP)
1175 #include <dir.h>
1177 #elif defined(macintosh)
1178 #include <TextUtils.h>
1180 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1181 #include <sys/types.h>
1182 #include <dirent.h>
1184 #elif defined(PYOS_OS2)
1185 #define INCL_DOS
1186 #define INCL_DOSERRORS
1187 #define INCL_NOPMAPI
1188 #include <os2.h>
1190 #elif defined(RISCOS)
1191 #include "oslib/osfscontrol.h"
1192 #endif
1194 static int
1195 case_ok(char *buf, int len, int namelen, char *name)
1197 /* Pick a platform-specific implementation; the sequence of #if's here should
1198 * match the sequence just above.
1201 /* MS_WINDOWS || __CYGWIN__ */
1202 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1203 WIN32_FIND_DATA data;
1204 HANDLE h;
1205 #ifdef __CYGWIN__
1206 char tempbuf[MAX_PATH];
1207 #endif
1209 if (Py_GETENV("PYTHONCASEOK") != NULL)
1210 return 1;
1212 #ifdef __CYGWIN__
1213 cygwin32_conv_to_win32_path(buf, tempbuf);
1214 h = FindFirstFile(tempbuf, &data);
1215 #else
1216 h = FindFirstFile(buf, &data);
1217 #endif
1218 if (h == INVALID_HANDLE_VALUE) {
1219 PyErr_Format(PyExc_NameError,
1220 "Can't find file for module %.100s\n(filename %.300s)",
1221 name, buf);
1222 return 0;
1224 FindClose(h);
1225 return strncmp(data.cFileName, name, namelen) == 0;
1227 /* DJGPP */
1228 #elif defined(DJGPP)
1229 struct ffblk ffblk;
1230 int done;
1232 if (Py_GETENV("PYTHONCASEOK") != NULL)
1233 return 1;
1235 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1236 if (done) {
1237 PyErr_Format(PyExc_NameError,
1238 "Can't find file for module %.100s\n(filename %.300s)",
1239 name, buf);
1240 return 0;
1242 return strncmp(ffblk.ff_name, name, namelen) == 0;
1244 /* macintosh */
1245 #elif defined(macintosh)
1246 FSSpec fss;
1247 OSErr err;
1249 if (Py_GETENV("PYTHONCASEOK") != NULL)
1250 return 1;
1252 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
1253 if (err) {
1254 PyErr_Format(PyExc_NameError,
1255 "Can't find file for module %.100s\n(filename %.300s)",
1256 name, buf);
1257 return 0;
1259 return fss.name[0] >= namelen &&
1260 strncmp(name, (char *)fss.name+1, namelen) == 0;
1262 /* new-fangled macintosh (macosx) */
1263 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1264 DIR *dirp;
1265 struct dirent *dp;
1266 char dirname[MAXPATHLEN + 1];
1267 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1269 if (Py_GETENV("PYTHONCASEOK") != NULL)
1270 return 1;
1272 /* Copy the dir component into dirname; substitute "." if empty */
1273 if (dirlen <= 0) {
1274 dirname[0] = '.';
1275 dirname[1] = '\0';
1277 else {
1278 assert(dirlen <= MAXPATHLEN);
1279 memcpy(dirname, buf, dirlen);
1280 dirname[dirlen] = '\0';
1282 /* Open the directory and search the entries for an exact match. */
1283 dirp = opendir(dirname);
1284 if (dirp) {
1285 char *nameWithExt = buf + len - namelen;
1286 while ((dp = readdir(dirp)) != NULL) {
1287 const int thislen =
1288 #ifdef _DIRENT_HAVE_D_NAMELEN
1289 dp->d_namlen;
1290 #else
1291 strlen(dp->d_name);
1292 #endif
1293 if (thislen >= namelen &&
1294 strcmp(dp->d_name, nameWithExt) == 0) {
1295 (void)closedir(dirp);
1296 return 1; /* Found */
1299 (void)closedir(dirp);
1301 return 0 ; /* Not found */
1303 /* RISC OS */
1304 #elif defined(RISCOS)
1305 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1306 char buf2[MAXPATHLEN+2];
1307 char *nameWithExt = buf+len-namelen;
1308 int canonlen;
1309 os_error *e;
1311 if (Py_GETENV("PYTHONCASEOK") != NULL)
1312 return 1;
1314 /* workaround:
1315 append wildcard, otherwise case of filename wouldn't be touched */
1316 strcpy(buf2, buf);
1317 strcat(buf2, "*");
1319 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1320 canonlen = MAXPATHLEN+1-canonlen;
1321 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1322 return 0;
1323 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1324 return 1; /* match */
1326 return 0;
1328 /* OS/2 */
1329 #elif defined(PYOS_OS2)
1330 HDIR hdir = 1;
1331 ULONG srchcnt = 1;
1332 FILEFINDBUF3 ffbuf;
1333 APIRET rc;
1335 if (getenv("PYTHONCASEOK") != NULL)
1336 return 1;
1338 rc = DosFindFirst(buf,
1339 &hdir,
1340 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1341 &ffbuf, sizeof(ffbuf),
1342 &srchcnt,
1343 FIL_STANDARD);
1344 if (rc != NO_ERROR)
1345 return 0;
1346 return strncmp(ffbuf.achName, name, namelen) == 0;
1348 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1349 #else
1350 return 1;
1352 #endif
1356 #ifdef HAVE_STAT
1357 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1358 static int
1359 find_init_module(char *buf)
1361 const size_t save_len = strlen(buf);
1362 size_t i = save_len;
1363 char *pname; /* pointer to start of __init__ */
1364 struct stat statbuf;
1366 /* For calling case_ok(buf, len, namelen, name):
1367 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1368 * ^ ^ ^ ^
1369 * |--------------------- buf ---------------------|
1370 * |------------------- len ------------------|
1371 * |------ name -------|
1372 * |----- namelen -----|
1374 if (save_len + 13 >= MAXPATHLEN)
1375 return 0;
1376 buf[i++] = SEP;
1377 pname = buf + i;
1378 strcpy(pname, "__init__.py");
1379 if (stat(buf, &statbuf) == 0) {
1380 if (case_ok(buf,
1381 save_len + 9, /* len("/__init__") */
1382 8, /* len("__init__") */
1383 pname)) {
1384 buf[save_len] = '\0';
1385 return 1;
1388 i += strlen(pname);
1389 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1390 if (stat(buf, &statbuf) == 0) {
1391 if (case_ok(buf,
1392 save_len + 9, /* len("/__init__") */
1393 8, /* len("__init__") */
1394 pname)) {
1395 buf[save_len] = '\0';
1396 return 1;
1399 buf[save_len] = '\0';
1400 return 0;
1403 #else
1405 #ifdef RISCOS
1406 static int
1407 find_init_module(buf)
1408 char *buf;
1410 int save_len = strlen(buf);
1411 int i = save_len;
1413 if (save_len + 13 >= MAXPATHLEN)
1414 return 0;
1415 buf[i++] = SEP;
1416 strcpy(buf+i, "__init__/py");
1417 if (isfile(buf)) {
1418 buf[save_len] = '\0';
1419 return 1;
1422 if (Py_OptimizeFlag)
1423 strcpy(buf+i, "o");
1424 else
1425 strcpy(buf+i, "c");
1426 if (isfile(buf)) {
1427 buf[save_len] = '\0';
1428 return 1;
1430 buf[save_len] = '\0';
1431 return 0;
1433 #endif /*RISCOS*/
1435 #endif /* HAVE_STAT */
1438 static int init_builtin(char *); /* Forward */
1440 /* Load an external module using the default search path and return
1441 its module object WITH INCREMENTED REFERENCE COUNT */
1443 static PyObject *
1444 load_module(char *name, FILE *fp, char *buf, int type)
1446 PyObject *modules;
1447 PyObject *m;
1448 int err;
1450 /* First check that there's an open file (if we need one) */
1451 switch (type) {
1452 case PY_SOURCE:
1453 case PY_COMPILED:
1454 if (fp == NULL) {
1455 PyErr_Format(PyExc_ValueError,
1456 "file object required for import (type code %d)",
1457 type);
1458 return NULL;
1462 switch (type) {
1464 case PY_SOURCE:
1465 m = load_source_module(name, buf, fp);
1466 break;
1468 case PY_COMPILED:
1469 m = load_compiled_module(name, buf, fp);
1470 break;
1472 #ifdef HAVE_DYNAMIC_LOADING
1473 case C_EXTENSION:
1474 m = _PyImport_LoadDynamicModule(name, buf, fp);
1475 break;
1476 #endif
1478 #ifdef macintosh
1479 case PY_RESOURCE:
1480 m = PyMac_LoadResourceModule(name, buf);
1481 break;
1482 case PY_CODERESOURCE:
1483 m = PyMac_LoadCodeResourceModule(name, buf);
1484 break;
1485 #endif
1487 case PKG_DIRECTORY:
1488 m = load_package(name, buf);
1489 break;
1491 case C_BUILTIN:
1492 case PY_FROZEN:
1493 if (buf != NULL && buf[0] != '\0')
1494 name = buf;
1495 if (type == C_BUILTIN)
1496 err = init_builtin(name);
1497 else
1498 err = PyImport_ImportFrozenModule(name);
1499 if (err < 0)
1500 return NULL;
1501 if (err == 0) {
1502 PyErr_Format(PyExc_ImportError,
1503 "Purported %s module %.200s not found",
1504 type == C_BUILTIN ?
1505 "builtin" : "frozen",
1506 name);
1507 return NULL;
1509 modules = PyImport_GetModuleDict();
1510 m = PyDict_GetItemString(modules, name);
1511 if (m == NULL) {
1512 PyErr_Format(
1513 PyExc_ImportError,
1514 "%s module %.200s not properly initialized",
1515 type == C_BUILTIN ?
1516 "builtin" : "frozen",
1517 name);
1518 return NULL;
1520 Py_INCREF(m);
1521 break;
1523 default:
1524 PyErr_Format(PyExc_ImportError,
1525 "Don't know how to import %.200s (type code %d)",
1526 name, type);
1527 m = NULL;
1531 return m;
1535 /* Initialize a built-in module.
1536 Return 1 for succes, 0 if the module is not found, and -1 with
1537 an exception set if the initialization failed. */
1539 static int
1540 init_builtin(char *name)
1542 struct _inittab *p;
1544 if (_PyImport_FindExtension(name, name) != NULL)
1545 return 1;
1547 for (p = PyImport_Inittab; p->name != NULL; p++) {
1548 if (strcmp(name, p->name) == 0) {
1549 if (p->initfunc == NULL) {
1550 PyErr_Format(PyExc_ImportError,
1551 "Cannot re-init internal module %.200s",
1552 name);
1553 return -1;
1555 if (Py_VerboseFlag)
1556 PySys_WriteStderr("import %s # builtin\n", name);
1557 (*p->initfunc)();
1558 if (PyErr_Occurred())
1559 return -1;
1560 if (_PyImport_FixupExtension(name, name) == NULL)
1561 return -1;
1562 return 1;
1565 return 0;
1569 /* Frozen modules */
1571 static struct _frozen *
1572 find_frozen(char *name)
1574 struct _frozen *p;
1576 for (p = PyImport_FrozenModules; ; p++) {
1577 if (p->name == NULL)
1578 return NULL;
1579 if (strcmp(p->name, name) == 0)
1580 break;
1582 return p;
1585 static PyObject *
1586 get_frozen_object(char *name)
1588 struct _frozen *p = find_frozen(name);
1589 int size;
1591 if (p == NULL) {
1592 PyErr_Format(PyExc_ImportError,
1593 "No such frozen object named %.200s",
1594 name);
1595 return NULL;
1597 if (p->code == NULL) {
1598 PyErr_Format(PyExc_ImportError,
1599 "Excluded frozen object named %.200s",
1600 name);
1601 return NULL;
1603 size = p->size;
1604 if (size < 0)
1605 size = -size;
1606 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1609 /* Initialize a frozen module.
1610 Return 1 for succes, 0 if the module is not found, and -1 with
1611 an exception set if the initialization failed.
1612 This function is also used from frozenmain.c */
1615 PyImport_ImportFrozenModule(char *name)
1617 struct _frozen *p = find_frozen(name);
1618 PyObject *co;
1619 PyObject *m;
1620 int ispackage;
1621 int size;
1623 if (p == NULL)
1624 return 0;
1625 if (p->code == NULL) {
1626 PyErr_Format(PyExc_ImportError,
1627 "Excluded frozen object named %.200s",
1628 name);
1629 return -1;
1631 size = p->size;
1632 ispackage = (size < 0);
1633 if (ispackage)
1634 size = -size;
1635 if (Py_VerboseFlag)
1636 PySys_WriteStderr("import %s # frozen%s\n",
1637 name, ispackage ? " package" : "");
1638 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1639 if (co == NULL)
1640 return -1;
1641 if (!PyCode_Check(co)) {
1642 Py_DECREF(co);
1643 PyErr_Format(PyExc_TypeError,
1644 "frozen object %.200s is not a code object",
1645 name);
1646 return -1;
1648 if (ispackage) {
1649 /* Set __path__ to the package name */
1650 PyObject *d, *s;
1651 int err;
1652 m = PyImport_AddModule(name);
1653 if (m == NULL)
1654 return -1;
1655 d = PyModule_GetDict(m);
1656 s = PyString_InternFromString(name);
1657 if (s == NULL)
1658 return -1;
1659 err = PyDict_SetItemString(d, "__path__", s);
1660 Py_DECREF(s);
1661 if (err != 0)
1662 return err;
1664 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1665 Py_DECREF(co);
1666 if (m == NULL)
1667 return -1;
1668 Py_DECREF(m);
1669 return 1;
1673 /* Import a module, either built-in, frozen, or external, and return
1674 its module object WITH INCREMENTED REFERENCE COUNT */
1676 PyObject *
1677 PyImport_ImportModule(char *name)
1679 PyObject *pname;
1680 PyObject *result;
1682 pname = PyString_FromString(name);
1683 result = PyImport_Import(pname);
1684 Py_DECREF(pname);
1685 return result;
1688 /* Forward declarations for helper routines */
1689 static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1690 static PyObject *load_next(PyObject *mod, PyObject *altmod,
1691 char **p_name, char *buf, int *p_buflen);
1692 static int mark_miss(char *name);
1693 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1694 char *buf, int buflen, int recursive);
1695 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1697 /* The Magnum Opus of dotted-name import :-) */
1699 static PyObject *
1700 import_module_ex(char *name, PyObject *globals, PyObject *locals,
1701 PyObject *fromlist)
1703 char buf[MAXPATHLEN+1];
1704 int buflen = 0;
1705 PyObject *parent, *head, *next, *tail;
1707 parent = get_parent(globals, buf, &buflen);
1708 if (parent == NULL)
1709 return NULL;
1711 head = load_next(parent, Py_None, &name, buf, &buflen);
1712 if (head == NULL)
1713 return NULL;
1715 tail = head;
1716 Py_INCREF(tail);
1717 while (name) {
1718 next = load_next(tail, tail, &name, buf, &buflen);
1719 Py_DECREF(tail);
1720 if (next == NULL) {
1721 Py_DECREF(head);
1722 return NULL;
1724 tail = next;
1727 if (fromlist != NULL) {
1728 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1729 fromlist = NULL;
1732 if (fromlist == NULL) {
1733 Py_DECREF(tail);
1734 return head;
1737 Py_DECREF(head);
1738 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
1739 Py_DECREF(tail);
1740 return NULL;
1743 return tail;
1746 PyObject *
1747 PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1748 PyObject *fromlist)
1750 PyObject *result;
1751 lock_import();
1752 result = import_module_ex(name, globals, locals, fromlist);
1753 unlock_import();
1754 return result;
1757 static PyObject *
1758 get_parent(PyObject *globals, char *buf, int *p_buflen)
1760 static PyObject *namestr = NULL;
1761 static PyObject *pathstr = NULL;
1762 PyObject *modname, *modpath, *modules, *parent;
1764 if (globals == NULL || !PyDict_Check(globals))
1765 return Py_None;
1767 if (namestr == NULL) {
1768 namestr = PyString_InternFromString("__name__");
1769 if (namestr == NULL)
1770 return NULL;
1772 if (pathstr == NULL) {
1773 pathstr = PyString_InternFromString("__path__");
1774 if (pathstr == NULL)
1775 return NULL;
1778 *buf = '\0';
1779 *p_buflen = 0;
1780 modname = PyDict_GetItem(globals, namestr);
1781 if (modname == NULL || !PyString_Check(modname))
1782 return Py_None;
1784 modpath = PyDict_GetItem(globals, pathstr);
1785 if (modpath != NULL) {
1786 int len = PyString_GET_SIZE(modname);
1787 if (len > MAXPATHLEN) {
1788 PyErr_SetString(PyExc_ValueError,
1789 "Module name too long");
1790 return NULL;
1792 strcpy(buf, PyString_AS_STRING(modname));
1793 *p_buflen = len;
1795 else {
1796 char *start = PyString_AS_STRING(modname);
1797 char *lastdot = strrchr(start, '.');
1798 size_t len;
1799 if (lastdot == NULL)
1800 return Py_None;
1801 len = lastdot - start;
1802 if (len >= MAXPATHLEN) {
1803 PyErr_SetString(PyExc_ValueError,
1804 "Module name too long");
1805 return NULL;
1807 strncpy(buf, start, len);
1808 buf[len] = '\0';
1809 *p_buflen = len;
1812 modules = PyImport_GetModuleDict();
1813 parent = PyDict_GetItemString(modules, buf);
1814 if (parent == NULL)
1815 parent = Py_None;
1816 return parent;
1817 /* We expect, but can't guarantee, if parent != None, that:
1818 - parent.__name__ == buf
1819 - parent.__dict__ is globals
1820 If this is violated... Who cares? */
1823 /* altmod is either None or same as mod */
1824 static PyObject *
1825 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
1826 int *p_buflen)
1828 char *name = *p_name;
1829 char *dot = strchr(name, '.');
1830 size_t len;
1831 char *p;
1832 PyObject *result;
1834 if (dot == NULL) {
1835 *p_name = NULL;
1836 len = strlen(name);
1838 else {
1839 *p_name = dot+1;
1840 len = dot-name;
1842 if (len == 0) {
1843 PyErr_SetString(PyExc_ValueError,
1844 "Empty module name");
1845 return NULL;
1848 p = buf + *p_buflen;
1849 if (p != buf)
1850 *p++ = '.';
1851 if (p+len-buf >= MAXPATHLEN) {
1852 PyErr_SetString(PyExc_ValueError,
1853 "Module name too long");
1854 return NULL;
1856 strncpy(p, name, len);
1857 p[len] = '\0';
1858 *p_buflen = p+len-buf;
1860 result = import_submodule(mod, p, buf);
1861 if (result == Py_None && altmod != mod) {
1862 Py_DECREF(result);
1863 /* Here, altmod must be None and mod must not be None */
1864 result = import_submodule(altmod, p, p);
1865 if (result != NULL && result != Py_None) {
1866 if (mark_miss(buf) != 0) {
1867 Py_DECREF(result);
1868 return NULL;
1870 strncpy(buf, name, len);
1871 buf[len] = '\0';
1872 *p_buflen = len;
1875 if (result == NULL)
1876 return NULL;
1878 if (result == Py_None) {
1879 Py_DECREF(result);
1880 PyErr_Format(PyExc_ImportError,
1881 "No module named %.200s", name);
1882 return NULL;
1885 return result;
1888 static int
1889 mark_miss(char *name)
1891 PyObject *modules = PyImport_GetModuleDict();
1892 return PyDict_SetItemString(modules, name, Py_None);
1895 static int
1896 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
1897 int recursive)
1899 int i;
1901 if (!PyObject_HasAttrString(mod, "__path__"))
1902 return 1;
1904 for (i = 0; ; i++) {
1905 PyObject *item = PySequence_GetItem(fromlist, i);
1906 int hasit;
1907 if (item == NULL) {
1908 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1909 PyErr_Clear();
1910 return 1;
1912 return 0;
1914 if (!PyString_Check(item)) {
1915 PyErr_SetString(PyExc_TypeError,
1916 "Item in ``from list'' not a string");
1917 Py_DECREF(item);
1918 return 0;
1920 if (PyString_AS_STRING(item)[0] == '*') {
1921 PyObject *all;
1922 Py_DECREF(item);
1923 /* See if the package defines __all__ */
1924 if (recursive)
1925 continue; /* Avoid endless recursion */
1926 all = PyObject_GetAttrString(mod, "__all__");
1927 if (all == NULL)
1928 PyErr_Clear();
1929 else {
1930 if (!ensure_fromlist(mod, all, buf, buflen, 1))
1931 return 0;
1932 Py_DECREF(all);
1934 continue;
1936 hasit = PyObject_HasAttr(mod, item);
1937 if (!hasit) {
1938 char *subname = PyString_AS_STRING(item);
1939 PyObject *submod;
1940 char *p;
1941 if (buflen + strlen(subname) >= MAXPATHLEN) {
1942 PyErr_SetString(PyExc_ValueError,
1943 "Module name too long");
1944 Py_DECREF(item);
1945 return 0;
1947 p = buf + buflen;
1948 *p++ = '.';
1949 strcpy(p, subname);
1950 submod = import_submodule(mod, subname, buf);
1951 Py_XDECREF(submod);
1952 if (submod == NULL) {
1953 Py_DECREF(item);
1954 return 0;
1957 Py_DECREF(item);
1960 /* NOTREACHED */
1963 static PyObject *
1964 import_submodule(PyObject *mod, char *subname, char *fullname)
1966 PyObject *modules = PyImport_GetModuleDict();
1967 PyObject *m, *res = NULL;
1969 /* Require:
1970 if mod == None: subname == fullname
1971 else: mod.__name__ + "." + subname == fullname
1974 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
1975 Py_INCREF(m);
1977 else {
1978 PyObject *path;
1979 char buf[MAXPATHLEN+1];
1980 struct filedescr *fdp;
1981 FILE *fp = NULL;
1983 if (mod == Py_None)
1984 path = NULL;
1985 else {
1986 path = PyObject_GetAttrString(mod, "__path__");
1987 if (path == NULL) {
1988 PyErr_Clear();
1989 Py_INCREF(Py_None);
1990 return Py_None;
1994 buf[0] = '\0';
1995 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1996 Py_XDECREF(path);
1997 if (fdp == NULL) {
1998 if (!PyErr_ExceptionMatches(PyExc_ImportError))
1999 return NULL;
2000 PyErr_Clear();
2001 Py_INCREF(Py_None);
2002 return Py_None;
2004 m = load_module(fullname, fp, buf, fdp->type);
2005 if (fp)
2006 fclose(fp);
2007 if (mod != Py_None) {
2008 /* Irrespective of the success of this load, make a
2009 reference to it in the parent package module.
2010 A copy gets saved in the modules dictionary
2011 under the full name, so get a reference from
2012 there, if need be. (The exception is when
2013 the load failed with a SyntaxError -- then
2014 there's no trace in sys.modules. In that case,
2015 of course, do nothing extra.) */
2016 res = m;
2017 if (res == NULL)
2018 res = PyDict_GetItemString(modules, fullname);
2019 if (res != NULL &&
2020 PyObject_SetAttrString(mod, subname, res) < 0) {
2021 Py_XDECREF(m);
2022 m = NULL;
2027 return m;
2031 /* Re-import a module of any kind and return its module object, WITH
2032 INCREMENTED REFERENCE COUNT */
2034 PyObject *
2035 PyImport_ReloadModule(PyObject *m)
2037 PyObject *modules = PyImport_GetModuleDict();
2038 PyObject *path = NULL;
2039 char *name, *subname;
2040 char buf[MAXPATHLEN+1];
2041 struct filedescr *fdp;
2042 FILE *fp = NULL;
2044 if (m == NULL || !PyModule_Check(m)) {
2045 PyErr_SetString(PyExc_TypeError,
2046 "reload() argument must be module");
2047 return NULL;
2049 name = PyModule_GetName(m);
2050 if (name == NULL)
2051 return NULL;
2052 if (m != PyDict_GetItemString(modules, name)) {
2053 PyErr_Format(PyExc_ImportError,
2054 "reload(): module %.200s not in sys.modules",
2055 name);
2056 return NULL;
2058 subname = strrchr(name, '.');
2059 if (subname == NULL)
2060 subname = name;
2061 else {
2062 PyObject *parentname, *parent;
2063 parentname = PyString_FromStringAndSize(name, (subname-name));
2064 if (parentname == NULL)
2065 return NULL;
2066 parent = PyDict_GetItem(modules, parentname);
2067 Py_DECREF(parentname);
2068 if (parent == NULL) {
2069 PyErr_Format(PyExc_ImportError,
2070 "reload(): parent %.200s not in sys.modules",
2071 name);
2072 return NULL;
2074 subname++;
2075 path = PyObject_GetAttrString(parent, "__path__");
2076 if (path == NULL)
2077 PyErr_Clear();
2079 buf[0] = '\0';
2080 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
2081 Py_XDECREF(path);
2082 if (fdp == NULL)
2083 return NULL;
2084 m = load_module(name, fp, buf, fdp->type);
2085 if (fp)
2086 fclose(fp);
2087 return m;
2091 /* Higher-level import emulator which emulates the "import" statement
2092 more accurately -- it invokes the __import__() function from the
2093 builtins of the current globals. This means that the import is
2094 done using whatever import hooks are installed in the current
2095 environment, e.g. by "rexec".
2096 A dummy list ["__doc__"] is passed as the 4th argument so that
2097 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2098 will return <module "gencache"> instead of <module "win32com">. */
2100 PyObject *
2101 PyImport_Import(PyObject *module_name)
2103 static PyObject *silly_list = NULL;
2104 static PyObject *builtins_str = NULL;
2105 static PyObject *import_str = NULL;
2106 PyObject *globals = NULL;
2107 PyObject *import = NULL;
2108 PyObject *builtins = NULL;
2109 PyObject *r = NULL;
2111 /* Initialize constant string objects */
2112 if (silly_list == NULL) {
2113 import_str = PyString_InternFromString("__import__");
2114 if (import_str == NULL)
2115 return NULL;
2116 builtins_str = PyString_InternFromString("__builtins__");
2117 if (builtins_str == NULL)
2118 return NULL;
2119 silly_list = Py_BuildValue("[s]", "__doc__");
2120 if (silly_list == NULL)
2121 return NULL;
2124 /* Get the builtins from current globals */
2125 globals = PyEval_GetGlobals();
2126 if (globals != NULL) {
2127 Py_INCREF(globals);
2128 builtins = PyObject_GetItem(globals, builtins_str);
2129 if (builtins == NULL)
2130 goto err;
2132 else {
2133 /* No globals -- use standard builtins, and fake globals */
2134 PyErr_Clear();
2136 builtins = PyImport_ImportModuleEx("__builtin__",
2137 NULL, NULL, NULL);
2138 if (builtins == NULL)
2139 return NULL;
2140 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2141 if (globals == NULL)
2142 goto err;
2145 /* Get the __import__ function from the builtins */
2146 if (PyDict_Check(builtins)) {
2147 import = PyObject_GetItem(builtins, import_str);
2148 if (import == NULL)
2149 PyErr_SetObject(PyExc_KeyError, import_str);
2151 else
2152 import = PyObject_GetAttr(builtins, import_str);
2153 if (import == NULL)
2154 goto err;
2156 /* Call the _import__ function with the proper argument list */
2157 r = PyObject_CallFunction(import, "OOOO",
2158 module_name, globals, globals, silly_list);
2160 err:
2161 Py_XDECREF(globals);
2162 Py_XDECREF(builtins);
2163 Py_XDECREF(import);
2165 return r;
2169 /* Module 'imp' provides Python access to the primitives used for
2170 importing modules.
2173 static PyObject *
2174 imp_get_magic(PyObject *self, PyObject *args)
2176 char buf[4];
2178 if (!PyArg_ParseTuple(args, ":get_magic"))
2179 return NULL;
2180 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2181 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2182 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2183 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2185 return PyString_FromStringAndSize(buf, 4);
2188 static PyObject *
2189 imp_get_suffixes(PyObject *self, PyObject *args)
2191 PyObject *list;
2192 struct filedescr *fdp;
2194 if (!PyArg_ParseTuple(args, ":get_suffixes"))
2195 return NULL;
2196 list = PyList_New(0);
2197 if (list == NULL)
2198 return NULL;
2199 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2200 PyObject *item = Py_BuildValue("ssi",
2201 fdp->suffix, fdp->mode, fdp->type);
2202 if (item == NULL) {
2203 Py_DECREF(list);
2204 return NULL;
2206 if (PyList_Append(list, item) < 0) {
2207 Py_DECREF(list);
2208 Py_DECREF(item);
2209 return NULL;
2211 Py_DECREF(item);
2213 return list;
2216 static PyObject *
2217 call_find_module(char *name, PyObject *path)
2219 extern int fclose(FILE *);
2220 PyObject *fob, *ret;
2221 struct filedescr *fdp;
2222 char pathname[MAXPATHLEN+1];
2223 FILE *fp = NULL;
2225 pathname[0] = '\0';
2226 if (path == Py_None)
2227 path = NULL;
2228 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
2229 if (fdp == NULL)
2230 return NULL;
2231 if (fp != NULL) {
2232 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2233 if (fob == NULL) {
2234 fclose(fp);
2235 return NULL;
2238 else {
2239 fob = Py_None;
2240 Py_INCREF(fob);
2242 ret = Py_BuildValue("Os(ssi)",
2243 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2244 Py_DECREF(fob);
2245 return ret;
2248 static PyObject *
2249 imp_find_module(PyObject *self, PyObject *args)
2251 char *name;
2252 PyObject *path = NULL;
2253 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2254 return NULL;
2255 return call_find_module(name, path);
2258 static PyObject *
2259 imp_init_builtin(PyObject *self, PyObject *args)
2261 char *name;
2262 int ret;
2263 PyObject *m;
2264 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2265 return NULL;
2266 ret = init_builtin(name);
2267 if (ret < 0)
2268 return NULL;
2269 if (ret == 0) {
2270 Py_INCREF(Py_None);
2271 return Py_None;
2273 m = PyImport_AddModule(name);
2274 Py_XINCREF(m);
2275 return m;
2278 static PyObject *
2279 imp_init_frozen(PyObject *self, PyObject *args)
2281 char *name;
2282 int ret;
2283 PyObject *m;
2284 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2285 return NULL;
2286 ret = PyImport_ImportFrozenModule(name);
2287 if (ret < 0)
2288 return NULL;
2289 if (ret == 0) {
2290 Py_INCREF(Py_None);
2291 return Py_None;
2293 m = PyImport_AddModule(name);
2294 Py_XINCREF(m);
2295 return m;
2298 static PyObject *
2299 imp_get_frozen_object(PyObject *self, PyObject *args)
2301 char *name;
2303 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2304 return NULL;
2305 return get_frozen_object(name);
2308 static PyObject *
2309 imp_is_builtin(PyObject *self, PyObject *args)
2311 char *name;
2312 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2313 return NULL;
2314 return PyInt_FromLong(is_builtin(name));
2317 static PyObject *
2318 imp_is_frozen(PyObject *self, PyObject *args)
2320 char *name;
2321 struct _frozen *p;
2322 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2323 return NULL;
2324 p = find_frozen(name);
2325 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2328 static FILE *
2329 get_file(char *pathname, PyObject *fob, char *mode)
2331 FILE *fp;
2332 if (fob == NULL) {
2333 if (mode[0] == 'U')
2334 mode = "r" PY_STDIOTEXTMODE;
2335 fp = fopen(pathname, mode);
2336 if (fp == NULL)
2337 PyErr_SetFromErrno(PyExc_IOError);
2339 else {
2340 fp = PyFile_AsFile(fob);
2341 if (fp == NULL)
2342 PyErr_SetString(PyExc_ValueError,
2343 "bad/closed file object");
2345 return fp;
2348 static PyObject *
2349 imp_load_compiled(PyObject *self, PyObject *args)
2351 char *name;
2352 char *pathname;
2353 PyObject *fob = NULL;
2354 PyObject *m;
2355 FILE *fp;
2356 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2357 &PyFile_Type, &fob))
2358 return NULL;
2359 fp = get_file(pathname, fob, "rb");
2360 if (fp == NULL)
2361 return NULL;
2362 m = load_compiled_module(name, pathname, fp);
2363 if (fob == NULL)
2364 fclose(fp);
2365 return m;
2368 #ifdef HAVE_DYNAMIC_LOADING
2370 static PyObject *
2371 imp_load_dynamic(PyObject *self, PyObject *args)
2373 char *name;
2374 char *pathname;
2375 PyObject *fob = NULL;
2376 PyObject *m;
2377 FILE *fp = NULL;
2378 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2379 &PyFile_Type, &fob))
2380 return NULL;
2381 if (fob) {
2382 fp = get_file(pathname, fob, "r");
2383 if (fp == NULL)
2384 return NULL;
2386 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2387 return m;
2390 #endif /* HAVE_DYNAMIC_LOADING */
2392 static PyObject *
2393 imp_load_source(PyObject *self, PyObject *args)
2395 char *name;
2396 char *pathname;
2397 PyObject *fob = NULL;
2398 PyObject *m;
2399 FILE *fp;
2400 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2401 &PyFile_Type, &fob))
2402 return NULL;
2403 fp = get_file(pathname, fob, "r");
2404 if (fp == NULL)
2405 return NULL;
2406 m = load_source_module(name, pathname, fp);
2407 if (fob == NULL)
2408 fclose(fp);
2409 return m;
2412 #ifdef macintosh
2413 static PyObject *
2414 imp_load_resource(PyObject *self, PyObject *args)
2416 char *name;
2417 char *pathname;
2418 PyObject *m;
2420 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
2421 return NULL;
2422 m = PyMac_LoadResourceModule(name, pathname);
2423 return m;
2425 #endif /* macintosh */
2427 static PyObject *
2428 imp_load_module(PyObject *self, PyObject *args)
2430 char *name;
2431 PyObject *fob;
2432 char *pathname;
2433 char *suffix; /* Unused */
2434 char *mode;
2435 int type;
2436 FILE *fp;
2438 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2439 &name, &fob, &pathname,
2440 &suffix, &mode, &type))
2441 return NULL;
2442 if (*mode) {
2443 /* Mode must start with 'r' or 'U' and must not contain '+'.
2444 Implicit in this test is the assumption that the mode
2445 may contain other modifiers like 'b' or 't'. */
2447 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
2448 PyErr_Format(PyExc_ValueError,
2449 "invalid file open mode %.200s", mode);
2450 return NULL;
2453 if (fob == Py_None)
2454 fp = NULL;
2455 else {
2456 if (!PyFile_Check(fob)) {
2457 PyErr_SetString(PyExc_ValueError,
2458 "load_module arg#2 should be a file or None");
2459 return NULL;
2461 fp = get_file(pathname, fob, mode);
2462 if (fp == NULL)
2463 return NULL;
2465 return load_module(name, fp, pathname, type);
2468 static PyObject *
2469 imp_load_package(PyObject *self, PyObject *args)
2471 char *name;
2472 char *pathname;
2473 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2474 return NULL;
2475 return load_package(name, pathname);
2478 static PyObject *
2479 imp_new_module(PyObject *self, PyObject *args)
2481 char *name;
2482 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2483 return NULL;
2484 return PyModule_New(name);
2487 /* Doc strings */
2489 PyDoc_STRVAR(doc_imp,
2490 "This module provides the components needed to build your own\n\
2491 __import__ function. Undocumented functions are obsolete.");
2493 PyDoc_STRVAR(doc_find_module,
2494 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2495 Search for a module. If path is omitted or None, search for a\n\
2496 built-in, frozen or special module and continue search in sys.path.\n\
2497 The module name cannot contain '.'; to search for a submodule of a\n\
2498 package, pass the submodule name and the package's __path__.");
2500 PyDoc_STRVAR(doc_load_module,
2501 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2502 Load a module, given information returned by find_module().\n\
2503 The module name must include the full package name, if any.");
2505 PyDoc_STRVAR(doc_get_magic,
2506 "get_magic() -> string\n\
2507 Return the magic number for .pyc or .pyo files.");
2509 PyDoc_STRVAR(doc_get_suffixes,
2510 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2511 Return a list of (suffix, mode, type) tuples describing the files\n\
2512 that find_module() looks for.");
2514 PyDoc_STRVAR(doc_new_module,
2515 "new_module(name) -> module\n\
2516 Create a new module. Do not enter it in sys.modules.\n\
2517 The module name must include the full package name, if any.");
2519 PyDoc_STRVAR(doc_lock_held,
2520 "lock_held() -> 0 or 1\n\
2521 Return 1 if the import lock is currently held.\n\
2522 On platforms without threads, return 0.");
2524 static PyMethodDef imp_methods[] = {
2525 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2526 {"get_magic", imp_get_magic, METH_VARARGS, doc_get_magic},
2527 {"get_suffixes", imp_get_suffixes, METH_VARARGS, doc_get_suffixes},
2528 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2529 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2530 {"lock_held", imp_lock_held, METH_VARARGS, doc_lock_held},
2531 /* The rest are obsolete */
2532 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2533 {"init_builtin", imp_init_builtin, METH_VARARGS},
2534 {"init_frozen", imp_init_frozen, METH_VARARGS},
2535 {"is_builtin", imp_is_builtin, METH_VARARGS},
2536 {"is_frozen", imp_is_frozen, METH_VARARGS},
2537 {"load_compiled", imp_load_compiled, METH_VARARGS},
2538 #ifdef HAVE_DYNAMIC_LOADING
2539 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
2540 #endif
2541 {"load_package", imp_load_package, METH_VARARGS},
2542 #ifdef macintosh
2543 {"load_resource", imp_load_resource, METH_VARARGS},
2544 #endif
2545 {"load_source", imp_load_source, METH_VARARGS},
2546 {NULL, NULL} /* sentinel */
2549 static int
2550 setint(PyObject *d, char *name, int value)
2552 PyObject *v;
2553 int err;
2555 v = PyInt_FromLong((long)value);
2556 err = PyDict_SetItemString(d, name, v);
2557 Py_XDECREF(v);
2558 return err;
2561 void
2562 initimp(void)
2564 PyObject *m, *d;
2566 m = Py_InitModule4("imp", imp_methods, doc_imp,
2567 NULL, PYTHON_API_VERSION);
2568 d = PyModule_GetDict(m);
2570 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2571 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2572 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2573 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2574 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2575 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2576 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2577 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2578 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2580 failure:
2585 /* API for embedding applications that want to add their own entries
2586 to the table of built-in modules. This should normally be called
2587 *before* Py_Initialize(). When the table resize fails, -1 is
2588 returned and the existing table is unchanged.
2590 After a similar function by Just van Rossum. */
2593 PyImport_ExtendInittab(struct _inittab *newtab)
2595 static struct _inittab *our_copy = NULL;
2596 struct _inittab *p;
2597 int i, n;
2599 /* Count the number of entries in both tables */
2600 for (n = 0; newtab[n].name != NULL; n++)
2602 if (n == 0)
2603 return 0; /* Nothing to do */
2604 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2607 /* Allocate new memory for the combined table */
2608 p = our_copy;
2609 PyMem_RESIZE(p, struct _inittab, i+n+1);
2610 if (p == NULL)
2611 return -1;
2613 /* Copy the tables into the new memory */
2614 if (our_copy != PyImport_Inittab)
2615 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2616 PyImport_Inittab = our_copy = p;
2617 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2619 return 0;
2622 /* Shorthand to add a single entry given a name and a function */
2625 PyImport_AppendInittab(char *name, void (*initfunc)(void))
2627 struct _inittab newtab[2];
2629 memset(newtab, '\0', sizeof newtab);
2631 newtab[0].name = name;
2632 newtab[0].initfunc = initfunc;
2634 return PyImport_ExtendInittab(newtab);