Update version number and release date.
[python/dscho.git] / Python / import.c
blob010e8213e00f00b8d42a6d43f834b4d14bdcf0e4
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 _PyImportHooks_Init(void)
158 PyObject *v, *path_hooks = NULL, *zimpimport;
159 int err = 0;
161 /* adding sys.path_hooks and sys.path_importer_cache, setting up
162 zipimport */
164 if (Py_VerboseFlag)
165 PySys_WriteStderr("# installing zipimport hook\n");
167 v = PyList_New(0);
168 if (v == NULL)
169 goto error;
170 err = PySys_SetObject("meta_path", v);
171 Py_DECREF(v);
172 if (err)
173 goto error;
174 v = PyDict_New();
175 if (v == NULL)
176 goto error;
177 err = PySys_SetObject("path_importer_cache", v);
178 Py_DECREF(v);
179 if (err)
180 goto error;
181 path_hooks = PyList_New(0);
182 if (path_hooks == NULL)
183 goto error;
184 err = PySys_SetObject("path_hooks", path_hooks);
185 if (err) {
186 error:
187 PyErr_Print();
188 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
189 "path_importer_cache failed");
191 zimpimport = PyImport_ImportModule("zipimport");
192 if (zimpimport == NULL) {
193 PyErr_Clear(); /* No zip import module -- okay */
194 if (Py_VerboseFlag)
195 PySys_WriteStderr("# can't import zipimport\n");
197 else {
198 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
199 "zipimporter");
200 Py_DECREF(zimpimport);
201 if (zipimporter == NULL) {
202 PyErr_Clear(); /* No zipimporter object -- okay */
203 if (Py_VerboseFlag)
204 PySys_WriteStderr(
205 "# can't import zipimport.zimimporter\n");
207 else {
208 /* sys.path_hooks.append(zipimporter) */
209 err = PyList_Append(path_hooks, zipimporter);
210 Py_DECREF(zipimporter);
211 if (err)
212 goto error;
213 if (Py_VerboseFlag)
214 PySys_WriteStderr(
215 "# installed zipimport hook\n");
218 Py_DECREF(path_hooks);
221 void
222 _PyImport_Fini(void)
224 Py_XDECREF(extensions);
225 extensions = NULL;
226 PyMem_DEL(_PyImport_Filetab);
227 _PyImport_Filetab = NULL;
231 /* Locking primitives to prevent parallel imports of the same module
232 in different threads to return with a partially loaded module.
233 These calls are serialized by the global interpreter lock. */
235 #ifdef WITH_THREAD
237 #include "pythread.h"
239 static PyThread_type_lock import_lock = 0;
240 static long import_lock_thread = -1;
241 static int import_lock_level = 0;
243 static void
244 lock_import(void)
246 long me = PyThread_get_thread_ident();
247 if (me == -1)
248 return; /* Too bad */
249 if (import_lock == NULL)
250 import_lock = PyThread_allocate_lock();
251 if (import_lock_thread == me) {
252 import_lock_level++;
253 return;
255 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
257 PyThreadState *tstate = PyEval_SaveThread();
258 PyThread_acquire_lock(import_lock, 1);
259 PyEval_RestoreThread(tstate);
261 import_lock_thread = me;
262 import_lock_level = 1;
265 static int
266 unlock_import(void)
268 long me = PyThread_get_thread_ident();
269 if (me == -1)
270 return 0; /* Too bad */
271 if (import_lock_thread != me)
272 return -1;
273 import_lock_level--;
274 if (import_lock_level == 0) {
275 import_lock_thread = -1;
276 PyThread_release_lock(import_lock);
278 return 1;
281 #else
283 #define lock_import()
284 #define unlock_import() 0
286 #endif
288 static PyObject *
289 imp_lock_held(PyObject *self, PyObject *noargs)
291 #ifdef WITH_THREAD
292 return PyBool_FromLong(import_lock_thread != -1);
293 #else
294 return PyBool_FromLong(0);
295 #endif
298 static PyObject *
299 imp_acquire_lock(PyObject *self, PyObject *noargs)
301 #ifdef WITH_THREAD
302 lock_import();
303 #endif
304 Py_INCREF(Py_None);
305 return Py_None;
308 static PyObject *
309 imp_release_lock(PyObject *self, PyObject *noargs)
311 #ifdef WITH_THREAD
312 if (unlock_import() < 0) {
313 PyErr_SetString(PyExc_RuntimeError,
314 "not holding the import lock");
315 return NULL;
317 #endif
318 Py_INCREF(Py_None);
319 return Py_None;
322 /* Helper for sys */
324 PyObject *
325 PyImport_GetModuleDict(void)
327 PyInterpreterState *interp = PyThreadState_Get()->interp;
328 if (interp->modules == NULL)
329 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
330 return interp->modules;
334 /* List of names to clear in sys */
335 static char* sys_deletes[] = {
336 "path", "argv", "ps1", "ps2", "exitfunc",
337 "exc_type", "exc_value", "exc_traceback",
338 "last_type", "last_value", "last_traceback",
339 "path_hooks", "path_importer_cache", "meta_path",
340 NULL
343 static char* sys_files[] = {
344 "stdin", "__stdin__",
345 "stdout", "__stdout__",
346 "stderr", "__stderr__",
347 NULL
351 /* Un-initialize things, as good as we can */
353 void
354 PyImport_Cleanup(void)
356 int pos, ndone;
357 char *name;
358 PyObject *key, *value, *dict;
359 PyInterpreterState *interp = PyThreadState_Get()->interp;
360 PyObject *modules = interp->modules;
362 if (modules == NULL)
363 return; /* Already done */
365 /* Delete some special variables first. These are common
366 places where user values hide and people complain when their
367 destructors fail. Since the modules containing them are
368 deleted *last* of all, they would come too late in the normal
369 destruction order. Sigh. */
371 value = PyDict_GetItemString(modules, "__builtin__");
372 if (value != NULL && PyModule_Check(value)) {
373 dict = PyModule_GetDict(value);
374 if (Py_VerboseFlag)
375 PySys_WriteStderr("# clear __builtin__._\n");
376 PyDict_SetItemString(dict, "_", Py_None);
378 value = PyDict_GetItemString(modules, "sys");
379 if (value != NULL && PyModule_Check(value)) {
380 char **p;
381 PyObject *v;
382 dict = PyModule_GetDict(value);
383 for (p = sys_deletes; *p != NULL; p++) {
384 if (Py_VerboseFlag)
385 PySys_WriteStderr("# clear sys.%s\n", *p);
386 PyDict_SetItemString(dict, *p, Py_None);
388 for (p = sys_files; *p != NULL; p+=2) {
389 if (Py_VerboseFlag)
390 PySys_WriteStderr("# restore sys.%s\n", *p);
391 v = PyDict_GetItemString(dict, *(p+1));
392 if (v == NULL)
393 v = Py_None;
394 PyDict_SetItemString(dict, *p, v);
398 /* First, delete __main__ */
399 value = PyDict_GetItemString(modules, "__main__");
400 if (value != NULL && PyModule_Check(value)) {
401 if (Py_VerboseFlag)
402 PySys_WriteStderr("# cleanup __main__\n");
403 _PyModule_Clear(value);
404 PyDict_SetItemString(modules, "__main__", Py_None);
407 /* The special treatment of __builtin__ here is because even
408 when it's not referenced as a module, its dictionary is
409 referenced by almost every module's __builtins__. Since
410 deleting a module clears its dictionary (even if there are
411 references left to it), we need to delete the __builtin__
412 module last. Likewise, we don't delete sys until the very
413 end because it is implicitly referenced (e.g. by print).
415 Also note that we 'delete' modules by replacing their entry
416 in the modules dict with None, rather than really deleting
417 them; this avoids a rehash of the modules dictionary and
418 also marks them as "non existent" so they won't be
419 re-imported. */
421 /* Next, repeatedly delete modules with a reference count of
422 one (skipping __builtin__ and sys) and delete them */
423 do {
424 ndone = 0;
425 pos = 0;
426 while (PyDict_Next(modules, &pos, &key, &value)) {
427 if (value->ob_refcnt != 1)
428 continue;
429 if (PyString_Check(key) && PyModule_Check(value)) {
430 name = PyString_AS_STRING(key);
431 if (strcmp(name, "__builtin__") == 0)
432 continue;
433 if (strcmp(name, "sys") == 0)
434 continue;
435 if (Py_VerboseFlag)
436 PySys_WriteStderr(
437 "# cleanup[1] %s\n", name);
438 _PyModule_Clear(value);
439 PyDict_SetItem(modules, key, Py_None);
440 ndone++;
443 } while (ndone > 0);
445 /* Next, delete all modules (still skipping __builtin__ and sys) */
446 pos = 0;
447 while (PyDict_Next(modules, &pos, &key, &value)) {
448 if (PyString_Check(key) && PyModule_Check(value)) {
449 name = PyString_AS_STRING(key);
450 if (strcmp(name, "__builtin__") == 0)
451 continue;
452 if (strcmp(name, "sys") == 0)
453 continue;
454 if (Py_VerboseFlag)
455 PySys_WriteStderr("# cleanup[2] %s\n", name);
456 _PyModule_Clear(value);
457 PyDict_SetItem(modules, key, Py_None);
461 /* Next, delete sys and __builtin__ (in that order) */
462 value = PyDict_GetItemString(modules, "sys");
463 if (value != NULL && PyModule_Check(value)) {
464 if (Py_VerboseFlag)
465 PySys_WriteStderr("# cleanup sys\n");
466 _PyModule_Clear(value);
467 PyDict_SetItemString(modules, "sys", Py_None);
469 value = PyDict_GetItemString(modules, "__builtin__");
470 if (value != NULL && PyModule_Check(value)) {
471 if (Py_VerboseFlag)
472 PySys_WriteStderr("# cleanup __builtin__\n");
473 _PyModule_Clear(value);
474 PyDict_SetItemString(modules, "__builtin__", Py_None);
477 /* Finally, clear and delete the modules directory */
478 PyDict_Clear(modules);
479 interp->modules = NULL;
480 Py_DECREF(modules);
484 /* Helper for pythonrun.c -- return magic number */
486 long
487 PyImport_GetMagicNumber(void)
489 return pyc_magic;
493 /* Magic for extension modules (built-in as well as dynamically
494 loaded). To prevent initializing an extension module more than
495 once, we keep a static dictionary 'extensions' keyed by module name
496 (for built-in modules) or by filename (for dynamically loaded
497 modules), containing these modules. A copy of the module's
498 dictionary is stored by calling _PyImport_FixupExtension()
499 immediately after the module initialization function succeeds. A
500 copy can be retrieved from there by calling
501 _PyImport_FindExtension(). */
503 PyObject *
504 _PyImport_FixupExtension(char *name, char *filename)
506 PyObject *modules, *mod, *dict, *copy;
507 if (extensions == NULL) {
508 extensions = PyDict_New();
509 if (extensions == NULL)
510 return NULL;
512 modules = PyImport_GetModuleDict();
513 mod = PyDict_GetItemString(modules, name);
514 if (mod == NULL || !PyModule_Check(mod)) {
515 PyErr_Format(PyExc_SystemError,
516 "_PyImport_FixupExtension: module %.200s not loaded", name);
517 return NULL;
519 dict = PyModule_GetDict(mod);
520 if (dict == NULL)
521 return NULL;
522 copy = PyDict_Copy(dict);
523 if (copy == NULL)
524 return NULL;
525 PyDict_SetItemString(extensions, filename, copy);
526 Py_DECREF(copy);
527 return copy;
530 PyObject *
531 _PyImport_FindExtension(char *name, char *filename)
533 PyObject *dict, *mod, *mdict;
534 if (extensions == NULL)
535 return NULL;
536 dict = PyDict_GetItemString(extensions, filename);
537 if (dict == NULL)
538 return NULL;
539 mod = PyImport_AddModule(name);
540 if (mod == NULL)
541 return NULL;
542 mdict = PyModule_GetDict(mod);
543 if (mdict == NULL)
544 return NULL;
545 if (PyDict_Update(mdict, dict))
546 return NULL;
547 if (Py_VerboseFlag)
548 PySys_WriteStderr("import %s # previously loaded (%s)\n",
549 name, filename);
550 return mod;
554 /* Get the module object corresponding to a module name.
555 First check the modules dictionary if there's one there,
556 if not, create a new one and insert in in the modules dictionary.
557 Because the former action is most common, THIS DOES NOT RETURN A
558 'NEW' REFERENCE! */
560 PyObject *
561 PyImport_AddModule(char *name)
563 PyObject *modules = PyImport_GetModuleDict();
564 PyObject *m;
566 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
567 PyModule_Check(m))
568 return m;
569 m = PyModule_New(name);
570 if (m == NULL)
571 return NULL;
572 if (PyDict_SetItemString(modules, name, m) != 0) {
573 Py_DECREF(m);
574 return NULL;
576 Py_DECREF(m); /* Yes, it still exists, in modules! */
578 return m;
582 /* Execute a code object in a module and return the module object
583 WITH INCREMENTED REFERENCE COUNT */
585 PyObject *
586 PyImport_ExecCodeModule(char *name, PyObject *co)
588 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
591 PyObject *
592 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
594 PyObject *modules = PyImport_GetModuleDict();
595 PyObject *m, *d, *v;
597 m = PyImport_AddModule(name);
598 if (m == NULL)
599 return NULL;
600 d = PyModule_GetDict(m);
601 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
602 if (PyDict_SetItemString(d, "__builtins__",
603 PyEval_GetBuiltins()) != 0)
604 return NULL;
606 /* Remember the filename as the __file__ attribute */
607 v = NULL;
608 if (pathname != NULL) {
609 v = PyString_FromString(pathname);
610 if (v == NULL)
611 PyErr_Clear();
613 if (v == NULL) {
614 v = ((PyCodeObject *)co)->co_filename;
615 Py_INCREF(v);
617 if (PyDict_SetItemString(d, "__file__", v) != 0)
618 PyErr_Clear(); /* Not important enough to report */
619 Py_DECREF(v);
621 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
622 if (v == NULL)
623 return NULL;
624 Py_DECREF(v);
626 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
627 PyErr_Format(PyExc_ImportError,
628 "Loaded module %.200s not found in sys.modules",
629 name);
630 return NULL;
633 Py_INCREF(m);
635 return m;
639 /* Given a pathname for a Python source file, fill a buffer with the
640 pathname for the corresponding compiled file. Return the pathname
641 for the compiled file, or NULL if there's no space in the buffer.
642 Doesn't set an exception. */
644 static char *
645 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
647 size_t len = strlen(pathname);
648 if (len+2 > buflen)
649 return NULL;
651 #ifdef MS_WINDOWS
652 /* Treat .pyw as if it were .py. The case of ".pyw" must match
653 that used in _PyImport_StandardFiletab. */
654 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
655 --len; /* pretend 'w' isn't there */
656 #endif
657 memcpy(buf, pathname, len);
658 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
659 buf[len+1] = '\0';
661 return buf;
665 /* Given a pathname for a Python source file, its time of last
666 modification, and a pathname for a compiled file, check whether the
667 compiled file represents the same version of the source. If so,
668 return a FILE pointer for the compiled file, positioned just after
669 the header; if not, return NULL.
670 Doesn't set an exception. */
672 static FILE *
673 check_compiled_module(char *pathname, long mtime, char *cpathname)
675 FILE *fp;
676 long magic;
677 long pyc_mtime;
679 fp = fopen(cpathname, "rb");
680 if (fp == NULL)
681 return NULL;
682 magic = PyMarshal_ReadLongFromFile(fp);
683 if (magic != pyc_magic) {
684 if (Py_VerboseFlag)
685 PySys_WriteStderr("# %s has bad magic\n", cpathname);
686 fclose(fp);
687 return NULL;
689 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
690 if (pyc_mtime != mtime) {
691 if (Py_VerboseFlag)
692 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
693 fclose(fp);
694 return NULL;
696 if (Py_VerboseFlag)
697 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
698 return fp;
702 /* Read a code object from a file and check it for validity */
704 static PyCodeObject *
705 read_compiled_module(char *cpathname, FILE *fp)
707 PyObject *co;
709 co = PyMarshal_ReadLastObjectFromFile(fp);
710 /* Ugly: rd_object() may return NULL with or without error */
711 if (co == NULL || !PyCode_Check(co)) {
712 if (!PyErr_Occurred())
713 PyErr_Format(PyExc_ImportError,
714 "Non-code object in %.200s", cpathname);
715 Py_XDECREF(co);
716 return NULL;
718 return (PyCodeObject *)co;
722 /* Load a module from a compiled file, execute it, and return its
723 module object WITH INCREMENTED REFERENCE COUNT */
725 static PyObject *
726 load_compiled_module(char *name, char *cpathname, FILE *fp)
728 long magic;
729 PyCodeObject *co;
730 PyObject *m;
732 magic = PyMarshal_ReadLongFromFile(fp);
733 if (magic != pyc_magic) {
734 PyErr_Format(PyExc_ImportError,
735 "Bad magic number in %.200s", cpathname);
736 return NULL;
738 (void) PyMarshal_ReadLongFromFile(fp);
739 co = read_compiled_module(cpathname, fp);
740 if (co == NULL)
741 return NULL;
742 if (Py_VerboseFlag)
743 PySys_WriteStderr("import %s # precompiled from %s\n",
744 name, cpathname);
745 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
746 Py_DECREF(co);
748 return m;
751 /* Parse a source file and return the corresponding code object */
753 static PyCodeObject *
754 parse_source_module(char *pathname, FILE *fp)
756 PyCodeObject *co;
757 node *n;
759 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
760 if (n == NULL)
761 return NULL;
762 co = PyNode_Compile(n, pathname);
763 PyNode_Free(n);
765 return co;
769 /* Helper to open a bytecode file for writing in exclusive mode */
771 static FILE *
772 open_exclusive(char *filename)
774 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
775 /* Use O_EXCL to avoid a race condition when another process tries to
776 write the same file. When that happens, our open() call fails,
777 which is just fine (since it's only a cache).
778 XXX If the file exists and is writable but the directory is not
779 writable, the file will never be written. Oh well.
781 int fd;
782 (void) unlink(filename);
783 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
784 #ifdef O_BINARY
785 |O_BINARY /* necessary for Windows */
786 #endif
787 #ifdef __VMS
788 , 0666, "ctxt=bin", "shr=nil");
789 #else
790 , 0666);
791 #endif
792 if (fd < 0)
793 return NULL;
794 return fdopen(fd, "wb");
795 #else
796 /* Best we can do -- on Windows this can't happen anyway */
797 return fopen(filename, "wb");
798 #endif
802 /* Write a compiled module to a file, placing the time of last
803 modification of its source into the header.
804 Errors are ignored, if a write error occurs an attempt is made to
805 remove the file. */
807 static void
808 write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
810 FILE *fp;
812 fp = open_exclusive(cpathname);
813 if (fp == NULL) {
814 if (Py_VerboseFlag)
815 PySys_WriteStderr(
816 "# can't create %s\n", cpathname);
817 return;
819 PyMarshal_WriteLongToFile(pyc_magic, fp);
820 /* First write a 0 for mtime */
821 PyMarshal_WriteLongToFile(0L, fp);
822 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
823 if (ferror(fp)) {
824 if (Py_VerboseFlag)
825 PySys_WriteStderr("# can't write %s\n", cpathname);
826 /* Don't keep partial file */
827 fclose(fp);
828 (void) unlink(cpathname);
829 return;
831 /* Now write the true mtime */
832 fseek(fp, 4L, 0);
833 PyMarshal_WriteLongToFile(mtime, fp);
834 fflush(fp);
835 fclose(fp);
836 if (Py_VerboseFlag)
837 PySys_WriteStderr("# wrote %s\n", cpathname);
838 #ifdef macintosh
839 PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
840 #endif
844 /* Load a source module from a given file and return its module
845 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
846 byte-compiled file, use that instead. */
848 static PyObject *
849 load_source_module(char *name, char *pathname, FILE *fp)
851 time_t mtime;
852 FILE *fpc;
853 char buf[MAXPATHLEN+1];
854 char *cpathname;
855 PyCodeObject *co;
856 PyObject *m;
858 mtime = PyOS_GetLastModificationTime(pathname, fp);
859 if (mtime == (time_t)(-1))
860 return NULL;
861 #if SIZEOF_TIME_T > 4
862 /* Python's .pyc timestamp handling presumes that the timestamp fits
863 in 4 bytes. This will be fine until sometime in the year 2038,
864 when a 4-byte signed time_t will overflow.
866 if (mtime >> 32) {
867 PyErr_SetString(PyExc_OverflowError,
868 "modification time overflows a 4 byte field");
869 return NULL;
871 #endif
872 cpathname = make_compiled_pathname(pathname, buf,
873 (size_t)MAXPATHLEN + 1);
874 if (cpathname != NULL &&
875 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
876 co = read_compiled_module(cpathname, fpc);
877 fclose(fpc);
878 if (co == NULL)
879 return NULL;
880 if (Py_VerboseFlag)
881 PySys_WriteStderr("import %s # precompiled from %s\n",
882 name, cpathname);
883 pathname = cpathname;
885 else {
886 co = parse_source_module(pathname, fp);
887 if (co == NULL)
888 return NULL;
889 if (Py_VerboseFlag)
890 PySys_WriteStderr("import %s # from %s\n",
891 name, pathname);
892 write_compiled_module(co, cpathname, mtime);
894 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
895 Py_DECREF(co);
897 return m;
901 /* Forward */
902 static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
903 static struct filedescr *find_module(char *, char *, PyObject *,
904 char *, size_t, FILE **, PyObject **);
905 static struct _frozen *find_frozen(char *name);
907 /* Load a package and return its module object WITH INCREMENTED
908 REFERENCE COUNT */
910 static PyObject *
911 load_package(char *name, char *pathname)
913 PyObject *m, *d, *file, *path;
914 int err;
915 char buf[MAXPATHLEN+1];
916 FILE *fp = NULL;
917 struct filedescr *fdp;
919 m = PyImport_AddModule(name);
920 if (m == NULL)
921 return NULL;
922 if (Py_VerboseFlag)
923 PySys_WriteStderr("import %s # directory %s\n",
924 name, pathname);
925 d = PyModule_GetDict(m);
926 file = PyString_FromString(pathname);
927 if (file == NULL)
928 return NULL;
929 path = Py_BuildValue("[O]", file);
930 if (path == NULL) {
931 Py_DECREF(file);
932 return NULL;
934 err = PyDict_SetItemString(d, "__file__", file);
935 if (err == 0)
936 err = PyDict_SetItemString(d, "__path__", path);
937 if (err != 0) {
938 m = NULL;
939 goto cleanup;
941 buf[0] = '\0';
942 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
943 if (fdp == NULL) {
944 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
945 PyErr_Clear();
947 else
948 m = NULL;
949 goto cleanup;
951 m = load_module(name, fp, buf, fdp->type, NULL);
952 if (fp != NULL)
953 fclose(fp);
954 cleanup:
955 Py_XDECREF(path);
956 Py_XDECREF(file);
957 return m;
961 /* Helper to test for built-in module */
963 static int
964 is_builtin(char *name)
966 int i;
967 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
968 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
969 if (PyImport_Inittab[i].initfunc == NULL)
970 return -1;
971 else
972 return 1;
975 return 0;
979 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
980 possibly by fetching it from the path_importer_cache dict. If it
981 wasn't yet cached, traverse path_hooks until it a hook is found
982 that can handle the path item. Return None if no hook could;
983 this tells our caller it should fall back to the builtin
984 import mechanism. Cache the result in path_importer_cache.
985 Returns a borrowed reference. */
987 static PyObject *
988 get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
989 PyObject *p)
991 PyObject *importer;
992 int j, nhooks;
994 /* These conditions are the caller's responsibility: */
995 assert(PyList_Check(path_hooks));
996 assert(PyDict_Check(path_importer_cache));
998 nhooks = PyList_Size(path_hooks);
999 if (nhooks < 0)
1000 return NULL; /* Shouldn't happen */
1002 importer = PyDict_GetItem(path_importer_cache, p);
1003 if (importer != NULL)
1004 return importer;
1006 /* set path_importer_cache[p] to None to avoid recursion */
1007 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1008 return NULL;
1010 for (j = 0; j < nhooks; j++) {
1011 PyObject *hook = PyList_GetItem(path_hooks, j);
1012 if (hook == NULL)
1013 return NULL;
1014 importer = PyObject_CallFunction(hook, "O", p);
1015 if (importer != NULL)
1016 break;
1018 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1019 return NULL;
1021 PyErr_Clear();
1023 if (importer == NULL)
1024 importer = Py_None;
1025 else if (importer != Py_None) {
1026 int err = PyDict_SetItem(path_importer_cache, p, importer);
1027 Py_DECREF(importer);
1028 if (err != 0)
1029 return NULL;
1031 return importer;
1034 /* Search the path (default sys.path) for a module. Return the
1035 corresponding filedescr struct, and (via return arguments) the
1036 pathname and an open file. Return NULL if the module is not found. */
1038 #ifdef MS_COREDLL
1039 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
1040 char *, int);
1041 #endif
1043 static int case_ok(char *, int, int, char *);
1044 static int find_init_module(char *); /* Forward */
1045 static struct filedescr importhookdescr = {"", "", IMP_HOOK};
1047 static struct filedescr *
1048 find_module(char *fullname, char *subname, PyObject *path, char *buf,
1049 size_t buflen, FILE **p_fp, PyObject **p_loader)
1051 int i, npath;
1052 size_t len, namelen;
1053 struct filedescr *fdp = NULL;
1054 char *filemode;
1055 FILE *fp = NULL;
1056 PyObject *path_hooks, *path_importer_cache;
1057 #ifndef RISCOS
1058 struct stat statbuf;
1059 #endif
1060 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1061 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1062 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1063 char name[MAXPATHLEN+1];
1064 #if defined(PYOS_OS2)
1065 size_t saved_len;
1066 size_t saved_namelen;
1067 char *saved_buf = NULL;
1068 #endif
1069 if (p_loader != NULL)
1070 *p_loader = NULL;
1072 if (strlen(subname) > MAXPATHLEN) {
1073 PyErr_SetString(PyExc_OverflowError,
1074 "module name is too long");
1075 return NULL;
1077 strcpy(name, subname);
1079 /* sys.meta_path import hook */
1080 if (p_loader != NULL) {
1081 PyObject *meta_path;
1083 meta_path = PySys_GetObject("meta_path");
1084 if (meta_path == NULL || !PyList_Check(meta_path)) {
1085 PyErr_SetString(PyExc_ImportError,
1086 "sys.meta_path must be a list of "
1087 "import hooks");
1088 return NULL;
1090 Py_INCREF(meta_path); /* zap guard */
1091 npath = PyList_Size(meta_path);
1092 for (i = 0; i < npath; i++) {
1093 PyObject *loader;
1094 PyObject *hook = PyList_GetItem(meta_path, i);
1095 loader = PyObject_CallMethod(hook, "find_module",
1096 "sO", fullname,
1097 path != NULL ?
1098 path : Py_None);
1099 if (loader == NULL) {
1100 Py_DECREF(meta_path);
1101 return NULL; /* true error */
1103 if (loader != Py_None) {
1104 /* a loader was found */
1105 *p_loader = loader;
1106 Py_DECREF(meta_path);
1107 return &importhookdescr;
1109 Py_DECREF(loader);
1111 Py_DECREF(meta_path);
1114 if (path != NULL && PyString_Check(path)) {
1115 /* The only type of submodule allowed inside a "frozen"
1116 package are other frozen modules or packages. */
1117 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1118 PyErr_SetString(PyExc_ImportError,
1119 "full frozen module name too long");
1120 return NULL;
1122 strcpy(buf, PyString_AsString(path));
1123 strcat(buf, ".");
1124 strcat(buf, name);
1125 strcpy(name, buf);
1126 #ifdef macintosh
1127 /* Freezing on the mac works different, and the modules are
1128 ** actually on sys.path. So we don't take the quick exit but
1129 ** continue with the normal flow.
1131 path = NULL;
1132 #else
1133 if (find_frozen(name) != NULL) {
1134 strcpy(buf, name);
1135 return &fd_frozen;
1137 PyErr_Format(PyExc_ImportError,
1138 "No frozen submodule named %.200s", name);
1139 return NULL;
1140 #endif
1142 if (path == NULL) {
1143 if (is_builtin(name)) {
1144 strcpy(buf, name);
1145 return &fd_builtin;
1147 if ((find_frozen(name)) != NULL) {
1148 strcpy(buf, name);
1149 return &fd_frozen;
1152 #ifdef MS_COREDLL
1153 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1154 if (fp != NULL) {
1155 *p_fp = fp;
1156 return fdp;
1158 #endif
1159 path = PySys_GetObject("path");
1161 if (path == NULL || !PyList_Check(path)) {
1162 PyErr_SetString(PyExc_ImportError,
1163 "sys.path must be a list of directory names");
1164 return NULL;
1167 path_hooks = PySys_GetObject("path_hooks");
1168 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1169 PyErr_SetString(PyExc_ImportError,
1170 "sys.path_hooks must be a list of "
1171 "import hooks");
1172 return NULL;
1174 path_importer_cache = PySys_GetObject("path_importer_cache");
1175 if (path_importer_cache == NULL ||
1176 !PyDict_Check(path_importer_cache)) {
1177 PyErr_SetString(PyExc_ImportError,
1178 "sys.path_importer_cache must be a dict");
1179 return NULL;
1182 npath = PyList_Size(path);
1183 namelen = strlen(name);
1184 for (i = 0; i < npath; i++) {
1185 PyObject *copy = NULL;
1186 PyObject *v = PyList_GetItem(path, i);
1187 #ifdef Py_USING_UNICODE
1188 if (PyUnicode_Check(v)) {
1189 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1190 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1191 if (copy == NULL)
1192 return NULL;
1193 v = copy;
1195 else
1196 #endif
1197 if (!PyString_Check(v))
1198 continue;
1199 len = PyString_Size(v);
1200 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1201 Py_XDECREF(copy);
1202 continue; /* Too long */
1204 strcpy(buf, PyString_AsString(v));
1205 if (strlen(buf) != len) {
1206 Py_XDECREF(copy);
1207 continue; /* v contains '\0' */
1210 /* sys.path_hooks import hook */
1211 if (p_loader != NULL) {
1212 PyObject *importer;
1214 importer = get_path_importer(path_importer_cache,
1215 path_hooks, v);
1216 if (importer == NULL)
1217 return NULL;
1218 /* Note: importer is a borrowed reference */
1219 if (importer != Py_None) {
1220 PyObject *loader;
1221 loader = PyObject_CallMethod(importer,
1222 "find_module",
1223 "s", fullname);
1224 if (loader == NULL)
1225 return NULL; /* error */
1226 if (loader != Py_None) {
1227 /* a loader was found */
1228 *p_loader = loader;
1229 return &importhookdescr;
1231 Py_DECREF(loader);
1233 /* no hook was successful, use builtin import */
1236 #ifdef macintosh
1238 ** Speedup: each sys.path item is interned, and
1239 ** FindResourceModule remembers which items refer to
1240 ** folders (so we don't have to bother trying to look
1241 ** into them for resources). We only do this for string
1242 ** items.
1244 if (PyString_Check(PyList_GET_ITEM(path, i))) {
1245 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
1246 v = PyList_GET_ITEM(path, i);
1247 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
1248 static struct filedescr resfiledescr =
1249 {"", "", PY_RESOURCE};
1251 Py_XDECREF(copy);
1252 return &resfiledescr;
1254 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
1255 static struct filedescr resfiledescr =
1256 {"", "", PY_CODERESOURCE};
1258 Py_XDECREF(copy);
1259 return &resfiledescr;
1262 #endif
1263 if (len > 0 && buf[len-1] != SEP
1264 #ifdef ALTSEP
1265 && buf[len-1] != ALTSEP
1266 #endif
1268 buf[len++] = SEP;
1269 strcpy(buf+len, name);
1270 len += namelen;
1272 /* Check for package import (buf holds a directory name,
1273 and there's an __init__ module in that directory */
1274 #ifdef HAVE_STAT
1275 if (stat(buf, &statbuf) == 0 && /* it exists */
1276 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1277 find_init_module(buf) && /* it has __init__.py */
1278 case_ok(buf, len, namelen, name)) { /* and case matches */
1279 Py_XDECREF(copy);
1280 return &fd_package;
1282 #else
1283 /* XXX How are you going to test for directories? */
1284 #ifdef RISCOS
1285 if (isdir(buf) &&
1286 find_init_module(buf) &&
1287 case_ok(buf, len, namelen, name)) {
1288 Py_XDECREF(copy);
1289 return &fd_package;
1291 #endif
1292 #endif
1293 #ifdef macintosh
1294 fdp = PyMac_FindModuleExtension(buf, &len, name);
1295 if (fdp) {
1296 #else
1297 #if defined(PYOS_OS2)
1298 /* take a snapshot of the module spec for restoration
1299 * after the 8 character DLL hackery
1301 saved_buf = strdup(buf);
1302 saved_len = len;
1303 saved_namelen = namelen;
1304 #endif /* PYOS_OS2 */
1305 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1306 #if defined(PYOS_OS2)
1307 /* OS/2 limits DLLs to 8 character names (w/o
1308 extension)
1309 * so if the name is longer than that and its a
1310 * dynamically loaded module we're going to try,
1311 * truncate the name before trying
1313 if (strlen(subname) > 8) {
1314 /* is this an attempt to load a C extension? */
1315 const struct filedescr *scan;
1316 scan = _PyImport_DynLoadFiletab;
1317 while (scan->suffix != NULL) {
1318 if (!strcmp(scan->suffix, fdp->suffix))
1319 break;
1320 else
1321 scan++;
1323 if (scan->suffix != NULL) {
1324 /* yes, so truncate the name */
1325 namelen = 8;
1326 len -= strlen(subname) - namelen;
1327 buf[len] = '\0';
1330 #endif /* PYOS_OS2 */
1331 strcpy(buf+len, fdp->suffix);
1332 if (Py_VerboseFlag > 1)
1333 PySys_WriteStderr("# trying %s\n", buf);
1334 #endif /* !macintosh */
1335 filemode = fdp->mode;
1336 if (filemode[0] == 'U')
1337 filemode = "r" PY_STDIOTEXTMODE;
1338 fp = fopen(buf, filemode);
1339 if (fp != NULL) {
1340 if (case_ok(buf, len, namelen, name))
1341 break;
1342 else { /* continue search */
1343 fclose(fp);
1344 fp = NULL;
1347 #if defined(PYOS_OS2)
1348 /* restore the saved snapshot */
1349 strcpy(buf, saved_buf);
1350 len = saved_len;
1351 namelen = saved_namelen;
1352 #endif
1354 #if defined(PYOS_OS2)
1355 /* don't need/want the module name snapshot anymore */
1356 if (saved_buf)
1358 free(saved_buf);
1359 saved_buf = NULL;
1361 #endif
1362 Py_XDECREF(copy);
1363 if (fp != NULL)
1364 break;
1366 if (fp == NULL) {
1367 PyErr_Format(PyExc_ImportError,
1368 "No module named %.200s", name);
1369 return NULL;
1371 *p_fp = fp;
1372 return fdp;
1375 /* case_ok(char* buf, int len, int namelen, char* name)
1376 * The arguments here are tricky, best shown by example:
1377 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1378 * ^ ^ ^ ^
1379 * |--------------------- buf ---------------------|
1380 * |------------------- len ------------------|
1381 * |------ name -------|
1382 * |----- namelen -----|
1383 * buf is the full path, but len only counts up to (& exclusive of) the
1384 * extension. name is the module name, also exclusive of extension.
1386 * We've already done a successful stat() or fopen() on buf, so know that
1387 * there's some match, possibly case-insensitive.
1389 * case_ok() is to return 1 if there's a case-sensitive match for
1390 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1391 * exists.
1393 * case_ok() is used to implement case-sensitive import semantics even
1394 * on platforms with case-insensitive filesystems. It's trivial to implement
1395 * for case-sensitive filesystems. It's pretty much a cross-platform
1396 * nightmare for systems with case-insensitive filesystems.
1399 /* First we may need a pile of platform-specific header files; the sequence
1400 * of #if's here should match the sequence in the body of case_ok().
1402 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1403 #include <windows.h>
1404 #ifdef __CYGWIN__
1405 #include <sys/cygwin.h>
1406 #endif
1408 #elif defined(DJGPP)
1409 #include <dir.h>
1411 #elif defined(macintosh)
1412 #include <TextUtils.h>
1414 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1415 #include <sys/types.h>
1416 #include <dirent.h>
1418 #elif defined(PYOS_OS2)
1419 #define INCL_DOS
1420 #define INCL_DOSERRORS
1421 #define INCL_NOPMAPI
1422 #include <os2.h>
1424 #elif defined(RISCOS)
1425 #include "oslib/osfscontrol.h"
1426 #endif
1428 static int
1429 case_ok(char *buf, int len, int namelen, char *name)
1431 /* Pick a platform-specific implementation; the sequence of #if's here should
1432 * match the sequence just above.
1435 /* MS_WINDOWS || __CYGWIN__ */
1436 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1437 WIN32_FIND_DATA data;
1438 HANDLE h;
1439 #ifdef __CYGWIN__
1440 char tempbuf[MAX_PATH];
1441 #endif
1443 if (Py_GETENV("PYTHONCASEOK") != NULL)
1444 return 1;
1446 #ifdef __CYGWIN__
1447 cygwin32_conv_to_win32_path(buf, tempbuf);
1448 h = FindFirstFile(tempbuf, &data);
1449 #else
1450 h = FindFirstFile(buf, &data);
1451 #endif
1452 if (h == INVALID_HANDLE_VALUE) {
1453 PyErr_Format(PyExc_NameError,
1454 "Can't find file for module %.100s\n(filename %.300s)",
1455 name, buf);
1456 return 0;
1458 FindClose(h);
1459 return strncmp(data.cFileName, name, namelen) == 0;
1461 /* DJGPP */
1462 #elif defined(DJGPP)
1463 struct ffblk ffblk;
1464 int done;
1466 if (Py_GETENV("PYTHONCASEOK") != NULL)
1467 return 1;
1469 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1470 if (done) {
1471 PyErr_Format(PyExc_NameError,
1472 "Can't find file for module %.100s\n(filename %.300s)",
1473 name, buf);
1474 return 0;
1476 return strncmp(ffblk.ff_name, name, namelen) == 0;
1478 /* macintosh */
1479 #elif defined(macintosh)
1480 FSSpec fss;
1481 OSErr err;
1483 if (Py_GETENV("PYTHONCASEOK") != NULL)
1484 return 1;
1486 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
1487 if (err) {
1488 PyErr_Format(PyExc_NameError,
1489 "Can't find file for module %.100s\n(filename %.300s)",
1490 name, buf);
1491 return 0;
1493 return fss.name[0] >= namelen &&
1494 strncmp(name, (char *)fss.name+1, namelen) == 0;
1496 /* new-fangled macintosh (macosx) */
1497 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1498 DIR *dirp;
1499 struct dirent *dp;
1500 char dirname[MAXPATHLEN + 1];
1501 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1503 if (Py_GETENV("PYTHONCASEOK") != NULL)
1504 return 1;
1506 /* Copy the dir component into dirname; substitute "." if empty */
1507 if (dirlen <= 0) {
1508 dirname[0] = '.';
1509 dirname[1] = '\0';
1511 else {
1512 assert(dirlen <= MAXPATHLEN);
1513 memcpy(dirname, buf, dirlen);
1514 dirname[dirlen] = '\0';
1516 /* Open the directory and search the entries for an exact match. */
1517 dirp = opendir(dirname);
1518 if (dirp) {
1519 char *nameWithExt = buf + len - namelen;
1520 while ((dp = readdir(dirp)) != NULL) {
1521 const int thislen =
1522 #ifdef _DIRENT_HAVE_D_NAMELEN
1523 dp->d_namlen;
1524 #else
1525 strlen(dp->d_name);
1526 #endif
1527 if (thislen >= namelen &&
1528 strcmp(dp->d_name, nameWithExt) == 0) {
1529 (void)closedir(dirp);
1530 return 1; /* Found */
1533 (void)closedir(dirp);
1535 return 0 ; /* Not found */
1537 /* RISC OS */
1538 #elif defined(RISCOS)
1539 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1540 char buf2[MAXPATHLEN+2];
1541 char *nameWithExt = buf+len-namelen;
1542 int canonlen;
1543 os_error *e;
1545 if (Py_GETENV("PYTHONCASEOK") != NULL)
1546 return 1;
1548 /* workaround:
1549 append wildcard, otherwise case of filename wouldn't be touched */
1550 strcpy(buf2, buf);
1551 strcat(buf2, "*");
1553 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1554 canonlen = MAXPATHLEN+1-canonlen;
1555 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1556 return 0;
1557 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1558 return 1; /* match */
1560 return 0;
1562 /* OS/2 */
1563 #elif defined(PYOS_OS2)
1564 HDIR hdir = 1;
1565 ULONG srchcnt = 1;
1566 FILEFINDBUF3 ffbuf;
1567 APIRET rc;
1569 if (getenv("PYTHONCASEOK") != NULL)
1570 return 1;
1572 rc = DosFindFirst(buf,
1573 &hdir,
1574 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1575 &ffbuf, sizeof(ffbuf),
1576 &srchcnt,
1577 FIL_STANDARD);
1578 if (rc != NO_ERROR)
1579 return 0;
1580 return strncmp(ffbuf.achName, name, namelen) == 0;
1582 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1583 #else
1584 return 1;
1586 #endif
1590 #ifdef HAVE_STAT
1591 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1592 static int
1593 find_init_module(char *buf)
1595 const size_t save_len = strlen(buf);
1596 size_t i = save_len;
1597 char *pname; /* pointer to start of __init__ */
1598 struct stat statbuf;
1600 /* For calling case_ok(buf, len, namelen, name):
1601 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1602 * ^ ^ ^ ^
1603 * |--------------------- buf ---------------------|
1604 * |------------------- len ------------------|
1605 * |------ name -------|
1606 * |----- namelen -----|
1608 if (save_len + 13 >= MAXPATHLEN)
1609 return 0;
1610 buf[i++] = SEP;
1611 pname = buf + i;
1612 strcpy(pname, "__init__.py");
1613 if (stat(buf, &statbuf) == 0) {
1614 if (case_ok(buf,
1615 save_len + 9, /* len("/__init__") */
1616 8, /* len("__init__") */
1617 pname)) {
1618 buf[save_len] = '\0';
1619 return 1;
1622 i += strlen(pname);
1623 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1624 if (stat(buf, &statbuf) == 0) {
1625 if (case_ok(buf,
1626 save_len + 9, /* len("/__init__") */
1627 8, /* len("__init__") */
1628 pname)) {
1629 buf[save_len] = '\0';
1630 return 1;
1633 buf[save_len] = '\0';
1634 return 0;
1637 #else
1639 #ifdef RISCOS
1640 static int
1641 find_init_module(buf)
1642 char *buf;
1644 int save_len = strlen(buf);
1645 int i = save_len;
1647 if (save_len + 13 >= MAXPATHLEN)
1648 return 0;
1649 buf[i++] = SEP;
1650 strcpy(buf+i, "__init__/py");
1651 if (isfile(buf)) {
1652 buf[save_len] = '\0';
1653 return 1;
1656 if (Py_OptimizeFlag)
1657 strcpy(buf+i, "o");
1658 else
1659 strcpy(buf+i, "c");
1660 if (isfile(buf)) {
1661 buf[save_len] = '\0';
1662 return 1;
1664 buf[save_len] = '\0';
1665 return 0;
1667 #endif /*RISCOS*/
1669 #endif /* HAVE_STAT */
1672 static int init_builtin(char *); /* Forward */
1674 /* Load an external module using the default search path and return
1675 its module object WITH INCREMENTED REFERENCE COUNT */
1677 static PyObject *
1678 load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
1680 PyObject *modules;
1681 PyObject *m;
1682 int err;
1684 /* First check that there's an open file (if we need one) */
1685 switch (type) {
1686 case PY_SOURCE:
1687 case PY_COMPILED:
1688 if (fp == NULL) {
1689 PyErr_Format(PyExc_ValueError,
1690 "file object required for import (type code %d)",
1691 type);
1692 return NULL;
1696 switch (type) {
1698 case PY_SOURCE:
1699 m = load_source_module(name, buf, fp);
1700 break;
1702 case PY_COMPILED:
1703 m = load_compiled_module(name, buf, fp);
1704 break;
1706 #ifdef HAVE_DYNAMIC_LOADING
1707 case C_EXTENSION:
1708 m = _PyImport_LoadDynamicModule(name, buf, fp);
1709 break;
1710 #endif
1712 #ifdef macintosh
1713 case PY_RESOURCE:
1714 m = PyMac_LoadResourceModule(name, buf);
1715 break;
1716 case PY_CODERESOURCE:
1717 m = PyMac_LoadCodeResourceModule(name, buf);
1718 break;
1719 #endif
1721 case PKG_DIRECTORY:
1722 m = load_package(name, buf);
1723 break;
1725 case C_BUILTIN:
1726 case PY_FROZEN:
1727 if (buf != NULL && buf[0] != '\0')
1728 name = buf;
1729 if (type == C_BUILTIN)
1730 err = init_builtin(name);
1731 else
1732 err = PyImport_ImportFrozenModule(name);
1733 if (err < 0)
1734 return NULL;
1735 if (err == 0) {
1736 PyErr_Format(PyExc_ImportError,
1737 "Purported %s module %.200s not found",
1738 type == C_BUILTIN ?
1739 "builtin" : "frozen",
1740 name);
1741 return NULL;
1743 modules = PyImport_GetModuleDict();
1744 m = PyDict_GetItemString(modules, name);
1745 if (m == NULL) {
1746 PyErr_Format(
1747 PyExc_ImportError,
1748 "%s module %.200s not properly initialized",
1749 type == C_BUILTIN ?
1750 "builtin" : "frozen",
1751 name);
1752 return NULL;
1754 Py_INCREF(m);
1755 break;
1757 case IMP_HOOK: {
1758 if (loader == NULL) {
1759 PyErr_SetString(PyExc_ImportError,
1760 "import hook without loader");
1761 return NULL;
1763 m = PyObject_CallMethod(loader, "load_module", "s", name);
1764 break;
1767 default:
1768 PyErr_Format(PyExc_ImportError,
1769 "Don't know how to import %.200s (type code %d)",
1770 name, type);
1771 m = NULL;
1775 return m;
1779 /* Initialize a built-in module.
1780 Return 1 for succes, 0 if the module is not found, and -1 with
1781 an exception set if the initialization failed. */
1783 static int
1784 init_builtin(char *name)
1786 struct _inittab *p;
1788 if (_PyImport_FindExtension(name, name) != NULL)
1789 return 1;
1791 for (p = PyImport_Inittab; p->name != NULL; p++) {
1792 if (strcmp(name, p->name) == 0) {
1793 if (p->initfunc == NULL) {
1794 PyErr_Format(PyExc_ImportError,
1795 "Cannot re-init internal module %.200s",
1796 name);
1797 return -1;
1799 if (Py_VerboseFlag)
1800 PySys_WriteStderr("import %s # builtin\n", name);
1801 (*p->initfunc)();
1802 if (PyErr_Occurred())
1803 return -1;
1804 if (_PyImport_FixupExtension(name, name) == NULL)
1805 return -1;
1806 return 1;
1809 return 0;
1813 /* Frozen modules */
1815 static struct _frozen *
1816 find_frozen(char *name)
1818 struct _frozen *p;
1820 for (p = PyImport_FrozenModules; ; p++) {
1821 if (p->name == NULL)
1822 return NULL;
1823 if (strcmp(p->name, name) == 0)
1824 break;
1826 return p;
1829 static PyObject *
1830 get_frozen_object(char *name)
1832 struct _frozen *p = find_frozen(name);
1833 int size;
1835 if (p == NULL) {
1836 PyErr_Format(PyExc_ImportError,
1837 "No such frozen object named %.200s",
1838 name);
1839 return NULL;
1841 if (p->code == NULL) {
1842 PyErr_Format(PyExc_ImportError,
1843 "Excluded frozen object named %.200s",
1844 name);
1845 return NULL;
1847 size = p->size;
1848 if (size < 0)
1849 size = -size;
1850 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1853 /* Initialize a frozen module.
1854 Return 1 for succes, 0 if the module is not found, and -1 with
1855 an exception set if the initialization failed.
1856 This function is also used from frozenmain.c */
1859 PyImport_ImportFrozenModule(char *name)
1861 struct _frozen *p = find_frozen(name);
1862 PyObject *co;
1863 PyObject *m;
1864 int ispackage;
1865 int size;
1867 if (p == NULL)
1868 return 0;
1869 if (p->code == NULL) {
1870 PyErr_Format(PyExc_ImportError,
1871 "Excluded frozen object named %.200s",
1872 name);
1873 return -1;
1875 size = p->size;
1876 ispackage = (size < 0);
1877 if (ispackage)
1878 size = -size;
1879 if (Py_VerboseFlag)
1880 PySys_WriteStderr("import %s # frozen%s\n",
1881 name, ispackage ? " package" : "");
1882 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1883 if (co == NULL)
1884 return -1;
1885 if (!PyCode_Check(co)) {
1886 Py_DECREF(co);
1887 PyErr_Format(PyExc_TypeError,
1888 "frozen object %.200s is not a code object",
1889 name);
1890 return -1;
1892 if (ispackage) {
1893 /* Set __path__ to the package name */
1894 PyObject *d, *s;
1895 int err;
1896 m = PyImport_AddModule(name);
1897 if (m == NULL)
1898 return -1;
1899 d = PyModule_GetDict(m);
1900 s = PyString_InternFromString(name);
1901 if (s == NULL)
1902 return -1;
1903 err = PyDict_SetItemString(d, "__path__", s);
1904 Py_DECREF(s);
1905 if (err != 0)
1906 return err;
1908 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1909 Py_DECREF(co);
1910 if (m == NULL)
1911 return -1;
1912 Py_DECREF(m);
1913 return 1;
1917 /* Import a module, either built-in, frozen, or external, and return
1918 its module object WITH INCREMENTED REFERENCE COUNT */
1920 PyObject *
1921 PyImport_ImportModule(char *name)
1923 PyObject *pname;
1924 PyObject *result;
1926 pname = PyString_FromString(name);
1927 if (pname == NULL)
1928 return NULL;
1929 result = PyImport_Import(pname);
1930 Py_DECREF(pname);
1931 return result;
1934 /* Forward declarations for helper routines */
1935 static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1936 static PyObject *load_next(PyObject *mod, PyObject *altmod,
1937 char **p_name, char *buf, int *p_buflen);
1938 static int mark_miss(char *name);
1939 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1940 char *buf, int buflen, int recursive);
1941 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1943 /* The Magnum Opus of dotted-name import :-) */
1945 static PyObject *
1946 import_module_ex(char *name, PyObject *globals, PyObject *locals,
1947 PyObject *fromlist)
1949 char buf[MAXPATHLEN+1];
1950 int buflen = 0;
1951 PyObject *parent, *head, *next, *tail;
1953 parent = get_parent(globals, buf, &buflen);
1954 if (parent == NULL)
1955 return NULL;
1957 head = load_next(parent, Py_None, &name, buf, &buflen);
1958 if (head == NULL)
1959 return NULL;
1961 tail = head;
1962 Py_INCREF(tail);
1963 while (name) {
1964 next = load_next(tail, tail, &name, buf, &buflen);
1965 Py_DECREF(tail);
1966 if (next == NULL) {
1967 Py_DECREF(head);
1968 return NULL;
1970 tail = next;
1973 if (fromlist != NULL) {
1974 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1975 fromlist = NULL;
1978 if (fromlist == NULL) {
1979 Py_DECREF(tail);
1980 return head;
1983 Py_DECREF(head);
1984 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
1985 Py_DECREF(tail);
1986 return NULL;
1989 return tail;
1992 PyObject *
1993 PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1994 PyObject *fromlist)
1996 PyObject *result;
1997 lock_import();
1998 result = import_module_ex(name, globals, locals, fromlist);
1999 if (unlock_import() < 0) {
2000 Py_XDECREF(result);
2001 PyErr_SetString(PyExc_RuntimeError,
2002 "not holding the import lock");
2003 return NULL;
2005 return result;
2008 static PyObject *
2009 get_parent(PyObject *globals, char *buf, int *p_buflen)
2011 static PyObject *namestr = NULL;
2012 static PyObject *pathstr = NULL;
2013 PyObject *modname, *modpath, *modules, *parent;
2015 if (globals == NULL || !PyDict_Check(globals))
2016 return Py_None;
2018 if (namestr == NULL) {
2019 namestr = PyString_InternFromString("__name__");
2020 if (namestr == NULL)
2021 return NULL;
2023 if (pathstr == NULL) {
2024 pathstr = PyString_InternFromString("__path__");
2025 if (pathstr == NULL)
2026 return NULL;
2029 *buf = '\0';
2030 *p_buflen = 0;
2031 modname = PyDict_GetItem(globals, namestr);
2032 if (modname == NULL || !PyString_Check(modname))
2033 return Py_None;
2035 modpath = PyDict_GetItem(globals, pathstr);
2036 if (modpath != NULL) {
2037 int len = PyString_GET_SIZE(modname);
2038 if (len > MAXPATHLEN) {
2039 PyErr_SetString(PyExc_ValueError,
2040 "Module name too long");
2041 return NULL;
2043 strcpy(buf, PyString_AS_STRING(modname));
2044 *p_buflen = len;
2046 else {
2047 char *start = PyString_AS_STRING(modname);
2048 char *lastdot = strrchr(start, '.');
2049 size_t len;
2050 if (lastdot == NULL)
2051 return Py_None;
2052 len = lastdot - start;
2053 if (len >= MAXPATHLEN) {
2054 PyErr_SetString(PyExc_ValueError,
2055 "Module name too long");
2056 return NULL;
2058 strncpy(buf, start, len);
2059 buf[len] = '\0';
2060 *p_buflen = len;
2063 modules = PyImport_GetModuleDict();
2064 parent = PyDict_GetItemString(modules, buf);
2065 if (parent == NULL)
2066 parent = Py_None;
2067 return parent;
2068 /* We expect, but can't guarantee, if parent != None, that:
2069 - parent.__name__ == buf
2070 - parent.__dict__ is globals
2071 If this is violated... Who cares? */
2074 /* altmod is either None or same as mod */
2075 static PyObject *
2076 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
2077 int *p_buflen)
2079 char *name = *p_name;
2080 char *dot = strchr(name, '.');
2081 size_t len;
2082 char *p;
2083 PyObject *result;
2085 if (dot == NULL) {
2086 *p_name = NULL;
2087 len = strlen(name);
2089 else {
2090 *p_name = dot+1;
2091 len = dot-name;
2093 if (len == 0) {
2094 PyErr_SetString(PyExc_ValueError,
2095 "Empty module name");
2096 return NULL;
2099 p = buf + *p_buflen;
2100 if (p != buf)
2101 *p++ = '.';
2102 if (p+len-buf >= MAXPATHLEN) {
2103 PyErr_SetString(PyExc_ValueError,
2104 "Module name too long");
2105 return NULL;
2107 strncpy(p, name, len);
2108 p[len] = '\0';
2109 *p_buflen = p+len-buf;
2111 result = import_submodule(mod, p, buf);
2112 if (result == Py_None && altmod != mod) {
2113 Py_DECREF(result);
2114 /* Here, altmod must be None and mod must not be None */
2115 result = import_submodule(altmod, p, p);
2116 if (result != NULL && result != Py_None) {
2117 if (mark_miss(buf) != 0) {
2118 Py_DECREF(result);
2119 return NULL;
2121 strncpy(buf, name, len);
2122 buf[len] = '\0';
2123 *p_buflen = len;
2126 if (result == NULL)
2127 return NULL;
2129 if (result == Py_None) {
2130 Py_DECREF(result);
2131 PyErr_Format(PyExc_ImportError,
2132 "No module named %.200s", name);
2133 return NULL;
2136 return result;
2139 static int
2140 mark_miss(char *name)
2142 PyObject *modules = PyImport_GetModuleDict();
2143 return PyDict_SetItemString(modules, name, Py_None);
2146 static int
2147 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
2148 int recursive)
2150 int i;
2152 if (!PyObject_HasAttrString(mod, "__path__"))
2153 return 1;
2155 for (i = 0; ; i++) {
2156 PyObject *item = PySequence_GetItem(fromlist, i);
2157 int hasit;
2158 if (item == NULL) {
2159 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2160 PyErr_Clear();
2161 return 1;
2163 return 0;
2165 if (!PyString_Check(item)) {
2166 PyErr_SetString(PyExc_TypeError,
2167 "Item in ``from list'' not a string");
2168 Py_DECREF(item);
2169 return 0;
2171 if (PyString_AS_STRING(item)[0] == '*') {
2172 PyObject *all;
2173 Py_DECREF(item);
2174 /* See if the package defines __all__ */
2175 if (recursive)
2176 continue; /* Avoid endless recursion */
2177 all = PyObject_GetAttrString(mod, "__all__");
2178 if (all == NULL)
2179 PyErr_Clear();
2180 else {
2181 if (!ensure_fromlist(mod, all, buf, buflen, 1))
2182 return 0;
2183 Py_DECREF(all);
2185 continue;
2187 hasit = PyObject_HasAttr(mod, item);
2188 if (!hasit) {
2189 char *subname = PyString_AS_STRING(item);
2190 PyObject *submod;
2191 char *p;
2192 if (buflen + strlen(subname) >= MAXPATHLEN) {
2193 PyErr_SetString(PyExc_ValueError,
2194 "Module name too long");
2195 Py_DECREF(item);
2196 return 0;
2198 p = buf + buflen;
2199 *p++ = '.';
2200 strcpy(p, subname);
2201 submod = import_submodule(mod, subname, buf);
2202 Py_XDECREF(submod);
2203 if (submod == NULL) {
2204 Py_DECREF(item);
2205 return 0;
2208 Py_DECREF(item);
2211 /* NOTREACHED */
2214 static PyObject *
2215 import_submodule(PyObject *mod, char *subname, char *fullname)
2217 PyObject *modules = PyImport_GetModuleDict();
2218 PyObject *m, *res = NULL;
2220 /* Require:
2221 if mod == None: subname == fullname
2222 else: mod.__name__ + "." + subname == fullname
2225 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2226 Py_INCREF(m);
2228 else {
2229 PyObject *path, *loader = NULL;
2230 char buf[MAXPATHLEN+1];
2231 struct filedescr *fdp;
2232 FILE *fp = NULL;
2234 if (mod == Py_None)
2235 path = NULL;
2236 else {
2237 path = PyObject_GetAttrString(mod, "__path__");
2238 if (path == NULL) {
2239 PyErr_Clear();
2240 Py_INCREF(Py_None);
2241 return Py_None;
2245 buf[0] = '\0';
2246 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2247 &fp, &loader);
2248 Py_XDECREF(path);
2249 if (fdp == NULL) {
2250 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2251 return NULL;
2252 PyErr_Clear();
2253 Py_INCREF(Py_None);
2254 return Py_None;
2256 m = load_module(fullname, fp, buf, fdp->type, loader);
2257 Py_XDECREF(loader);
2258 if (fp)
2259 fclose(fp);
2260 if (mod != Py_None) {
2261 /* Irrespective of the success of this load, make a
2262 reference to it in the parent package module.
2263 A copy gets saved in the modules dictionary
2264 under the full name, so get a reference from
2265 there, if need be. (The exception is when
2266 the load failed with a SyntaxError -- then
2267 there's no trace in sys.modules. In that case,
2268 of course, do nothing extra.) */
2269 res = m;
2270 if (res == NULL)
2271 res = PyDict_GetItemString(modules, fullname);
2272 if (res != NULL &&
2273 PyObject_SetAttrString(mod, subname, res) < 0) {
2274 Py_XDECREF(m);
2275 m = NULL;
2280 return m;
2284 /* Re-import a module of any kind and return its module object, WITH
2285 INCREMENTED REFERENCE COUNT */
2287 PyObject *
2288 PyImport_ReloadModule(PyObject *m)
2290 PyObject *modules = PyImport_GetModuleDict();
2291 PyObject *path = NULL;
2292 char *name, *subname;
2293 char buf[MAXPATHLEN+1];
2294 struct filedescr *fdp;
2295 FILE *fp = NULL;
2297 if (m == NULL || !PyModule_Check(m)) {
2298 PyErr_SetString(PyExc_TypeError,
2299 "reload() argument must be module");
2300 return NULL;
2302 name = PyModule_GetName(m);
2303 if (name == NULL)
2304 return NULL;
2305 if (m != PyDict_GetItemString(modules, name)) {
2306 PyErr_Format(PyExc_ImportError,
2307 "reload(): module %.200s not in sys.modules",
2308 name);
2309 return NULL;
2311 subname = strrchr(name, '.');
2312 if (subname == NULL)
2313 subname = name;
2314 else {
2315 PyObject *parentname, *parent;
2316 parentname = PyString_FromStringAndSize(name, (subname-name));
2317 if (parentname == NULL)
2318 return NULL;
2319 parent = PyDict_GetItem(modules, parentname);
2320 Py_DECREF(parentname);
2321 if (parent == NULL) {
2322 PyErr_Format(PyExc_ImportError,
2323 "reload(): parent %.200s not in sys.modules",
2324 name);
2325 return NULL;
2327 subname++;
2328 path = PyObject_GetAttrString(parent, "__path__");
2329 if (path == NULL)
2330 PyErr_Clear();
2332 buf[0] = '\0';
2333 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, NULL);
2334 Py_XDECREF(path);
2335 if (fdp == NULL)
2336 return NULL;
2337 m = load_module(name, fp, buf, fdp->type, NULL);
2338 if (fp)
2339 fclose(fp);
2340 return m;
2344 /* Higher-level import emulator which emulates the "import" statement
2345 more accurately -- it invokes the __import__() function from the
2346 builtins of the current globals. This means that the import is
2347 done using whatever import hooks are installed in the current
2348 environment, e.g. by "rexec".
2349 A dummy list ["__doc__"] is passed as the 4th argument so that
2350 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2351 will return <module "gencache"> instead of <module "win32com">. */
2353 PyObject *
2354 PyImport_Import(PyObject *module_name)
2356 static PyObject *silly_list = NULL;
2357 static PyObject *builtins_str = NULL;
2358 static PyObject *import_str = NULL;
2359 PyObject *globals = NULL;
2360 PyObject *import = NULL;
2361 PyObject *builtins = NULL;
2362 PyObject *r = NULL;
2364 /* Initialize constant string objects */
2365 if (silly_list == NULL) {
2366 import_str = PyString_InternFromString("__import__");
2367 if (import_str == NULL)
2368 return NULL;
2369 builtins_str = PyString_InternFromString("__builtins__");
2370 if (builtins_str == NULL)
2371 return NULL;
2372 silly_list = Py_BuildValue("[s]", "__doc__");
2373 if (silly_list == NULL)
2374 return NULL;
2377 /* Get the builtins from current globals */
2378 globals = PyEval_GetGlobals();
2379 if (globals != NULL) {
2380 Py_INCREF(globals);
2381 builtins = PyObject_GetItem(globals, builtins_str);
2382 if (builtins == NULL)
2383 goto err;
2385 else {
2386 /* No globals -- use standard builtins, and fake globals */
2387 PyErr_Clear();
2389 builtins = PyImport_ImportModuleEx("__builtin__",
2390 NULL, NULL, NULL);
2391 if (builtins == NULL)
2392 return NULL;
2393 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2394 if (globals == NULL)
2395 goto err;
2398 /* Get the __import__ function from the builtins */
2399 if (PyDict_Check(builtins)) {
2400 import = PyObject_GetItem(builtins, import_str);
2401 if (import == NULL)
2402 PyErr_SetObject(PyExc_KeyError, import_str);
2404 else
2405 import = PyObject_GetAttr(builtins, import_str);
2406 if (import == NULL)
2407 goto err;
2409 /* Call the _import__ function with the proper argument list */
2410 r = PyObject_CallFunction(import, "OOOO",
2411 module_name, globals, globals, silly_list);
2413 err:
2414 Py_XDECREF(globals);
2415 Py_XDECREF(builtins);
2416 Py_XDECREF(import);
2418 return r;
2422 /* Module 'imp' provides Python access to the primitives used for
2423 importing modules.
2426 static PyObject *
2427 imp_get_magic(PyObject *self, PyObject *noargs)
2429 char buf[4];
2431 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2432 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2433 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2434 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2436 return PyString_FromStringAndSize(buf, 4);
2439 static PyObject *
2440 imp_get_suffixes(PyObject *self, PyObject *noargs)
2442 PyObject *list;
2443 struct filedescr *fdp;
2445 list = PyList_New(0);
2446 if (list == NULL)
2447 return NULL;
2448 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2449 PyObject *item = Py_BuildValue("ssi",
2450 fdp->suffix, fdp->mode, fdp->type);
2451 if (item == NULL) {
2452 Py_DECREF(list);
2453 return NULL;
2455 if (PyList_Append(list, item) < 0) {
2456 Py_DECREF(list);
2457 Py_DECREF(item);
2458 return NULL;
2460 Py_DECREF(item);
2462 return list;
2465 static PyObject *
2466 call_find_module(char *name, PyObject *path)
2468 extern int fclose(FILE *);
2469 PyObject *fob, *ret;
2470 struct filedescr *fdp;
2471 char pathname[MAXPATHLEN+1];
2472 FILE *fp = NULL;
2474 pathname[0] = '\0';
2475 if (path == Py_None)
2476 path = NULL;
2477 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
2478 if (fdp == NULL)
2479 return NULL;
2480 if (fp != NULL) {
2481 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2482 if (fob == NULL) {
2483 fclose(fp);
2484 return NULL;
2487 else {
2488 fob = Py_None;
2489 Py_INCREF(fob);
2491 ret = Py_BuildValue("Os(ssi)",
2492 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2493 Py_DECREF(fob);
2494 return ret;
2497 static PyObject *
2498 imp_find_module(PyObject *self, PyObject *args)
2500 char *name;
2501 PyObject *path = NULL;
2502 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2503 return NULL;
2504 return call_find_module(name, path);
2507 static PyObject *
2508 imp_init_builtin(PyObject *self, PyObject *args)
2510 char *name;
2511 int ret;
2512 PyObject *m;
2513 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2514 return NULL;
2515 ret = init_builtin(name);
2516 if (ret < 0)
2517 return NULL;
2518 if (ret == 0) {
2519 Py_INCREF(Py_None);
2520 return Py_None;
2522 m = PyImport_AddModule(name);
2523 Py_XINCREF(m);
2524 return m;
2527 static PyObject *
2528 imp_init_frozen(PyObject *self, PyObject *args)
2530 char *name;
2531 int ret;
2532 PyObject *m;
2533 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2534 return NULL;
2535 ret = PyImport_ImportFrozenModule(name);
2536 if (ret < 0)
2537 return NULL;
2538 if (ret == 0) {
2539 Py_INCREF(Py_None);
2540 return Py_None;
2542 m = PyImport_AddModule(name);
2543 Py_XINCREF(m);
2544 return m;
2547 static PyObject *
2548 imp_get_frozen_object(PyObject *self, PyObject *args)
2550 char *name;
2552 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2553 return NULL;
2554 return get_frozen_object(name);
2557 static PyObject *
2558 imp_is_builtin(PyObject *self, PyObject *args)
2560 char *name;
2561 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2562 return NULL;
2563 return PyInt_FromLong(is_builtin(name));
2566 static PyObject *
2567 imp_is_frozen(PyObject *self, PyObject *args)
2569 char *name;
2570 struct _frozen *p;
2571 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2572 return NULL;
2573 p = find_frozen(name);
2574 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2577 static FILE *
2578 get_file(char *pathname, PyObject *fob, char *mode)
2580 FILE *fp;
2581 if (fob == NULL) {
2582 if (mode[0] == 'U')
2583 mode = "r" PY_STDIOTEXTMODE;
2584 fp = fopen(pathname, mode);
2585 if (fp == NULL)
2586 PyErr_SetFromErrno(PyExc_IOError);
2588 else {
2589 fp = PyFile_AsFile(fob);
2590 if (fp == NULL)
2591 PyErr_SetString(PyExc_ValueError,
2592 "bad/closed file object");
2594 return fp;
2597 static PyObject *
2598 imp_load_compiled(PyObject *self, PyObject *args)
2600 char *name;
2601 char *pathname;
2602 PyObject *fob = NULL;
2603 PyObject *m;
2604 FILE *fp;
2605 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2606 &PyFile_Type, &fob))
2607 return NULL;
2608 fp = get_file(pathname, fob, "rb");
2609 if (fp == NULL)
2610 return NULL;
2611 m = load_compiled_module(name, pathname, fp);
2612 if (fob == NULL)
2613 fclose(fp);
2614 return m;
2617 #ifdef HAVE_DYNAMIC_LOADING
2619 static PyObject *
2620 imp_load_dynamic(PyObject *self, PyObject *args)
2622 char *name;
2623 char *pathname;
2624 PyObject *fob = NULL;
2625 PyObject *m;
2626 FILE *fp = NULL;
2627 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2628 &PyFile_Type, &fob))
2629 return NULL;
2630 if (fob) {
2631 fp = get_file(pathname, fob, "r");
2632 if (fp == NULL)
2633 return NULL;
2635 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2636 return m;
2639 #endif /* HAVE_DYNAMIC_LOADING */
2641 static PyObject *
2642 imp_load_source(PyObject *self, PyObject *args)
2644 char *name;
2645 char *pathname;
2646 PyObject *fob = NULL;
2647 PyObject *m;
2648 FILE *fp;
2649 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2650 &PyFile_Type, &fob))
2651 return NULL;
2652 fp = get_file(pathname, fob, "r");
2653 if (fp == NULL)
2654 return NULL;
2655 m = load_source_module(name, pathname, fp);
2656 if (fob == NULL)
2657 fclose(fp);
2658 return m;
2661 #ifdef macintosh
2662 static PyObject *
2663 imp_load_resource(PyObject *self, PyObject *args)
2665 char *name;
2666 char *pathname;
2667 PyObject *m;
2669 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
2670 return NULL;
2671 m = PyMac_LoadResourceModule(name, pathname);
2672 return m;
2674 #endif /* macintosh */
2676 static PyObject *
2677 imp_load_module(PyObject *self, PyObject *args)
2679 char *name;
2680 PyObject *fob;
2681 char *pathname;
2682 char *suffix; /* Unused */
2683 char *mode;
2684 int type;
2685 FILE *fp;
2687 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2688 &name, &fob, &pathname,
2689 &suffix, &mode, &type))
2690 return NULL;
2691 if (*mode) {
2692 /* Mode must start with 'r' or 'U' and must not contain '+'.
2693 Implicit in this test is the assumption that the mode
2694 may contain other modifiers like 'b' or 't'. */
2696 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
2697 PyErr_Format(PyExc_ValueError,
2698 "invalid file open mode %.200s", mode);
2699 return NULL;
2702 if (fob == Py_None)
2703 fp = NULL;
2704 else {
2705 if (!PyFile_Check(fob)) {
2706 PyErr_SetString(PyExc_ValueError,
2707 "load_module arg#2 should be a file or None");
2708 return NULL;
2710 fp = get_file(pathname, fob, mode);
2711 if (fp == NULL)
2712 return NULL;
2714 return load_module(name, fp, pathname, type, NULL);
2717 static PyObject *
2718 imp_load_package(PyObject *self, PyObject *args)
2720 char *name;
2721 char *pathname;
2722 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2723 return NULL;
2724 return load_package(name, pathname);
2727 static PyObject *
2728 imp_new_module(PyObject *self, PyObject *args)
2730 char *name;
2731 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2732 return NULL;
2733 return PyModule_New(name);
2736 /* Doc strings */
2738 PyDoc_STRVAR(doc_imp,
2739 "This module provides the components needed to build your own\n\
2740 __import__ function. Undocumented functions are obsolete.");
2742 PyDoc_STRVAR(doc_find_module,
2743 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2744 Search for a module. If path is omitted or None, search for a\n\
2745 built-in, frozen or special module and continue search in sys.path.\n\
2746 The module name cannot contain '.'; to search for a submodule of a\n\
2747 package, pass the submodule name and the package's __path__.");
2749 PyDoc_STRVAR(doc_load_module,
2750 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2751 Load a module, given information returned by find_module().\n\
2752 The module name must include the full package name, if any.");
2754 PyDoc_STRVAR(doc_get_magic,
2755 "get_magic() -> string\n\
2756 Return the magic number for .pyc or .pyo files.");
2758 PyDoc_STRVAR(doc_get_suffixes,
2759 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2760 Return a list of (suffix, mode, type) tuples describing the files\n\
2761 that find_module() looks for.");
2763 PyDoc_STRVAR(doc_new_module,
2764 "new_module(name) -> module\n\
2765 Create a new module. Do not enter it in sys.modules.\n\
2766 The module name must include the full package name, if any.");
2768 PyDoc_STRVAR(doc_lock_held,
2769 "lock_held() -> 0 or 1\n\
2770 Return 1 if the import lock is currently held.\n\
2771 On platforms without threads, return 0.");
2773 PyDoc_STRVAR(doc_acquire_lock,
2774 "acquire_lock() -> None\n\
2775 Acquires the interpreter's import lock for the current thread.\n\
2776 This lock should be used by import hooks to ensure thread-safety\n\
2777 when importing modules.\n\
2778 On platforms without threads, this function does nothing.");
2780 PyDoc_STRVAR(doc_release_lock,
2781 "release_lock() -> None\n\
2782 Release the interpreter's import lock.\n\
2783 On platforms without threads, this function does nothing.");
2785 static PyMethodDef imp_methods[] = {
2786 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2787 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2788 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2789 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2790 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2791 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2792 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2793 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
2794 /* The rest are obsolete */
2795 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2796 {"init_builtin", imp_init_builtin, METH_VARARGS},
2797 {"init_frozen", imp_init_frozen, METH_VARARGS},
2798 {"is_builtin", imp_is_builtin, METH_VARARGS},
2799 {"is_frozen", imp_is_frozen, METH_VARARGS},
2800 {"load_compiled", imp_load_compiled, METH_VARARGS},
2801 #ifdef HAVE_DYNAMIC_LOADING
2802 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
2803 #endif
2804 {"load_package", imp_load_package, METH_VARARGS},
2805 #ifdef macintosh
2806 {"load_resource", imp_load_resource, METH_VARARGS},
2807 #endif
2808 {"load_source", imp_load_source, METH_VARARGS},
2809 {NULL, NULL} /* sentinel */
2812 static int
2813 setint(PyObject *d, char *name, int value)
2815 PyObject *v;
2816 int err;
2818 v = PyInt_FromLong((long)value);
2819 err = PyDict_SetItemString(d, name, v);
2820 Py_XDECREF(v);
2821 return err;
2824 void
2825 initimp(void)
2827 PyObject *m, *d;
2829 m = Py_InitModule4("imp", imp_methods, doc_imp,
2830 NULL, PYTHON_API_VERSION);
2831 d = PyModule_GetDict(m);
2833 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2834 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2835 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2836 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2837 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2838 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2839 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2840 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2841 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2842 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
2844 failure:
2849 /* API for embedding applications that want to add their own entries
2850 to the table of built-in modules. This should normally be called
2851 *before* Py_Initialize(). When the table resize fails, -1 is
2852 returned and the existing table is unchanged.
2854 After a similar function by Just van Rossum. */
2857 PyImport_ExtendInittab(struct _inittab *newtab)
2859 static struct _inittab *our_copy = NULL;
2860 struct _inittab *p;
2861 int i, n;
2863 /* Count the number of entries in both tables */
2864 for (n = 0; newtab[n].name != NULL; n++)
2866 if (n == 0)
2867 return 0; /* Nothing to do */
2868 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2871 /* Allocate new memory for the combined table */
2872 p = our_copy;
2873 PyMem_RESIZE(p, struct _inittab, i+n+1);
2874 if (p == NULL)
2875 return -1;
2877 /* Copy the tables into the new memory */
2878 if (our_copy != PyImport_Inittab)
2879 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2880 PyImport_Inittab = our_copy = p;
2881 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2883 return 0;
2886 /* Shorthand to add a single entry given a name and a function */
2889 PyImport_AppendInittab(char *name, void (*initfunc)(void))
2891 struct _inittab newtab[2];
2893 memset(newtab, '\0', sizeof newtab);
2895 newtab[0].name = name;
2896 newtab[0].initfunc = initfunc;
2898 return PyImport_ExtendInittab(newtab);