Update to 2.7.3
[profile/ivi/python.git] / Python / import.c
1
2 /* Module definition and import implementation */
3
4 #include "Python.h"
5
6 #include "Python-ast.h"
7 #undef Yield /* undefine macro conflicting with winbase.h */
8 #include "pyarena.h"
9 #include "pythonrun.h"
10 #include "errcode.h"
11 #include "marshal.h"
12 #include "code.h"
13 #include "compile.h"
14 #include "eval.h"
15 #include "osdefs.h"
16 #include "importdl.h"
17
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
21 #ifdef __cplusplus
22 extern "C" {
23 #endif
24
25 #ifdef MS_WINDOWS
26 /* for stat.st_mode */
27 typedef unsigned short mode_t;
28 #endif
29
30
31 /* Magic word to reject .pyc files generated by other Python versions.
32    It should change for each incompatible change to the bytecode.
33
34    The value of CR and LF is incorporated so if you ever read or write
35    a .pyc file in text mode the magic number will be wrong; also, the
36    Apple MPW compiler swaps their values, botching string constants.
37
38    The magic numbers must be spaced apart atleast 2 values, as the
39    -U interpeter flag will cause MAGIC+1 being used. They have been
40    odd numbers for some time now.
41
42    There were a variety of old schemes for setting the magic number.
43    The current working scheme is to increment the previous value by
44    10.
45
46    Known values:
47        Python 1.5:   20121
48        Python 1.5.1: 20121
49        Python 1.5.2: 20121
50        Python 1.6:   50428
51        Python 2.0:   50823
52        Python 2.0.1: 50823
53        Python 2.1:   60202
54        Python 2.1.1: 60202
55        Python 2.1.2: 60202
56        Python 2.2:   60717
57        Python 2.3a0: 62011
58        Python 2.3a0: 62021
59        Python 2.3a0: 62011 (!)
60        Python 2.4a0: 62041
61        Python 2.4a3: 62051
62        Python 2.4b1: 62061
63        Python 2.5a0: 62071
64        Python 2.5a0: 62081 (ast-branch)
65        Python 2.5a0: 62091 (with)
66        Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
67        Python 2.5b3: 62101 (fix wrong code: for x, in ...)
68        Python 2.5b3: 62111 (fix wrong code: x += yield)
69        Python 2.5c1: 62121 (fix wrong lnotab with for loops and
70                             storing constants that should have been removed)
71        Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
72        Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
73        Python 2.6a1: 62161 (WITH_CLEANUP optimization)
74        Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
75        Python 2.7a0: 62181 (optimize conditional branches:
76                 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
77        Python 2.7a0  62191 (introduce SETUP_WITH)
78        Python 2.7a0  62201 (introduce BUILD_SET)
79        Python 2.7a0  62211 (introduce MAP_ADD and SET_ADD)
80 .
81 */
82 #define MAGIC (62211 | ((long)'\r'<<16) | ((long)'\n'<<24))
83
84 /* Magic word as global; note that _PyImport_Init() can change the
85    value of this global to accommodate for alterations of how the
86    compiler works which are enabled by command line switches. */
87 static long pyc_magic = MAGIC;
88
89 /* See _PyImport_FixupExtension() below */
90 static PyObject *extensions = NULL;
91
92 /* This table is defined in config.c: */
93 extern struct _inittab _PyImport_Inittab[];
94
95 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
96
97 /* these tables define the module suffixes that Python recognizes */
98 struct filedescr * _PyImport_Filetab = NULL;
99
100 #ifdef RISCOS
101 static const struct filedescr _PyImport_StandardFiletab[] = {
102     {"/py", "U", PY_SOURCE},
103     {"/pyc", "rb", PY_COMPILED},
104     {0, 0}
105 };
106 #else
107 static const struct filedescr _PyImport_StandardFiletab[] = {
108     {".py", "U", PY_SOURCE},
109 #ifdef MS_WINDOWS
110     {".pyw", "U", PY_SOURCE},
111 #endif
112     {".pyc", "rb", PY_COMPILED},
113     {0, 0}
114 };
115 #endif
116
117
118 /* Initialize things */
119
120 void
121 _PyImport_Init(void)
122 {
123     const struct filedescr *scan;
124     struct filedescr *filetab;
125     int countD = 0;
126     int countS = 0;
127
128     /* prepare _PyImport_Filetab: copy entries from
129        _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
130      */
131 #ifdef HAVE_DYNAMIC_LOADING
132     for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
133         ++countD;
134 #endif
135     for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
136         ++countS;
137     filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
138     if (filetab == NULL)
139         Py_FatalError("Can't initialize import file table.");
140 #ifdef HAVE_DYNAMIC_LOADING
141     memcpy(filetab, _PyImport_DynLoadFiletab,
142            countD * sizeof(struct filedescr));
143 #endif
144     memcpy(filetab + countD, _PyImport_StandardFiletab,
145            countS * sizeof(struct filedescr));
146     filetab[countD + countS].suffix = NULL;
147
148     _PyImport_Filetab = filetab;
149
150     if (Py_OptimizeFlag) {
151         /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
152         for (; filetab->suffix != NULL; filetab++) {
153 #ifndef RISCOS
154             if (strcmp(filetab->suffix, ".pyc") == 0)
155                 filetab->suffix = ".pyo";
156 #else
157             if (strcmp(filetab->suffix, "/pyc") == 0)
158                 filetab->suffix = "/pyo";
159 #endif
160         }
161     }
162
163     if (Py_UnicodeFlag) {
164         /* Fix the pyc_magic so that byte compiled code created
165            using the all-Unicode method doesn't interfere with
166            code created in normal operation mode. */
167         pyc_magic = MAGIC + 1;
168     }
169 }
170
171 void
172 _PyImportHooks_Init(void)
173 {
174     PyObject *v, *path_hooks = NULL, *zimpimport;
175     int err = 0;
176
177     /* adding sys.path_hooks and sys.path_importer_cache, setting up
178        zipimport */
179     if (PyType_Ready(&PyNullImporter_Type) < 0)
180         goto error;
181
182     if (Py_VerboseFlag)
183         PySys_WriteStderr("# installing zipimport hook\n");
184
185     v = PyList_New(0);
186     if (v == NULL)
187         goto error;
188     err = PySys_SetObject("meta_path", v);
189     Py_DECREF(v);
190     if (err)
191         goto error;
192     v = PyDict_New();
193     if (v == NULL)
194         goto error;
195     err = PySys_SetObject("path_importer_cache", v);
196     Py_DECREF(v);
197     if (err)
198         goto error;
199     path_hooks = PyList_New(0);
200     if (path_hooks == NULL)
201         goto error;
202     err = PySys_SetObject("path_hooks", path_hooks);
203     if (err) {
204   error:
205         PyErr_Print();
206         Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
207                       "path_importer_cache, or NullImporter failed"
208                       );
209     }
210
211     zimpimport = PyImport_ImportModule("zipimport");
212     if (zimpimport == NULL) {
213         PyErr_Clear(); /* No zip import module -- okay */
214         if (Py_VerboseFlag)
215             PySys_WriteStderr("# can't import zipimport\n");
216     }
217     else {
218         PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
219                                                        "zipimporter");
220         Py_DECREF(zimpimport);
221         if (zipimporter == NULL) {
222             PyErr_Clear(); /* No zipimporter object -- okay */
223             if (Py_VerboseFlag)
224                 PySys_WriteStderr(
225                     "# can't import zipimport.zipimporter\n");
226         }
227         else {
228             /* sys.path_hooks.append(zipimporter) */
229             err = PyList_Append(path_hooks, zipimporter);
230             Py_DECREF(zipimporter);
231             if (err)
232                 goto error;
233             if (Py_VerboseFlag)
234                 PySys_WriteStderr(
235                     "# installed zipimport hook\n");
236         }
237     }
238     Py_DECREF(path_hooks);
239 }
240
241 void
242 _PyImport_Fini(void)
243 {
244     Py_XDECREF(extensions);
245     extensions = NULL;
246     PyMem_DEL(_PyImport_Filetab);
247     _PyImport_Filetab = NULL;
248 }
249
250
251 /* Locking primitives to prevent parallel imports of the same module
252    in different threads to return with a partially loaded module.
253    These calls are serialized by the global interpreter lock. */
254
255 #ifdef WITH_THREAD
256
257 #include "pythread.h"
258
259 static PyThread_type_lock import_lock = 0;
260 static long import_lock_thread = -1;
261 static int import_lock_level = 0;
262
263 void
264 _PyImport_AcquireLock(void)
265 {
266     long me = PyThread_get_thread_ident();
267     if (me == -1)
268         return; /* Too bad */
269     if (import_lock == NULL) {
270         import_lock = PyThread_allocate_lock();
271         if (import_lock == NULL)
272             return;  /* Nothing much we can do. */
273     }
274     if (import_lock_thread == me) {
275         import_lock_level++;
276         return;
277     }
278     if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
279     {
280         PyThreadState *tstate = PyEval_SaveThread();
281         PyThread_acquire_lock(import_lock, 1);
282         PyEval_RestoreThread(tstate);
283     }
284     import_lock_thread = me;
285     import_lock_level = 1;
286 }
287
288 int
289 _PyImport_ReleaseLock(void)
290 {
291     long me = PyThread_get_thread_ident();
292     if (me == -1 || import_lock == NULL)
293         return 0; /* Too bad */
294     if (import_lock_thread != me)
295         return -1;
296     import_lock_level--;
297     if (import_lock_level == 0) {
298         import_lock_thread = -1;
299         PyThread_release_lock(import_lock);
300     }
301     return 1;
302 }
303
304 /* This function is called from PyOS_AfterFork to ensure that newly
305    created child processes do not share locks with the parent.
306    We now acquire the import lock around fork() calls but on some platforms
307    (Solaris 9 and earlier? see isue7242) that still left us with problems. */
308
309 void
310 _PyImport_ReInitLock(void)
311 {
312     if (import_lock != NULL)
313         import_lock = PyThread_allocate_lock();
314     import_lock_thread = -1;
315     import_lock_level = 0;
316 }
317
318 #endif
319
320 static PyObject *
321 imp_lock_held(PyObject *self, PyObject *noargs)
322 {
323 #ifdef WITH_THREAD
324     return PyBool_FromLong(import_lock_thread != -1);
325 #else
326     return PyBool_FromLong(0);
327 #endif
328 }
329
330 static PyObject *
331 imp_acquire_lock(PyObject *self, PyObject *noargs)
332 {
333 #ifdef WITH_THREAD
334     _PyImport_AcquireLock();
335 #endif
336     Py_INCREF(Py_None);
337     return Py_None;
338 }
339
340 static PyObject *
341 imp_release_lock(PyObject *self, PyObject *noargs)
342 {
343 #ifdef WITH_THREAD
344     if (_PyImport_ReleaseLock() < 0) {
345         PyErr_SetString(PyExc_RuntimeError,
346                         "not holding the import lock");
347         return NULL;
348     }
349 #endif
350     Py_INCREF(Py_None);
351     return Py_None;
352 }
353
354 static void
355 imp_modules_reloading_clear(void)
356 {
357     PyInterpreterState *interp = PyThreadState_Get()->interp;
358     if (interp->modules_reloading != NULL)
359         PyDict_Clear(interp->modules_reloading);
360 }
361
362 /* Helper for sys */
363
364 PyObject *
365 PyImport_GetModuleDict(void)
366 {
367     PyInterpreterState *interp = PyThreadState_GET()->interp;
368     if (interp->modules == NULL)
369         Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
370     return interp->modules;
371 }
372
373
374 /* List of names to clear in sys */
375 static char* sys_deletes[] = {
376     "path", "argv", "ps1", "ps2", "exitfunc",
377     "exc_type", "exc_value", "exc_traceback",
378     "last_type", "last_value", "last_traceback",
379     "path_hooks", "path_importer_cache", "meta_path",
380     /* misc stuff */
381     "flags", "float_info",
382     NULL
383 };
384
385 static char* sys_files[] = {
386     "stdin", "__stdin__",
387     "stdout", "__stdout__",
388     "stderr", "__stderr__",
389     NULL
390 };
391
392
393 /* Un-initialize things, as good as we can */
394
395 void
396 PyImport_Cleanup(void)
397 {
398     Py_ssize_t pos, ndone;
399     char *name;
400     PyObject *key, *value, *dict;
401     PyInterpreterState *interp = PyThreadState_GET()->interp;
402     PyObject *modules = interp->modules;
403
404     if (modules == NULL)
405         return; /* Already done */
406
407     /* Delete some special variables first.  These are common
408        places where user values hide and people complain when their
409        destructors fail.  Since the modules containing them are
410        deleted *last* of all, they would come too late in the normal
411        destruction order.  Sigh. */
412
413     value = PyDict_GetItemString(modules, "__builtin__");
414     if (value != NULL && PyModule_Check(value)) {
415         dict = PyModule_GetDict(value);
416         if (Py_VerboseFlag)
417             PySys_WriteStderr("# clear __builtin__._\n");
418         PyDict_SetItemString(dict, "_", Py_None);
419     }
420     value = PyDict_GetItemString(modules, "sys");
421     if (value != NULL && PyModule_Check(value)) {
422         char **p;
423         PyObject *v;
424         dict = PyModule_GetDict(value);
425         for (p = sys_deletes; *p != NULL; p++) {
426             if (Py_VerboseFlag)
427                 PySys_WriteStderr("# clear sys.%s\n", *p);
428             PyDict_SetItemString(dict, *p, Py_None);
429         }
430         for (p = sys_files; *p != NULL; p+=2) {
431             if (Py_VerboseFlag)
432                 PySys_WriteStderr("# restore sys.%s\n", *p);
433             v = PyDict_GetItemString(dict, *(p+1));
434             if (v == NULL)
435                 v = Py_None;
436             PyDict_SetItemString(dict, *p, v);
437         }
438     }
439
440     /* First, delete __main__ */
441     value = PyDict_GetItemString(modules, "__main__");
442     if (value != NULL && PyModule_Check(value)) {
443         if (Py_VerboseFlag)
444             PySys_WriteStderr("# cleanup __main__\n");
445         _PyModule_Clear(value);
446         PyDict_SetItemString(modules, "__main__", Py_None);
447     }
448
449     /* The special treatment of __builtin__ here is because even
450        when it's not referenced as a module, its dictionary is
451        referenced by almost every module's __builtins__.  Since
452        deleting a module clears its dictionary (even if there are
453        references left to it), we need to delete the __builtin__
454        module last.  Likewise, we don't delete sys until the very
455        end because it is implicitly referenced (e.g. by print).
456
457        Also note that we 'delete' modules by replacing their entry
458        in the modules dict with None, rather than really deleting
459        them; this avoids a rehash of the modules dictionary and
460        also marks them as "non existent" so they won't be
461        re-imported. */
462
463     /* Next, repeatedly delete modules with a reference count of
464        one (skipping __builtin__ and sys) and delete them */
465     do {
466         ndone = 0;
467         pos = 0;
468         while (PyDict_Next(modules, &pos, &key, &value)) {
469             if (value->ob_refcnt != 1)
470                 continue;
471             if (PyString_Check(key) && PyModule_Check(value)) {
472                 name = PyString_AS_STRING(key);
473                 if (strcmp(name, "__builtin__") == 0)
474                     continue;
475                 if (strcmp(name, "sys") == 0)
476                     continue;
477                 if (Py_VerboseFlag)
478                     PySys_WriteStderr(
479                         "# cleanup[1] %s\n", name);
480                 _PyModule_Clear(value);
481                 PyDict_SetItem(modules, key, Py_None);
482                 ndone++;
483             }
484         }
485     } while (ndone > 0);
486
487     /* Next, delete all modules (still skipping __builtin__ and sys) */
488     pos = 0;
489     while (PyDict_Next(modules, &pos, &key, &value)) {
490         if (PyString_Check(key) && PyModule_Check(value)) {
491             name = PyString_AS_STRING(key);
492             if (strcmp(name, "__builtin__") == 0)
493                 continue;
494             if (strcmp(name, "sys") == 0)
495                 continue;
496             if (Py_VerboseFlag)
497                 PySys_WriteStderr("# cleanup[2] %s\n", name);
498             _PyModule_Clear(value);
499             PyDict_SetItem(modules, key, Py_None);
500         }
501     }
502
503     /* Next, delete sys and __builtin__ (in that order) */
504     value = PyDict_GetItemString(modules, "sys");
505     if (value != NULL && PyModule_Check(value)) {
506         if (Py_VerboseFlag)
507             PySys_WriteStderr("# cleanup sys\n");
508         _PyModule_Clear(value);
509         PyDict_SetItemString(modules, "sys", Py_None);
510     }
511     value = PyDict_GetItemString(modules, "__builtin__");
512     if (value != NULL && PyModule_Check(value)) {
513         if (Py_VerboseFlag)
514             PySys_WriteStderr("# cleanup __builtin__\n");
515         _PyModule_Clear(value);
516         PyDict_SetItemString(modules, "__builtin__", Py_None);
517     }
518
519     /* Finally, clear and delete the modules directory */
520     PyDict_Clear(modules);
521     interp->modules = NULL;
522     Py_DECREF(modules);
523     Py_CLEAR(interp->modules_reloading);
524 }
525
526
527 /* Helper for pythonrun.c -- return magic number */
528
529 long
530 PyImport_GetMagicNumber(void)
531 {
532     return pyc_magic;
533 }
534
535
536 /* Magic for extension modules (built-in as well as dynamically
537    loaded).  To prevent initializing an extension module more than
538    once, we keep a static dictionary 'extensions' keyed by module name
539    (for built-in modules) or by filename (for dynamically loaded
540    modules), containing these modules.  A copy of the module's
541    dictionary is stored by calling _PyImport_FixupExtension()
542    immediately after the module initialization function succeeds.  A
543    copy can be retrieved from there by calling
544    _PyImport_FindExtension(). */
545
546 PyObject *
547 _PyImport_FixupExtension(char *name, char *filename)
548 {
549     PyObject *modules, *mod, *dict, *copy;
550     if (extensions == NULL) {
551         extensions = PyDict_New();
552         if (extensions == NULL)
553             return NULL;
554     }
555     modules = PyImport_GetModuleDict();
556     mod = PyDict_GetItemString(modules, name);
557     if (mod == NULL || !PyModule_Check(mod)) {
558         PyErr_Format(PyExc_SystemError,
559           "_PyImport_FixupExtension: module %.200s not loaded", name);
560         return NULL;
561     }
562     dict = PyModule_GetDict(mod);
563     if (dict == NULL)
564         return NULL;
565     copy = PyDict_Copy(dict);
566     if (copy == NULL)
567         return NULL;
568     PyDict_SetItemString(extensions, filename, copy);
569     Py_DECREF(copy);
570     return copy;
571 }
572
573 PyObject *
574 _PyImport_FindExtension(char *name, char *filename)
575 {
576     PyObject *dict, *mod, *mdict;
577     if (extensions == NULL)
578         return NULL;
579     dict = PyDict_GetItemString(extensions, filename);
580     if (dict == NULL)
581         return NULL;
582     mod = PyImport_AddModule(name);
583     if (mod == NULL)
584         return NULL;
585     mdict = PyModule_GetDict(mod);
586     if (mdict == NULL)
587         return NULL;
588     if (PyDict_Update(mdict, dict))
589         return NULL;
590     if (Py_VerboseFlag)
591         PySys_WriteStderr("import %s # previously loaded (%s)\n",
592             name, filename);
593     return mod;
594 }
595
596
597 /* Get the module object corresponding to a module name.
598    First check the modules dictionary if there's one there,
599    if not, create a new one and insert it in the modules dictionary.
600    Because the former action is most common, THIS DOES NOT RETURN A
601    'NEW' REFERENCE! */
602
603 PyObject *
604 PyImport_AddModule(const char *name)
605 {
606     PyObject *modules = PyImport_GetModuleDict();
607     PyObject *m;
608
609     if ((m = PyDict_GetItemString(modules, name)) != NULL &&
610         PyModule_Check(m))
611         return m;
612     m = PyModule_New(name);
613     if (m == NULL)
614         return NULL;
615     if (PyDict_SetItemString(modules, name, m) != 0) {
616         Py_DECREF(m);
617         return NULL;
618     }
619     Py_DECREF(m); /* Yes, it still exists, in modules! */
620
621     return m;
622 }
623
624 /* Remove name from sys.modules, if it's there. */
625 static void
626 remove_module(const char *name)
627 {
628     PyObject *modules = PyImport_GetModuleDict();
629     if (PyDict_GetItemString(modules, name) == NULL)
630         return;
631     if (PyDict_DelItemString(modules, name) < 0)
632         Py_FatalError("import:  deleting existing key in"
633                       "sys.modules failed");
634 }
635
636 /* Execute a code object in a module and return the module object
637  * WITH INCREMENTED REFERENCE COUNT.  If an error occurs, name is
638  * removed from sys.modules, to avoid leaving damaged module objects
639  * in sys.modules.  The caller may wish to restore the original
640  * module object (if any) in this case; PyImport_ReloadModule is an
641  * example.
642  */
643 PyObject *
644 PyImport_ExecCodeModule(char *name, PyObject *co)
645 {
646     return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
647 }
648
649 PyObject *
650 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
651 {
652     PyObject *modules = PyImport_GetModuleDict();
653     PyObject *m, *d, *v;
654
655     m = PyImport_AddModule(name);
656     if (m == NULL)
657         return NULL;
658     /* If the module is being reloaded, we get the old module back
659        and re-use its dict to exec the new code. */
660     d = PyModule_GetDict(m);
661     if (PyDict_GetItemString(d, "__builtins__") == NULL) {
662         if (PyDict_SetItemString(d, "__builtins__",
663                                  PyEval_GetBuiltins()) != 0)
664             goto error;
665     }
666     /* Remember the filename as the __file__ attribute */
667     v = NULL;
668     if (pathname != NULL) {
669         v = PyString_FromString(pathname);
670         if (v == NULL)
671             PyErr_Clear();
672     }
673     if (v == NULL) {
674         v = ((PyCodeObject *)co)->co_filename;
675         Py_INCREF(v);
676     }
677     if (PyDict_SetItemString(d, "__file__", v) != 0)
678         PyErr_Clear(); /* Not important enough to report */
679     Py_DECREF(v);
680
681     v = PyEval_EvalCode((PyCodeObject *)co, d, d);
682     if (v == NULL)
683         goto error;
684     Py_DECREF(v);
685
686     if ((m = PyDict_GetItemString(modules, name)) == NULL) {
687         PyErr_Format(PyExc_ImportError,
688                      "Loaded module %.200s not found in sys.modules",
689                      name);
690         return NULL;
691     }
692
693     Py_INCREF(m);
694
695     return m;
696
697   error:
698     remove_module(name);
699     return NULL;
700 }
701
702
703 /* Given a pathname for a Python source file, fill a buffer with the
704    pathname for the corresponding compiled file.  Return the pathname
705    for the compiled file, or NULL if there's no space in the buffer.
706    Doesn't set an exception. */
707
708 static char *
709 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
710 {
711     size_t len = strlen(pathname);
712     if (len+2 > buflen)
713         return NULL;
714
715 #ifdef MS_WINDOWS
716     /* Treat .pyw as if it were .py.  The case of ".pyw" must match
717        that used in _PyImport_StandardFiletab. */
718     if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
719         --len;          /* pretend 'w' isn't there */
720 #endif
721     memcpy(buf, pathname, len);
722     buf[len] = Py_OptimizeFlag ? 'o' : 'c';
723     buf[len+1] = '\0';
724
725     return buf;
726 }
727
728
729 /* Given a pathname for a Python source file, its time of last
730    modification, and a pathname for a compiled file, check whether the
731    compiled file represents the same version of the source.  If so,
732    return a FILE pointer for the compiled file, positioned just after
733    the header; if not, return NULL.
734    Doesn't set an exception. */
735
736 static FILE *
737 check_compiled_module(char *pathname, time_t mtime, char *cpathname)
738 {
739     FILE *fp;
740     long magic;
741     long pyc_mtime;
742
743     fp = fopen(cpathname, "rb");
744     if (fp == NULL)
745         return NULL;
746     magic = PyMarshal_ReadLongFromFile(fp);
747     if (magic != pyc_magic) {
748         if (Py_VerboseFlag)
749             PySys_WriteStderr("# %s has bad magic\n", cpathname);
750         fclose(fp);
751         return NULL;
752     }
753     pyc_mtime = PyMarshal_ReadLongFromFile(fp);
754     if (pyc_mtime != mtime) {
755         if (Py_VerboseFlag)
756             PySys_WriteStderr("# %s has bad mtime\n", cpathname);
757         fclose(fp);
758         return NULL;
759     }
760     if (Py_VerboseFlag)
761         PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
762     return fp;
763 }
764
765
766 /* Read a code object from a file and check it for validity */
767
768 static PyCodeObject *
769 read_compiled_module(char *cpathname, FILE *fp)
770 {
771     PyObject *co;
772
773     co = PyMarshal_ReadLastObjectFromFile(fp);
774     if (co == NULL)
775         return NULL;
776     if (!PyCode_Check(co)) {
777         PyErr_Format(PyExc_ImportError,
778                      "Non-code object in %.200s", cpathname);
779         Py_DECREF(co);
780         return NULL;
781     }
782     return (PyCodeObject *)co;
783 }
784
785
786 /* Load a module from a compiled file, execute it, and return its
787    module object WITH INCREMENTED REFERENCE COUNT */
788
789 static PyObject *
790 load_compiled_module(char *name, char *cpathname, FILE *fp)
791 {
792     long magic;
793     PyCodeObject *co;
794     PyObject *m;
795
796     magic = PyMarshal_ReadLongFromFile(fp);
797     if (magic != pyc_magic) {
798         PyErr_Format(PyExc_ImportError,
799                      "Bad magic number in %.200s", cpathname);
800         return NULL;
801     }
802     (void) PyMarshal_ReadLongFromFile(fp);
803     co = read_compiled_module(cpathname, fp);
804     if (co == NULL)
805         return NULL;
806     if (Py_VerboseFlag)
807         PySys_WriteStderr("import %s # precompiled from %s\n",
808             name, cpathname);
809     m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
810     Py_DECREF(co);
811
812     return m;
813 }
814
815 /* Parse a source file and return the corresponding code object */
816
817 static PyCodeObject *
818 parse_source_module(const char *pathname, FILE *fp)
819 {
820     PyCodeObject *co = NULL;
821     mod_ty mod;
822     PyCompilerFlags flags;
823     PyArena *arena = PyArena_New();
824     if (arena == NULL)
825         return NULL;
826
827     flags.cf_flags = 0;
828
829     mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags,
830                                NULL, arena);
831     if (mod) {
832         co = PyAST_Compile(mod, pathname, NULL, arena);
833     }
834     PyArena_Free(arena);
835     return co;
836 }
837
838
839 /* Helper to open a bytecode file for writing in exclusive mode */
840
841 static FILE *
842 open_exclusive(char *filename, mode_t mode)
843 {
844 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
845     /* Use O_EXCL to avoid a race condition when another process tries to
846        write the same file.  When that happens, our open() call fails,
847        which is just fine (since it's only a cache).
848        XXX If the file exists and is writable but the directory is not
849        writable, the file will never be written.  Oh well.
850     */
851     int fd;
852     (void) unlink(filename);
853     fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
854 #ifdef O_BINARY
855                             |O_BINARY   /* necessary for Windows */
856 #endif
857 #ifdef __VMS
858             , mode, "ctxt=bin", "shr=nil"
859 #else
860             , mode
861 #endif
862           );
863     if (fd < 0)
864         return NULL;
865     return fdopen(fd, "wb");
866 #else
867     /* Best we can do -- on Windows this can't happen anyway */
868     return fopen(filename, "wb");
869 #endif
870 }
871
872
873 /* Write a compiled module to a file, placing the time of last
874    modification of its source into the header.
875    Errors are ignored, if a write error occurs an attempt is made to
876    remove the file. */
877
878 static void
879 write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
880 {
881     FILE *fp;
882     time_t mtime = srcstat->st_mtime;
883 #ifdef MS_WINDOWS   /* since Windows uses different permissions  */
884     mode_t mode = srcstat->st_mode & ~S_IEXEC;
885 #else
886     mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
887 #endif
888
889     fp = open_exclusive(cpathname, mode);
890     if (fp == NULL) {
891         if (Py_VerboseFlag)
892             PySys_WriteStderr(
893                 "# can't create %s\n", cpathname);
894         return;
895     }
896     PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
897     /* First write a 0 for mtime */
898     PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
899     PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
900     if (fflush(fp) != 0 || ferror(fp)) {
901         if (Py_VerboseFlag)
902             PySys_WriteStderr("# can't write %s\n", cpathname);
903         /* Don't keep partial file */
904         fclose(fp);
905         (void) unlink(cpathname);
906         return;
907     }
908     /* Now write the true mtime (as a 32-bit field) */
909     fseek(fp, 4L, 0);
910     assert(mtime <= 0xFFFFFFFF);
911     PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
912     fflush(fp);
913     fclose(fp);
914     if (Py_VerboseFlag)
915         PySys_WriteStderr("# wrote %s\n", cpathname);
916 }
917
918 static void
919 update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
920 {
921     PyObject *constants, *tmp;
922     Py_ssize_t i, n;
923
924     if (!_PyString_Eq(co->co_filename, oldname))
925         return;
926
927     tmp = co->co_filename;
928     co->co_filename = newname;
929     Py_INCREF(co->co_filename);
930     Py_DECREF(tmp);
931
932     constants = co->co_consts;
933     n = PyTuple_GET_SIZE(constants);
934     for (i = 0; i < n; i++) {
935         tmp = PyTuple_GET_ITEM(constants, i);
936         if (PyCode_Check(tmp))
937             update_code_filenames((PyCodeObject *)tmp,
938                                   oldname, newname);
939     }
940 }
941
942 static int
943 update_compiled_module(PyCodeObject *co, char *pathname)
944 {
945     PyObject *oldname, *newname;
946
947     if (strcmp(PyString_AsString(co->co_filename), pathname) == 0)
948         return 0;
949
950     newname = PyString_FromString(pathname);
951     if (newname == NULL)
952         return -1;
953
954     oldname = co->co_filename;
955     Py_INCREF(oldname);
956     update_code_filenames(co, oldname, newname);
957     Py_DECREF(oldname);
958     Py_DECREF(newname);
959     return 1;
960 }
961
962 /* Load a source module from a given file and return its module
963    object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
964    byte-compiled file, use that instead. */
965
966 static PyObject *
967 load_source_module(char *name, char *pathname, FILE *fp)
968 {
969     struct stat st;
970     FILE *fpc;
971     char buf[MAXPATHLEN+1];
972     char *cpathname;
973     PyCodeObject *co;
974     PyObject *m;
975
976     if (fstat(fileno(fp), &st) != 0) {
977         PyErr_Format(PyExc_RuntimeError,
978                      "unable to get file status from '%s'",
979                      pathname);
980         return NULL;
981     }
982     if (sizeof st.st_mtime > 4) {
983         /* Python's .pyc timestamp handling presumes that the timestamp fits
984            in 4 bytes. Since the code only does an equality comparison,
985            ordering is not important and we can safely ignore the higher bits
986            (collisions are extremely unlikely).
987          */
988         st.st_mtime &= 0xFFFFFFFF;
989     }
990     cpathname = make_compiled_pathname(pathname, buf,
991                                        (size_t)MAXPATHLEN + 1);
992     if (cpathname != NULL &&
993         (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
994         co = read_compiled_module(cpathname, fpc);
995         fclose(fpc);
996         if (co == NULL)
997             return NULL;
998         if (update_compiled_module(co, pathname) < 0)
999             return NULL;
1000         if (Py_VerboseFlag)
1001             PySys_WriteStderr("import %s # precompiled from %s\n",
1002                 name, cpathname);
1003         pathname = cpathname;
1004     }
1005     else {
1006         co = parse_source_module(pathname, fp);
1007         if (co == NULL)
1008             return NULL;
1009         if (Py_VerboseFlag)
1010             PySys_WriteStderr("import %s # from %s\n",
1011                 name, pathname);
1012         if (cpathname) {
1013             PyObject *ro = PySys_GetObject("dont_write_bytecode");
1014             if (ro == NULL || !PyObject_IsTrue(ro))
1015                 write_compiled_module(co, cpathname, &st);
1016         }
1017     }
1018     m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
1019     Py_DECREF(co);
1020
1021     return m;
1022 }
1023
1024
1025 /* Forward */
1026 static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1027 static struct filedescr *find_module(char *, char *, PyObject *,
1028                                      char *, size_t, FILE **, PyObject **);
1029 static struct _frozen *find_frozen(char *name);
1030
1031 /* Load a package and return its module object WITH INCREMENTED
1032    REFERENCE COUNT */
1033
1034 static PyObject *
1035 load_package(char *name, char *pathname)
1036 {
1037     PyObject *m, *d;
1038     PyObject *file = NULL;
1039     PyObject *path = NULL;
1040     int err;
1041     char buf[MAXPATHLEN+1];
1042     FILE *fp = NULL;
1043     struct filedescr *fdp;
1044
1045     m = PyImport_AddModule(name);
1046     if (m == NULL)
1047         return NULL;
1048     if (Py_VerboseFlag)
1049         PySys_WriteStderr("import %s # directory %s\n",
1050             name, pathname);
1051     d = PyModule_GetDict(m);
1052     file = PyString_FromString(pathname);
1053     if (file == NULL)
1054         goto error;
1055     path = Py_BuildValue("[O]", file);
1056     if (path == NULL)
1057         goto error;
1058     err = PyDict_SetItemString(d, "__file__", file);
1059     if (err == 0)
1060         err = PyDict_SetItemString(d, "__path__", path);
1061     if (err != 0)
1062         goto error;
1063     buf[0] = '\0';
1064     fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1065     if (fdp == NULL) {
1066         if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1067             PyErr_Clear();
1068             Py_INCREF(m);
1069         }
1070         else
1071             m = NULL;
1072         goto cleanup;
1073     }
1074     m = load_module(name, fp, buf, fdp->type, NULL);
1075     if (fp != NULL)
1076         fclose(fp);
1077     goto cleanup;
1078
1079   error:
1080     m = NULL;
1081   cleanup:
1082     Py_XDECREF(path);
1083     Py_XDECREF(file);
1084     return m;
1085 }
1086
1087
1088 /* Helper to test for built-in module */
1089
1090 static int
1091 is_builtin(char *name)
1092 {
1093     int i;
1094     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1095         if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1096             if (PyImport_Inittab[i].initfunc == NULL)
1097                 return -1;
1098             else
1099                 return 1;
1100         }
1101     }
1102     return 0;
1103 }
1104
1105
1106 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1107    possibly by fetching it from the path_importer_cache dict. If it
1108    wasn't yet cached, traverse path_hooks until a hook is found
1109    that can handle the path item. Return None if no hook could;
1110    this tells our caller it should fall back to the builtin
1111    import mechanism. Cache the result in path_importer_cache.
1112    Returns a borrowed reference. */
1113
1114 static PyObject *
1115 get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1116                   PyObject *p)
1117 {
1118     PyObject *importer;
1119     Py_ssize_t j, nhooks;
1120
1121     /* These conditions are the caller's responsibility: */
1122     assert(PyList_Check(path_hooks));
1123     assert(PyDict_Check(path_importer_cache));
1124
1125     nhooks = PyList_Size(path_hooks);
1126     if (nhooks < 0)
1127         return NULL; /* Shouldn't happen */
1128
1129     importer = PyDict_GetItem(path_importer_cache, p);
1130     if (importer != NULL)
1131         return importer;
1132
1133     /* set path_importer_cache[p] to None to avoid recursion */
1134     if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1135         return NULL;
1136
1137     for (j = 0; j < nhooks; j++) {
1138         PyObject *hook = PyList_GetItem(path_hooks, j);
1139         if (hook == NULL)
1140             return NULL;
1141         importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1142         if (importer != NULL)
1143             break;
1144
1145         if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1146             return NULL;
1147         }
1148         PyErr_Clear();
1149     }
1150     if (importer == NULL) {
1151         importer = PyObject_CallFunctionObjArgs(
1152             (PyObject *)&PyNullImporter_Type, p, NULL
1153         );
1154         if (importer == NULL) {
1155             if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1156                 PyErr_Clear();
1157                 return Py_None;
1158             }
1159         }
1160     }
1161     if (importer != NULL) {
1162         int err = PyDict_SetItem(path_importer_cache, p, importer);
1163         Py_DECREF(importer);
1164         if (err != 0)
1165             return NULL;
1166     }
1167     return importer;
1168 }
1169
1170 PyAPI_FUNC(PyObject *)
1171 PyImport_GetImporter(PyObject *path) {
1172     PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1173
1174     if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1175         if ((path_hooks = PySys_GetObject("path_hooks"))) {
1176             importer = get_path_importer(path_importer_cache,
1177                                          path_hooks, path);
1178         }
1179     }
1180     Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1181     return importer;
1182 }
1183
1184 /* Search the path (default sys.path) for a module.  Return the
1185    corresponding filedescr struct, and (via return arguments) the
1186    pathname and an open file.  Return NULL if the module is not found. */
1187
1188 #ifdef MS_COREDLL
1189 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
1190                                         char *, Py_ssize_t);
1191 #endif
1192
1193 static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
1194 static int find_init_module(char *); /* Forward */
1195 static struct filedescr importhookdescr = {"", "", IMP_HOOK};
1196
1197 static struct filedescr *
1198 find_module(char *fullname, char *subname, PyObject *path, char *buf,
1199             size_t buflen, FILE **p_fp, PyObject **p_loader)
1200 {
1201     Py_ssize_t i, npath;
1202     size_t len, namelen;
1203     struct filedescr *fdp = NULL;
1204     char *filemode;
1205     FILE *fp = NULL;
1206     PyObject *path_hooks, *path_importer_cache;
1207 #ifndef RISCOS
1208     struct stat statbuf;
1209 #endif
1210     static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1211     static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1212     static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1213     char name[MAXPATHLEN+1];
1214 #if defined(PYOS_OS2)
1215     size_t saved_len;
1216     size_t saved_namelen;
1217     char *saved_buf = NULL;
1218 #endif
1219     if (p_loader != NULL)
1220         *p_loader = NULL;
1221
1222     if (strlen(subname) > MAXPATHLEN) {
1223         PyErr_SetString(PyExc_OverflowError,
1224                         "module name is too long");
1225         return NULL;
1226     }
1227     strcpy(name, subname);
1228
1229     /* sys.meta_path import hook */
1230     if (p_loader != NULL) {
1231         PyObject *meta_path;
1232
1233         meta_path = PySys_GetObject("meta_path");
1234         if (meta_path == NULL || !PyList_Check(meta_path)) {
1235             PyErr_SetString(PyExc_RuntimeError,
1236                             "sys.meta_path must be a list of "
1237                             "import hooks");
1238             return NULL;
1239         }
1240         Py_INCREF(meta_path);  /* zap guard */
1241         npath = PyList_Size(meta_path);
1242         for (i = 0; i < npath; i++) {
1243             PyObject *loader;
1244             PyObject *hook = PyList_GetItem(meta_path, i);
1245             loader = PyObject_CallMethod(hook, "find_module",
1246                                          "sO", fullname,
1247                                          path != NULL ?
1248                                          path : Py_None);
1249             if (loader == NULL) {
1250                 Py_DECREF(meta_path);
1251                 return NULL;  /* true error */
1252             }
1253             if (loader != Py_None) {
1254                 /* a loader was found */
1255                 *p_loader = loader;
1256                 Py_DECREF(meta_path);
1257                 return &importhookdescr;
1258             }
1259             Py_DECREF(loader);
1260         }
1261         Py_DECREF(meta_path);
1262     }
1263
1264     if (path != NULL && PyString_Check(path)) {
1265         /* The only type of submodule allowed inside a "frozen"
1266            package are other frozen modules or packages. */
1267         if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1268             PyErr_SetString(PyExc_ImportError,
1269                             "full frozen module name too long");
1270             return NULL;
1271         }
1272         strcpy(buf, PyString_AsString(path));
1273         strcat(buf, ".");
1274         strcat(buf, name);
1275         strcpy(name, buf);
1276         if (find_frozen(name) != NULL) {
1277             strcpy(buf, name);
1278             return &fd_frozen;
1279         }
1280         PyErr_Format(PyExc_ImportError,
1281                      "No frozen submodule named %.200s", name);
1282         return NULL;
1283     }
1284     if (path == NULL) {
1285         if (is_builtin(name)) {
1286             strcpy(buf, name);
1287             return &fd_builtin;
1288         }
1289         if ((find_frozen(name)) != NULL) {
1290             strcpy(buf, name);
1291             return &fd_frozen;
1292         }
1293
1294 #ifdef MS_COREDLL
1295         fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1296         if (fp != NULL) {
1297             *p_fp = fp;
1298             return fdp;
1299         }
1300 #endif
1301         path = PySys_GetObject("path");
1302     }
1303     if (path == NULL || !PyList_Check(path)) {
1304         PyErr_SetString(PyExc_RuntimeError,
1305                         "sys.path must be a list of directory names");
1306         return NULL;
1307     }
1308
1309     path_hooks = PySys_GetObject("path_hooks");
1310     if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1311         PyErr_SetString(PyExc_RuntimeError,
1312                         "sys.path_hooks must be a list of "
1313                         "import hooks");
1314         return NULL;
1315     }
1316     path_importer_cache = PySys_GetObject("path_importer_cache");
1317     if (path_importer_cache == NULL ||
1318         !PyDict_Check(path_importer_cache)) {
1319         PyErr_SetString(PyExc_RuntimeError,
1320                         "sys.path_importer_cache must be a dict");
1321         return NULL;
1322     }
1323
1324     npath = PyList_Size(path);
1325     namelen = strlen(name);
1326     for (i = 0; i < npath; i++) {
1327         PyObject *copy = NULL;
1328         PyObject *v = PyList_GetItem(path, i);
1329         if (!v)
1330             return NULL;
1331 #ifdef Py_USING_UNICODE
1332         if (PyUnicode_Check(v)) {
1333             copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1334                 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1335             if (copy == NULL)
1336                 return NULL;
1337             v = copy;
1338         }
1339         else
1340 #endif
1341         if (!PyString_Check(v))
1342             continue;
1343         len = PyString_GET_SIZE(v);
1344         if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1345             Py_XDECREF(copy);
1346             continue; /* Too long */
1347         }
1348         strcpy(buf, PyString_AS_STRING(v));
1349         if (strlen(buf) != len) {
1350             Py_XDECREF(copy);
1351             continue; /* v contains '\0' */
1352         }
1353
1354         /* sys.path_hooks import hook */
1355         if (p_loader != NULL) {
1356             PyObject *importer;
1357
1358             importer = get_path_importer(path_importer_cache,
1359                                          path_hooks, v);
1360             if (importer == NULL) {
1361                 Py_XDECREF(copy);
1362                 return NULL;
1363             }
1364             /* Note: importer is a borrowed reference */
1365             if (importer != Py_None) {
1366                 PyObject *loader;
1367                 loader = PyObject_CallMethod(importer,
1368                                              "find_module",
1369                                              "s", fullname);
1370                 Py_XDECREF(copy);
1371                 if (loader == NULL)
1372                     return NULL;  /* error */
1373                 if (loader != Py_None) {
1374                     /* a loader was found */
1375                     *p_loader = loader;
1376                     return &importhookdescr;
1377                 }
1378                 Py_DECREF(loader);
1379                 continue;
1380             }
1381         }
1382         /* no hook was found, use builtin import */
1383
1384         if (len > 0 && buf[len-1] != SEP
1385 #ifdef ALTSEP
1386             && buf[len-1] != ALTSEP
1387 #endif
1388             )
1389             buf[len++] = SEP;
1390         strcpy(buf+len, name);
1391         len += namelen;
1392
1393         /* Check for package import (buf holds a directory name,
1394            and there's an __init__ module in that directory */
1395 #ifdef HAVE_STAT
1396         if (stat(buf, &statbuf) == 0 &&         /* it exists */
1397             S_ISDIR(statbuf.st_mode) &&         /* it's a directory */
1398             case_ok(buf, len, namelen, name)) { /* case matches */
1399             if (find_init_module(buf)) { /* and has __init__.py */
1400                 Py_XDECREF(copy);
1401                 return &fd_package;
1402             }
1403             else {
1404                 char warnstr[MAXPATHLEN+80];
1405                 sprintf(warnstr, "Not importing directory "
1406                     "'%.*s': missing __init__.py",
1407                     MAXPATHLEN, buf);
1408                 if (PyErr_Warn(PyExc_ImportWarning,
1409                                warnstr)) {
1410                     Py_XDECREF(copy);
1411                     return NULL;
1412                 }
1413             }
1414         }
1415 #else
1416         /* XXX How are you going to test for directories? */
1417 #ifdef RISCOS
1418         if (isdir(buf) &&
1419             case_ok(buf, len, namelen, name)) {
1420             if (find_init_module(buf)) {
1421                 Py_XDECREF(copy);
1422                 return &fd_package;
1423             }
1424             else {
1425                 char warnstr[MAXPATHLEN+80];
1426                 sprintf(warnstr, "Not importing directory "
1427                     "'%.*s': missing __init__.py",
1428                     MAXPATHLEN, buf);
1429                 if (PyErr_Warn(PyExc_ImportWarning,
1430                                warnstr)) {
1431                     Py_XDECREF(copy);
1432                     return NULL;
1433                 }
1434         }
1435 #endif
1436 #endif
1437 #if defined(PYOS_OS2)
1438         /* take a snapshot of the module spec for restoration
1439          * after the 8 character DLL hackery
1440          */
1441         saved_buf = strdup(buf);
1442         saved_len = len;
1443         saved_namelen = namelen;
1444 #endif /* PYOS_OS2 */
1445         for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1446 #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
1447             /* OS/2 limits DLLs to 8 character names (w/o
1448                extension)
1449              * so if the name is longer than that and its a
1450              * dynamically loaded module we're going to try,
1451              * truncate the name before trying
1452              */
1453             if (strlen(subname) > 8) {
1454                 /* is this an attempt to load a C extension? */
1455                 const struct filedescr *scan;
1456                 scan = _PyImport_DynLoadFiletab;
1457                 while (scan->suffix != NULL) {
1458                     if (!strcmp(scan->suffix, fdp->suffix))
1459                         break;
1460                     else
1461                         scan++;
1462                 }
1463                 if (scan->suffix != NULL) {
1464                     /* yes, so truncate the name */
1465                     namelen = 8;
1466                     len -= strlen(subname) - namelen;
1467                     buf[len] = '\0';
1468                 }
1469             }
1470 #endif /* PYOS_OS2 */
1471             strcpy(buf+len, fdp->suffix);
1472             if (Py_VerboseFlag > 1)
1473                 PySys_WriteStderr("# trying %s\n", buf);
1474             filemode = fdp->mode;
1475             if (filemode[0] == 'U')
1476                 filemode = "r" PY_STDIOTEXTMODE;
1477             fp = fopen(buf, filemode);
1478             if (fp != NULL) {
1479                 if (case_ok(buf, len, namelen, name))
1480                     break;
1481                 else {                   /* continue search */
1482                     fclose(fp);
1483                     fp = NULL;
1484                 }
1485             }
1486 #if defined(PYOS_OS2)
1487             /* restore the saved snapshot */
1488             strcpy(buf, saved_buf);
1489             len = saved_len;
1490             namelen = saved_namelen;
1491 #endif
1492         }
1493 #if defined(PYOS_OS2)
1494         /* don't need/want the module name snapshot anymore */
1495         if (saved_buf)
1496         {
1497             free(saved_buf);
1498             saved_buf = NULL;
1499         }
1500 #endif
1501         Py_XDECREF(copy);
1502         if (fp != NULL)
1503             break;
1504     }
1505     if (fp == NULL) {
1506         PyErr_Format(PyExc_ImportError,
1507                      "No module named %.200s", name);
1508         return NULL;
1509     }
1510     *p_fp = fp;
1511     return fdp;
1512 }
1513
1514 /* Helpers for main.c
1515  *  Find the source file corresponding to a named module
1516  */
1517 struct filedescr *
1518 _PyImport_FindModule(const char *name, PyObject *path, char *buf,
1519             size_t buflen, FILE **p_fp, PyObject **p_loader)
1520 {
1521     return find_module((char *) name, (char *) name, path,
1522                        buf, buflen, p_fp, p_loader);
1523 }
1524
1525 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1526 {
1527     return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1528 }
1529
1530 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1531  * The arguments here are tricky, best shown by example:
1532  *    /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1533  *    ^                      ^                   ^    ^
1534  *    |--------------------- buf ---------------------|
1535  *    |------------------- len ------------------|
1536  *                           |------ name -------|
1537  *                           |----- namelen -----|
1538  * buf is the full path, but len only counts up to (& exclusive of) the
1539  * extension.  name is the module name, also exclusive of extension.
1540  *
1541  * We've already done a successful stat() or fopen() on buf, so know that
1542  * there's some match, possibly case-insensitive.
1543  *
1544  * case_ok() is to return 1 if there's a case-sensitive match for
1545  * name, else 0.  case_ok() is also to return 1 if envar PYTHONCASEOK
1546  * exists.
1547  *
1548  * case_ok() is used to implement case-sensitive import semantics even
1549  * on platforms with case-insensitive filesystems.  It's trivial to implement
1550  * for case-sensitive filesystems.  It's pretty much a cross-platform
1551  * nightmare for systems with case-insensitive filesystems.
1552  */
1553
1554 /* First we may need a pile of platform-specific header files; the sequence
1555  * of #if's here should match the sequence in the body of case_ok().
1556  */
1557 #if defined(MS_WINDOWS)
1558 #include <windows.h>
1559
1560 #elif defined(DJGPP)
1561 #include <dir.h>
1562
1563 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1564 #include <sys/types.h>
1565 #include <dirent.h>
1566
1567 #elif defined(PYOS_OS2)
1568 #define INCL_DOS
1569 #define INCL_DOSERRORS
1570 #define INCL_NOPMAPI
1571 #include <os2.h>
1572
1573 #elif defined(RISCOS)
1574 #include "oslib/osfscontrol.h"
1575 #endif
1576
1577 static int
1578 case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
1579 {
1580 /* Pick a platform-specific implementation; the sequence of #if's here should
1581  * match the sequence just above.
1582  */
1583
1584 /* MS_WINDOWS */
1585 #if defined(MS_WINDOWS)
1586     WIN32_FIND_DATA data;
1587     HANDLE h;
1588
1589     if (Py_GETENV("PYTHONCASEOK") != NULL)
1590         return 1;
1591
1592     h = FindFirstFile(buf, &data);
1593     if (h == INVALID_HANDLE_VALUE) {
1594         PyErr_Format(PyExc_NameError,
1595           "Can't find file for module %.100s\n(filename %.300s)",
1596           name, buf);
1597         return 0;
1598     }
1599     FindClose(h);
1600     return strncmp(data.cFileName, name, namelen) == 0;
1601
1602 /* DJGPP */
1603 #elif defined(DJGPP)
1604     struct ffblk ffblk;
1605     int done;
1606
1607     if (Py_GETENV("PYTHONCASEOK") != NULL)
1608         return 1;
1609
1610     done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1611     if (done) {
1612         PyErr_Format(PyExc_NameError,
1613           "Can't find file for module %.100s\n(filename %.300s)",
1614           name, buf);
1615         return 0;
1616     }
1617     return strncmp(ffblk.ff_name, name, namelen) == 0;
1618
1619 /* new-fangled macintosh (macosx) or Cygwin */
1620 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1621     DIR *dirp;
1622     struct dirent *dp;
1623     char dirname[MAXPATHLEN + 1];
1624     const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1625
1626     if (Py_GETENV("PYTHONCASEOK") != NULL)
1627         return 1;
1628
1629     /* Copy the dir component into dirname; substitute "." if empty */
1630     if (dirlen <= 0) {
1631         dirname[0] = '.';
1632         dirname[1] = '\0';
1633     }
1634     else {
1635         assert(dirlen <= MAXPATHLEN);
1636         memcpy(dirname, buf, dirlen);
1637         dirname[dirlen] = '\0';
1638     }
1639     /* Open the directory and search the entries for an exact match. */
1640     dirp = opendir(dirname);
1641     if (dirp) {
1642         char *nameWithExt = buf + len - namelen;
1643         while ((dp = readdir(dirp)) != NULL) {
1644             const int thislen =
1645 #ifdef _DIRENT_HAVE_D_NAMELEN
1646                                     dp->d_namlen;
1647 #else
1648                                     strlen(dp->d_name);
1649 #endif
1650             if (thislen >= namelen &&
1651                 strcmp(dp->d_name, nameWithExt) == 0) {
1652                 (void)closedir(dirp);
1653                 return 1; /* Found */
1654             }
1655         }
1656         (void)closedir(dirp);
1657     }
1658     return 0 ; /* Not found */
1659
1660 /* RISC OS */
1661 #elif defined(RISCOS)
1662     char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1663     char buf2[MAXPATHLEN+2];
1664     char *nameWithExt = buf+len-namelen;
1665     int canonlen;
1666     os_error *e;
1667
1668     if (Py_GETENV("PYTHONCASEOK") != NULL)
1669         return 1;
1670
1671     /* workaround:
1672        append wildcard, otherwise case of filename wouldn't be touched */
1673     strcpy(buf2, buf);
1674     strcat(buf2, "*");
1675
1676     e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1677     canonlen = MAXPATHLEN+1-canonlen;
1678     if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1679         return 0;
1680     if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1681         return 1; /* match */
1682
1683     return 0;
1684
1685 /* OS/2 */
1686 #elif defined(PYOS_OS2)
1687     HDIR hdir = 1;
1688     ULONG srchcnt = 1;
1689     FILEFINDBUF3 ffbuf;
1690     APIRET rc;
1691
1692     if (Py_GETENV("PYTHONCASEOK") != NULL)
1693         return 1;
1694
1695     rc = DosFindFirst(buf,
1696                       &hdir,
1697                       FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1698                       &ffbuf, sizeof(ffbuf),
1699                       &srchcnt,
1700                       FIL_STANDARD);
1701     if (rc != NO_ERROR)
1702         return 0;
1703     return strncmp(ffbuf.achName, name, namelen) == 0;
1704
1705 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1706 #else
1707     return 1;
1708
1709 #endif
1710 }
1711
1712
1713 #ifdef HAVE_STAT
1714 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1715 static int
1716 find_init_module(char *buf)
1717 {
1718     const size_t save_len = strlen(buf);
1719     size_t i = save_len;
1720     char *pname;  /* pointer to start of __init__ */
1721     struct stat statbuf;
1722
1723 /*      For calling case_ok(buf, len, namelen, name):
1724  *      /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1725  *      ^                      ^                   ^    ^
1726  *      |--------------------- buf ---------------------|
1727  *      |------------------- len ------------------|
1728  *                             |------ name -------|
1729  *                             |----- namelen -----|
1730  */
1731     if (save_len + 13 >= MAXPATHLEN)
1732         return 0;
1733     buf[i++] = SEP;
1734     pname = buf + i;
1735     strcpy(pname, "__init__.py");
1736     if (stat(buf, &statbuf) == 0) {
1737         if (case_ok(buf,
1738                     save_len + 9,               /* len("/__init__") */
1739                 8,                              /* len("__init__") */
1740                 pname)) {
1741             buf[save_len] = '\0';
1742             return 1;
1743         }
1744     }
1745     i += strlen(pname);
1746     strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1747     if (stat(buf, &statbuf) == 0) {
1748         if (case_ok(buf,
1749                     save_len + 9,               /* len("/__init__") */
1750                 8,                              /* len("__init__") */
1751                 pname)) {
1752             buf[save_len] = '\0';
1753             return 1;
1754         }
1755     }
1756     buf[save_len] = '\0';
1757     return 0;
1758 }
1759
1760 #else
1761
1762 #ifdef RISCOS
1763 static int
1764 find_init_module(buf)
1765     char *buf;
1766 {
1767     int save_len = strlen(buf);
1768     int i = save_len;
1769
1770     if (save_len + 13 >= MAXPATHLEN)
1771         return 0;
1772     buf[i++] = SEP;
1773     strcpy(buf+i, "__init__/py");
1774     if (isfile(buf)) {
1775         buf[save_len] = '\0';
1776         return 1;
1777     }
1778
1779     if (Py_OptimizeFlag)
1780         strcpy(buf+i, "o");
1781     else
1782         strcpy(buf+i, "c");
1783     if (isfile(buf)) {
1784         buf[save_len] = '\0';
1785         return 1;
1786     }
1787     buf[save_len] = '\0';
1788     return 0;
1789 }
1790 #endif /*RISCOS*/
1791
1792 #endif /* HAVE_STAT */
1793
1794
1795 static int init_builtin(char *); /* Forward */
1796
1797 /* Load an external module using the default search path and return
1798    its module object WITH INCREMENTED REFERENCE COUNT */
1799
1800 static PyObject *
1801 load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
1802 {
1803     PyObject *modules;
1804     PyObject *m;
1805     int err;
1806
1807     /* First check that there's an open file (if we need one)  */
1808     switch (type) {
1809     case PY_SOURCE:
1810     case PY_COMPILED:
1811         if (fp == NULL) {
1812             PyErr_Format(PyExc_ValueError,
1813                "file object required for import (type code %d)",
1814                          type);
1815             return NULL;
1816         }
1817     }
1818
1819     switch (type) {
1820
1821     case PY_SOURCE:
1822         m = load_source_module(name, pathname, fp);
1823         break;
1824
1825     case PY_COMPILED:
1826         m = load_compiled_module(name, pathname, fp);
1827         break;
1828
1829 #ifdef HAVE_DYNAMIC_LOADING
1830     case C_EXTENSION:
1831         m = _PyImport_LoadDynamicModule(name, pathname, fp);
1832         break;
1833 #endif
1834
1835     case PKG_DIRECTORY:
1836         m = load_package(name, pathname);
1837         break;
1838
1839     case C_BUILTIN:
1840     case PY_FROZEN:
1841         if (pathname != NULL && pathname[0] != '\0')
1842             name = pathname;
1843         if (type == C_BUILTIN)
1844             err = init_builtin(name);
1845         else
1846             err = PyImport_ImportFrozenModule(name);
1847         if (err < 0)
1848             return NULL;
1849         if (err == 0) {
1850             PyErr_Format(PyExc_ImportError,
1851                          "Purported %s module %.200s not found",
1852                          type == C_BUILTIN ?
1853                                     "builtin" : "frozen",
1854                          name);
1855             return NULL;
1856         }
1857         modules = PyImport_GetModuleDict();
1858         m = PyDict_GetItemString(modules, name);
1859         if (m == NULL) {
1860             PyErr_Format(
1861                 PyExc_ImportError,
1862                 "%s module %.200s not properly initialized",
1863                 type == C_BUILTIN ?
1864                     "builtin" : "frozen",
1865                 name);
1866             return NULL;
1867         }
1868         Py_INCREF(m);
1869         break;
1870
1871     case IMP_HOOK: {
1872         if (loader == NULL) {
1873             PyErr_SetString(PyExc_ImportError,
1874                             "import hook without loader");
1875             return NULL;
1876         }
1877         m = PyObject_CallMethod(loader, "load_module", "s", name);
1878         break;
1879     }
1880
1881     default:
1882         PyErr_Format(PyExc_ImportError,
1883                      "Don't know how to import %.200s (type code %d)",
1884                       name, type);
1885         m = NULL;
1886
1887     }
1888
1889     return m;
1890 }
1891
1892
1893 /* Initialize a built-in module.
1894    Return 1 for success, 0 if the module is not found, and -1 with
1895    an exception set if the initialization failed. */
1896
1897 static int
1898 init_builtin(char *name)
1899 {
1900     struct _inittab *p;
1901
1902     if (_PyImport_FindExtension(name, name) != NULL)
1903         return 1;
1904
1905     for (p = PyImport_Inittab; p->name != NULL; p++) {
1906         if (strcmp(name, p->name) == 0) {
1907             if (p->initfunc == NULL) {
1908                 PyErr_Format(PyExc_ImportError,
1909                     "Cannot re-init internal module %.200s",
1910                     name);
1911                 return -1;
1912             }
1913             if (Py_VerboseFlag)
1914                 PySys_WriteStderr("import %s # builtin\n", name);
1915             (*p->initfunc)();
1916             if (PyErr_Occurred())
1917                 return -1;
1918             if (_PyImport_FixupExtension(name, name) == NULL)
1919                 return -1;
1920             return 1;
1921         }
1922     }
1923     return 0;
1924 }
1925
1926
1927 /* Frozen modules */
1928
1929 static struct _frozen *
1930 find_frozen(char *name)
1931 {
1932     struct _frozen *p;
1933
1934     for (p = PyImport_FrozenModules; ; p++) {
1935         if (p->name == NULL)
1936             return NULL;
1937         if (strcmp(p->name, name) == 0)
1938             break;
1939     }
1940     return p;
1941 }
1942
1943 static PyObject *
1944 get_frozen_object(char *name)
1945 {
1946     struct _frozen *p = find_frozen(name);
1947     int size;
1948
1949     if (p == NULL) {
1950         PyErr_Format(PyExc_ImportError,
1951                      "No such frozen object named %.200s",
1952                      name);
1953         return NULL;
1954     }
1955     if (p->code == NULL) {
1956         PyErr_Format(PyExc_ImportError,
1957                      "Excluded frozen object named %.200s",
1958                      name);
1959         return NULL;
1960     }
1961     size = p->size;
1962     if (size < 0)
1963         size = -size;
1964     return PyMarshal_ReadObjectFromString((char *)p->code, size);
1965 }
1966
1967 /* Initialize a frozen module.
1968    Return 1 for succes, 0 if the module is not found, and -1 with
1969    an exception set if the initialization failed.
1970    This function is also used from frozenmain.c */
1971
1972 int
1973 PyImport_ImportFrozenModule(char *name)
1974 {
1975     struct _frozen *p = find_frozen(name);
1976     PyObject *co;
1977     PyObject *m;
1978     int ispackage;
1979     int size;
1980
1981     if (p == NULL)
1982         return 0;
1983     if (p->code == NULL) {
1984         PyErr_Format(PyExc_ImportError,
1985                      "Excluded frozen object named %.200s",
1986                      name);
1987         return -1;
1988     }
1989     size = p->size;
1990     ispackage = (size < 0);
1991     if (ispackage)
1992         size = -size;
1993     if (Py_VerboseFlag)
1994         PySys_WriteStderr("import %s # frozen%s\n",
1995             name, ispackage ? " package" : "");
1996     co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1997     if (co == NULL)
1998         return -1;
1999     if (!PyCode_Check(co)) {
2000         PyErr_Format(PyExc_TypeError,
2001                      "frozen object %.200s is not a code object",
2002                      name);
2003         goto err_return;
2004     }
2005     if (ispackage) {
2006         /* Set __path__ to the package name */
2007         PyObject *d, *s;
2008         int err;
2009         m = PyImport_AddModule(name);
2010         if (m == NULL)
2011             goto err_return;
2012         d = PyModule_GetDict(m);
2013         s = PyString_InternFromString(name);
2014         if (s == NULL)
2015             goto err_return;
2016         err = PyDict_SetItemString(d, "__path__", s);
2017         Py_DECREF(s);
2018         if (err != 0)
2019             goto err_return;
2020     }
2021     m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2022     if (m == NULL)
2023         goto err_return;
2024     Py_DECREF(co);
2025     Py_DECREF(m);
2026     return 1;
2027 err_return:
2028     Py_DECREF(co);
2029     return -1;
2030 }
2031
2032
2033 /* Import a module, either built-in, frozen, or external, and return
2034    its module object WITH INCREMENTED REFERENCE COUNT */
2035
2036 PyObject *
2037 PyImport_ImportModule(const char *name)
2038 {
2039     PyObject *pname;
2040     PyObject *result;
2041
2042     pname = PyString_FromString(name);
2043     if (pname == NULL)
2044         return NULL;
2045     result = PyImport_Import(pname);
2046     Py_DECREF(pname);
2047     return result;
2048 }
2049
2050 /* Import a module without blocking
2051  *
2052  * At first it tries to fetch the module from sys.modules. If the module was
2053  * never loaded before it loads it with PyImport_ImportModule() unless another
2054  * thread holds the import lock. In the latter case the function raises an
2055  * ImportError instead of blocking.
2056  *
2057  * Returns the module object with incremented ref count.
2058  */
2059 PyObject *
2060 PyImport_ImportModuleNoBlock(const char *name)
2061 {
2062     PyObject *result;
2063     PyObject *modules;
2064 #ifdef WITH_THREAD
2065     long me;
2066 #endif
2067
2068     /* Try to get the module from sys.modules[name] */
2069     modules = PyImport_GetModuleDict();
2070     if (modules == NULL)
2071         return NULL;
2072
2073     result = PyDict_GetItemString(modules, name);
2074     if (result != NULL) {
2075         Py_INCREF(result);
2076         return result;
2077     }
2078     else {
2079         PyErr_Clear();
2080     }
2081 #ifdef WITH_THREAD
2082     /* check the import lock
2083      * me might be -1 but I ignore the error here, the lock function
2084      * takes care of the problem */
2085     me = PyThread_get_thread_ident();
2086     if (import_lock_thread == -1 || import_lock_thread == me) {
2087         /* no thread or me is holding the lock */
2088         return PyImport_ImportModule(name);
2089     }
2090     else {
2091         PyErr_Format(PyExc_ImportError,
2092                      "Failed to import %.200s because the import lock"
2093                      "is held by another thread.",
2094                      name);
2095         return NULL;
2096     }
2097 #else
2098     return PyImport_ImportModule(name);
2099 #endif
2100 }
2101
2102 /* Forward declarations for helper routines */
2103 static PyObject *get_parent(PyObject *globals, char *buf,
2104                             Py_ssize_t *p_buflen, int level);
2105 static PyObject *load_next(PyObject *mod, PyObject *altmod,
2106                            char **p_name, char *buf, Py_ssize_t *p_buflen);
2107 static int mark_miss(char *name);
2108 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
2109                            char *buf, Py_ssize_t buflen, int recursive);
2110 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
2111
2112 /* The Magnum Opus of dotted-name import :-) */
2113
2114 static PyObject *
2115 import_module_level(char *name, PyObject *globals, PyObject *locals,
2116                     PyObject *fromlist, int level)
2117 {
2118     char buf[MAXPATHLEN+1];
2119     Py_ssize_t buflen = 0;
2120     PyObject *parent, *head, *next, *tail;
2121
2122     if (strchr(name, '/') != NULL
2123 #ifdef MS_WINDOWS
2124         || strchr(name, '\\') != NULL
2125 #endif
2126         ) {
2127         PyErr_SetString(PyExc_ImportError,
2128                         "Import by filename is not supported.");
2129         return NULL;
2130     }
2131
2132     parent = get_parent(globals, buf, &buflen, level);
2133     if (parent == NULL)
2134         return NULL;
2135
2136     head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2137                         &buflen);
2138     if (head == NULL)
2139         return NULL;
2140
2141     tail = head;
2142     Py_INCREF(tail);
2143     while (name) {
2144         next = load_next(tail, tail, &name, buf, &buflen);
2145         Py_DECREF(tail);
2146         if (next == NULL) {
2147             Py_DECREF(head);
2148             return NULL;
2149         }
2150         tail = next;
2151     }
2152     if (tail == Py_None) {
2153         /* If tail is Py_None, both get_parent and load_next found
2154            an empty module name: someone called __import__("") or
2155            doctored faulty bytecode */
2156         Py_DECREF(tail);
2157         Py_DECREF(head);
2158         PyErr_SetString(PyExc_ValueError,
2159                         "Empty module name");
2160         return NULL;
2161     }
2162
2163     if (fromlist != NULL) {
2164         if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2165             fromlist = NULL;
2166     }
2167
2168     if (fromlist == NULL) {
2169         Py_DECREF(tail);
2170         return head;
2171     }
2172
2173     Py_DECREF(head);
2174     if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2175         Py_DECREF(tail);
2176         return NULL;
2177     }
2178
2179     return tail;
2180 }
2181
2182 PyObject *
2183 PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2184                          PyObject *fromlist, int level)
2185 {
2186     PyObject *result;
2187     _PyImport_AcquireLock();
2188     result = import_module_level(name, globals, locals, fromlist, level);
2189     if (_PyImport_ReleaseLock() < 0) {
2190         Py_XDECREF(result);
2191         PyErr_SetString(PyExc_RuntimeError,
2192                         "not holding the import lock");
2193         return NULL;
2194     }
2195     return result;
2196 }
2197
2198 /* Return the package that an import is being performed in.  If globals comes
2199    from the module foo.bar.bat (not itself a package), this returns the
2200    sys.modules entry for foo.bar.  If globals is from a package's __init__.py,
2201    the package's entry in sys.modules is returned, as a borrowed reference.
2202
2203    The *name* of the returned package is returned in buf, with the length of
2204    the name in *p_buflen.
2205
2206    If globals doesn't come from a package or a module in a package, or a
2207    corresponding entry is not found in sys.modules, Py_None is returned.
2208 */
2209 static PyObject *
2210 get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
2211 {
2212     static PyObject *namestr = NULL;
2213     static PyObject *pathstr = NULL;
2214     static PyObject *pkgstr = NULL;
2215     PyObject *pkgname, *modname, *modpath, *modules, *parent;
2216     int orig_level = level;
2217
2218     if (globals == NULL || !PyDict_Check(globals) || !level)
2219         return Py_None;
2220
2221     if (namestr == NULL) {
2222         namestr = PyString_InternFromString("__name__");
2223         if (namestr == NULL)
2224             return NULL;
2225     }
2226     if (pathstr == NULL) {
2227         pathstr = PyString_InternFromString("__path__");
2228         if (pathstr == NULL)
2229             return NULL;
2230     }
2231     if (pkgstr == NULL) {
2232         pkgstr = PyString_InternFromString("__package__");
2233         if (pkgstr == NULL)
2234             return NULL;
2235     }
2236
2237     *buf = '\0';
2238     *p_buflen = 0;
2239     pkgname = PyDict_GetItem(globals, pkgstr);
2240
2241     if ((pkgname != NULL) && (pkgname != Py_None)) {
2242         /* __package__ is set, so use it */
2243         Py_ssize_t len;
2244         if (!PyString_Check(pkgname)) {
2245             PyErr_SetString(PyExc_ValueError,
2246                             "__package__ set to non-string");
2247             return NULL;
2248         }
2249         len = PyString_GET_SIZE(pkgname);
2250         if (len == 0) {
2251             if (level > 0) {
2252                 PyErr_SetString(PyExc_ValueError,
2253                     "Attempted relative import in non-package");
2254                 return NULL;
2255             }
2256             return Py_None;
2257         }
2258         if (len > MAXPATHLEN) {
2259             PyErr_SetString(PyExc_ValueError,
2260                             "Package name too long");
2261             return NULL;
2262         }
2263         strcpy(buf, PyString_AS_STRING(pkgname));
2264     } else {
2265         /* __package__ not set, so figure it out and set it */
2266         modname = PyDict_GetItem(globals, namestr);
2267         if (modname == NULL || !PyString_Check(modname))
2268             return Py_None;
2269
2270         modpath = PyDict_GetItem(globals, pathstr);
2271         if (modpath != NULL) {
2272             /* __path__ is set, so modname is already the package name */
2273             Py_ssize_t len = PyString_GET_SIZE(modname);
2274             int error;
2275             if (len > MAXPATHLEN) {
2276                 PyErr_SetString(PyExc_ValueError,
2277                                 "Module name too long");
2278                 return NULL;
2279             }
2280             strcpy(buf, PyString_AS_STRING(modname));
2281             error = PyDict_SetItem(globals, pkgstr, modname);
2282             if (error) {
2283                 PyErr_SetString(PyExc_ValueError,
2284                                 "Could not set __package__");
2285                 return NULL;
2286             }
2287         } else {
2288             /* Normal module, so work out the package name if any */
2289             char *start = PyString_AS_STRING(modname);
2290             char *lastdot = strrchr(start, '.');
2291             size_t len;
2292             int error;
2293             if (lastdot == NULL && level > 0) {
2294                 PyErr_SetString(PyExc_ValueError,
2295                     "Attempted relative import in non-package");
2296                 return NULL;
2297             }
2298             if (lastdot == NULL) {
2299                 error = PyDict_SetItem(globals, pkgstr, Py_None);
2300                 if (error) {
2301                     PyErr_SetString(PyExc_ValueError,
2302                         "Could not set __package__");
2303                     return NULL;
2304                 }
2305                 return Py_None;
2306             }
2307             len = lastdot - start;
2308             if (len >= MAXPATHLEN) {
2309                 PyErr_SetString(PyExc_ValueError,
2310                                 "Module name too long");
2311                 return NULL;
2312             }
2313             strncpy(buf, start, len);
2314             buf[len] = '\0';
2315             pkgname = PyString_FromString(buf);
2316             if (pkgname == NULL) {
2317                 return NULL;
2318             }
2319             error = PyDict_SetItem(globals, pkgstr, pkgname);
2320             Py_DECREF(pkgname);
2321             if (error) {
2322                 PyErr_SetString(PyExc_ValueError,
2323                                 "Could not set __package__");
2324                 return NULL;
2325             }
2326         }
2327     }
2328     while (--level > 0) {
2329         char *dot = strrchr(buf, '.');
2330         if (dot == NULL) {
2331             PyErr_SetString(PyExc_ValueError,
2332                 "Attempted relative import beyond "
2333                 "toplevel package");
2334             return NULL;
2335         }
2336         *dot = '\0';
2337     }
2338     *p_buflen = strlen(buf);
2339
2340     modules = PyImport_GetModuleDict();
2341     parent = PyDict_GetItemString(modules, buf);
2342     if (parent == NULL) {
2343         if (orig_level < 1) {
2344             PyObject *err_msg = PyString_FromFormat(
2345                 "Parent module '%.200s' not found "
2346                 "while handling absolute import", buf);
2347             if (err_msg == NULL) {
2348                 return NULL;
2349             }
2350             if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2351                             PyString_AsString(err_msg), 1)) {
2352                 *buf = '\0';
2353                 *p_buflen = 0;
2354                 parent = Py_None;
2355             }
2356             Py_DECREF(err_msg);
2357         } else {
2358             PyErr_Format(PyExc_SystemError,
2359                 "Parent module '%.200s' not loaded, "
2360                 "cannot perform relative import", buf);
2361         }
2362     }
2363     return parent;
2364     /* We expect, but can't guarantee, if parent != None, that:
2365        - parent.__name__ == buf
2366        - parent.__dict__ is globals
2367        If this is violated...  Who cares? */
2368 }
2369
2370 /* altmod is either None or same as mod */
2371 static PyObject *
2372 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
2373           Py_ssize_t *p_buflen)
2374 {
2375     char *name = *p_name;
2376     char *dot = strchr(name, '.');
2377     size_t len;
2378     char *p;
2379     PyObject *result;
2380
2381     if (strlen(name) == 0) {
2382         /* completely empty module name should only happen in
2383            'from . import' (or '__import__("")')*/
2384         Py_INCREF(mod);
2385         *p_name = NULL;
2386         return mod;
2387     }
2388
2389     if (dot == NULL) {
2390         *p_name = NULL;
2391         len = strlen(name);
2392     }
2393     else {
2394         *p_name = dot+1;
2395         len = dot-name;
2396     }
2397     if (len == 0) {
2398         PyErr_SetString(PyExc_ValueError,
2399                         "Empty module name");
2400         return NULL;
2401     }
2402
2403     p = buf + *p_buflen;
2404     if (p != buf)
2405         *p++ = '.';
2406     if (p+len-buf >= MAXPATHLEN) {
2407         PyErr_SetString(PyExc_ValueError,
2408                         "Module name too long");
2409         return NULL;
2410     }
2411     strncpy(p, name, len);
2412     p[len] = '\0';
2413     *p_buflen = p+len-buf;
2414
2415     result = import_submodule(mod, p, buf);
2416     if (result == Py_None && altmod != mod) {
2417         Py_DECREF(result);
2418         /* Here, altmod must be None and mod must not be None */
2419         result = import_submodule(altmod, p, p);
2420         if (result != NULL && result != Py_None) {
2421             if (mark_miss(buf) != 0) {
2422                 Py_DECREF(result);
2423                 return NULL;
2424             }
2425             strncpy(buf, name, len);
2426             buf[len] = '\0';
2427             *p_buflen = len;
2428         }
2429     }
2430     if (result == NULL)
2431         return NULL;
2432
2433     if (result == Py_None) {
2434         Py_DECREF(result);
2435         PyErr_Format(PyExc_ImportError,
2436                      "No module named %.200s", name);
2437         return NULL;
2438     }
2439
2440     return result;
2441 }
2442
2443 static int
2444 mark_miss(char *name)
2445 {
2446     PyObject *modules = PyImport_GetModuleDict();
2447     return PyDict_SetItemString(modules, name, Py_None);
2448 }
2449
2450 static int
2451 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
2452                 int recursive)
2453 {
2454     int i;
2455
2456     if (!PyObject_HasAttrString(mod, "__path__"))
2457         return 1;
2458
2459     for (i = 0; ; i++) {
2460         PyObject *item = PySequence_GetItem(fromlist, i);
2461         int hasit;
2462         if (item == NULL) {
2463             if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2464                 PyErr_Clear();
2465                 return 1;
2466             }
2467             return 0;
2468         }
2469         if (!PyString_Check(item)) {
2470             PyErr_SetString(PyExc_TypeError,
2471                             "Item in ``from list'' not a string");
2472             Py_DECREF(item);
2473             return 0;
2474         }
2475         if (PyString_AS_STRING(item)[0] == '*') {
2476             PyObject *all;
2477             Py_DECREF(item);
2478             /* See if the package defines __all__ */
2479             if (recursive)
2480                 continue; /* Avoid endless recursion */
2481             all = PyObject_GetAttrString(mod, "__all__");
2482             if (all == NULL)
2483                 PyErr_Clear();
2484             else {
2485                 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2486                 Py_DECREF(all);
2487                 if (!ret)
2488                     return 0;
2489             }
2490             continue;
2491         }
2492         hasit = PyObject_HasAttr(mod, item);
2493         if (!hasit) {
2494             char *subname = PyString_AS_STRING(item);
2495             PyObject *submod;
2496             char *p;
2497             if (buflen + strlen(subname) >= MAXPATHLEN) {
2498                 PyErr_SetString(PyExc_ValueError,
2499                                 "Module name too long");
2500                 Py_DECREF(item);
2501                 return 0;
2502             }
2503             p = buf + buflen;
2504             *p++ = '.';
2505             strcpy(p, subname);
2506             submod = import_submodule(mod, subname, buf);
2507             Py_XDECREF(submod);
2508             if (submod == NULL) {
2509                 Py_DECREF(item);
2510                 return 0;
2511             }
2512         }
2513         Py_DECREF(item);
2514     }
2515
2516     /* NOTREACHED */
2517 }
2518
2519 static int
2520 add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2521               PyObject *modules)
2522 {
2523     if (mod == Py_None)
2524         return 1;
2525     /* Irrespective of the success of this load, make a
2526        reference to it in the parent package module.  A copy gets
2527        saved in the modules dictionary under the full name, so get a
2528        reference from there, if need be.  (The exception is when the
2529        load failed with a SyntaxError -- then there's no trace in
2530        sys.modules.  In that case, of course, do nothing extra.) */
2531     if (submod == NULL) {
2532         submod = PyDict_GetItemString(modules, fullname);
2533         if (submod == NULL)
2534             return 1;
2535     }
2536     if (PyModule_Check(mod)) {
2537         /* We can't use setattr here since it can give a
2538          * spurious warning if the submodule name shadows a
2539          * builtin name */
2540         PyObject *dict = PyModule_GetDict(mod);
2541         if (!dict)
2542             return 0;
2543         if (PyDict_SetItemString(dict, subname, submod) < 0)
2544             return 0;
2545     }
2546     else {
2547         if (PyObject_SetAttrString(mod, subname, submod) < 0)
2548             return 0;
2549     }
2550     return 1;
2551 }
2552
2553 static PyObject *
2554 import_submodule(PyObject *mod, char *subname, char *fullname)
2555 {
2556     PyObject *modules = PyImport_GetModuleDict();
2557     PyObject *m = NULL;
2558
2559     /* Require:
2560        if mod == None: subname == fullname
2561        else: mod.__name__ + "." + subname == fullname
2562     */
2563
2564     if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2565         Py_INCREF(m);
2566     }
2567     else {
2568         PyObject *path, *loader = NULL;
2569         char buf[MAXPATHLEN+1];
2570         struct filedescr *fdp;
2571         FILE *fp = NULL;
2572
2573         if (mod == Py_None)
2574             path = NULL;
2575         else {
2576             path = PyObject_GetAttrString(mod, "__path__");
2577             if (path == NULL) {
2578                 PyErr_Clear();
2579                 Py_INCREF(Py_None);
2580                 return Py_None;
2581             }
2582         }
2583
2584         buf[0] = '\0';
2585         fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2586                           &fp, &loader);
2587         Py_XDECREF(path);
2588         if (fdp == NULL) {
2589             if (!PyErr_ExceptionMatches(PyExc_ImportError))
2590                 return NULL;
2591             PyErr_Clear();
2592             Py_INCREF(Py_None);
2593             return Py_None;
2594         }
2595         m = load_module(fullname, fp, buf, fdp->type, loader);
2596         Py_XDECREF(loader);
2597         if (fp)
2598             fclose(fp);
2599         if (!add_submodule(mod, m, fullname, subname, modules)) {
2600             Py_XDECREF(m);
2601             m = NULL;
2602         }
2603     }
2604
2605     return m;
2606 }
2607
2608
2609 /* Re-import a module of any kind and return its module object, WITH
2610    INCREMENTED REFERENCE COUNT */
2611
2612 PyObject *
2613 PyImport_ReloadModule(PyObject *m)
2614 {
2615     PyInterpreterState *interp = PyThreadState_Get()->interp;
2616     PyObject *modules_reloading = interp->modules_reloading;
2617     PyObject *modules = PyImport_GetModuleDict();
2618     PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2619     char *name, *subname;
2620     char buf[MAXPATHLEN+1];
2621     struct filedescr *fdp;
2622     FILE *fp = NULL;
2623     PyObject *newm;
2624
2625     if (modules_reloading == NULL) {
2626         Py_FatalError("PyImport_ReloadModule: "
2627                       "no modules_reloading dictionary!");
2628         return NULL;
2629     }
2630
2631     if (m == NULL || !PyModule_Check(m)) {
2632         PyErr_SetString(PyExc_TypeError,
2633                         "reload() argument must be module");
2634         return NULL;
2635     }
2636     name = PyModule_GetName(m);
2637     if (name == NULL)
2638         return NULL;
2639     if (m != PyDict_GetItemString(modules, name)) {
2640         PyErr_Format(PyExc_ImportError,
2641                      "reload(): module %.200s not in sys.modules",
2642                      name);
2643         return NULL;
2644     }
2645     existing_m = PyDict_GetItemString(modules_reloading, name);
2646     if (existing_m != NULL) {
2647         /* Due to a recursive reload, this module is already
2648            being reloaded. */
2649         Py_INCREF(existing_m);
2650         return existing_m;
2651     }
2652     if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2653         return NULL;
2654
2655     subname = strrchr(name, '.');
2656     if (subname == NULL)
2657         subname = name;
2658     else {
2659         PyObject *parentname, *parent;
2660         parentname = PyString_FromStringAndSize(name, (subname-name));
2661         if (parentname == NULL) {
2662             imp_modules_reloading_clear();
2663             return NULL;
2664         }
2665         parent = PyDict_GetItem(modules, parentname);
2666         if (parent == NULL) {
2667             PyErr_Format(PyExc_ImportError,
2668                 "reload(): parent %.200s not in sys.modules",
2669                 PyString_AS_STRING(parentname));
2670             Py_DECREF(parentname);
2671             imp_modules_reloading_clear();
2672             return NULL;
2673         }
2674         Py_DECREF(parentname);
2675         subname++;
2676         path = PyObject_GetAttrString(parent, "__path__");
2677         if (path == NULL)
2678             PyErr_Clear();
2679     }
2680     buf[0] = '\0';
2681     fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2682     Py_XDECREF(path);
2683
2684     if (fdp == NULL) {
2685         Py_XDECREF(loader);
2686         imp_modules_reloading_clear();
2687         return NULL;
2688     }
2689
2690     newm = load_module(name, fp, buf, fdp->type, loader);
2691     Py_XDECREF(loader);
2692
2693     if (fp)
2694         fclose(fp);
2695     if (newm == NULL) {
2696         /* load_module probably removed name from modules because of
2697          * the error.  Put back the original module object.  We're
2698          * going to return NULL in this case regardless of whether
2699          * replacing name succeeds, so the return value is ignored.
2700          */
2701         PyDict_SetItemString(modules, name, m);
2702     }
2703     imp_modules_reloading_clear();
2704     return newm;
2705 }
2706
2707
2708 /* Higher-level import emulator which emulates the "import" statement
2709    more accurately -- it invokes the __import__() function from the
2710    builtins of the current globals.  This means that the import is
2711    done using whatever import hooks are installed in the current
2712    environment, e.g. by "rexec".
2713    A dummy list ["__doc__"] is passed as the 4th argument so that
2714    e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2715    will return <module "gencache"> instead of <module "win32com">. */
2716
2717 PyObject *
2718 PyImport_Import(PyObject *module_name)
2719 {
2720     static PyObject *silly_list = NULL;
2721     static PyObject *builtins_str = NULL;
2722     static PyObject *import_str = NULL;
2723     PyObject *globals = NULL;
2724     PyObject *import = NULL;
2725     PyObject *builtins = NULL;
2726     PyObject *r = NULL;
2727
2728     /* Initialize constant string objects */
2729     if (silly_list == NULL) {
2730         import_str = PyString_InternFromString("__import__");
2731         if (import_str == NULL)
2732             return NULL;
2733         builtins_str = PyString_InternFromString("__builtins__");
2734         if (builtins_str == NULL)
2735             return NULL;
2736         silly_list = Py_BuildValue("[s]", "__doc__");
2737         if (silly_list == NULL)
2738             return NULL;
2739     }
2740
2741     /* Get the builtins from current globals */
2742     globals = PyEval_GetGlobals();
2743     if (globals != NULL) {
2744         Py_INCREF(globals);
2745         builtins = PyObject_GetItem(globals, builtins_str);
2746         if (builtins == NULL)
2747             goto err;
2748     }
2749     else {
2750         /* No globals -- use standard builtins, and fake globals */
2751         builtins = PyImport_ImportModuleLevel("__builtin__",
2752                                               NULL, NULL, NULL, 0);
2753         if (builtins == NULL)
2754             return NULL;
2755         globals = Py_BuildValue("{OO}", builtins_str, builtins);
2756         if (globals == NULL)
2757             goto err;
2758     }
2759
2760     /* Get the __import__ function from the builtins */
2761     if (PyDict_Check(builtins)) {
2762         import = PyObject_GetItem(builtins, import_str);
2763         if (import == NULL)
2764             PyErr_SetObject(PyExc_KeyError, import_str);
2765     }
2766     else
2767         import = PyObject_GetAttr(builtins, import_str);
2768     if (import == NULL)
2769         goto err;
2770
2771     /* Call the __import__ function with the proper argument list
2772      * Always use absolute import here. */
2773     r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2774                               globals, silly_list, 0, NULL);
2775
2776   err:
2777     Py_XDECREF(globals);
2778     Py_XDECREF(builtins);
2779     Py_XDECREF(import);
2780
2781     return r;
2782 }
2783
2784
2785 /* Module 'imp' provides Python access to the primitives used for
2786    importing modules.
2787 */
2788
2789 static PyObject *
2790 imp_get_magic(PyObject *self, PyObject *noargs)
2791 {
2792     char buf[4];
2793
2794     buf[0] = (char) ((pyc_magic >>  0) & 0xff);
2795     buf[1] = (char) ((pyc_magic >>  8) & 0xff);
2796     buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2797     buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2798
2799     return PyString_FromStringAndSize(buf, 4);
2800 }
2801
2802 static PyObject *
2803 imp_get_suffixes(PyObject *self, PyObject *noargs)
2804 {
2805     PyObject *list;
2806     struct filedescr *fdp;
2807
2808     list = PyList_New(0);
2809     if (list == NULL)
2810         return NULL;
2811     for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2812         PyObject *item = Py_BuildValue("ssi",
2813                                fdp->suffix, fdp->mode, fdp->type);
2814         if (item == NULL) {
2815             Py_DECREF(list);
2816             return NULL;
2817         }
2818         if (PyList_Append(list, item) < 0) {
2819             Py_DECREF(list);
2820             Py_DECREF(item);
2821             return NULL;
2822         }
2823         Py_DECREF(item);
2824     }
2825     return list;
2826 }
2827
2828 static PyObject *
2829 call_find_module(char *name, PyObject *path)
2830 {
2831     extern int fclose(FILE *);
2832     PyObject *fob, *ret;
2833     struct filedescr *fdp;
2834     char pathname[MAXPATHLEN+1];
2835     FILE *fp = NULL;
2836
2837     pathname[0] = '\0';
2838     if (path == Py_None)
2839         path = NULL;
2840     fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
2841     if (fdp == NULL)
2842         return NULL;
2843     if (fp != NULL) {
2844         fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2845         if (fob == NULL)
2846             return NULL;
2847     }
2848     else {
2849         fob = Py_None;
2850         Py_INCREF(fob);
2851     }
2852     ret = Py_BuildValue("Os(ssi)",
2853                   fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2854     Py_DECREF(fob);
2855     return ret;
2856 }
2857
2858 static PyObject *
2859 imp_find_module(PyObject *self, PyObject *args)
2860 {
2861     char *name;
2862     PyObject *path = NULL;
2863     if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2864         return NULL;
2865     return call_find_module(name, path);
2866 }
2867
2868 static PyObject *
2869 imp_init_builtin(PyObject *self, PyObject *args)
2870 {
2871     char *name;
2872     int ret;
2873     PyObject *m;
2874     if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2875         return NULL;
2876     ret = init_builtin(name);
2877     if (ret < 0)
2878         return NULL;
2879     if (ret == 0) {
2880         Py_INCREF(Py_None);
2881         return Py_None;
2882     }
2883     m = PyImport_AddModule(name);
2884     Py_XINCREF(m);
2885     return m;
2886 }
2887
2888 static PyObject *
2889 imp_init_frozen(PyObject *self, PyObject *args)
2890 {
2891     char *name;
2892     int ret;
2893     PyObject *m;
2894     if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2895         return NULL;
2896     ret = PyImport_ImportFrozenModule(name);
2897     if (ret < 0)
2898         return NULL;
2899     if (ret == 0) {
2900         Py_INCREF(Py_None);
2901         return Py_None;
2902     }
2903     m = PyImport_AddModule(name);
2904     Py_XINCREF(m);
2905     return m;
2906 }
2907
2908 static PyObject *
2909 imp_get_frozen_object(PyObject *self, PyObject *args)
2910 {
2911     char *name;
2912
2913     if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2914         return NULL;
2915     return get_frozen_object(name);
2916 }
2917
2918 static PyObject *
2919 imp_is_builtin(PyObject *self, PyObject *args)
2920 {
2921     char *name;
2922     if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2923         return NULL;
2924     return PyInt_FromLong(is_builtin(name));
2925 }
2926
2927 static PyObject *
2928 imp_is_frozen(PyObject *self, PyObject *args)
2929 {
2930     char *name;
2931     struct _frozen *p;
2932     if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2933         return NULL;
2934     p = find_frozen(name);
2935     return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2936 }
2937
2938 static FILE *
2939 get_file(char *pathname, PyObject *fob, char *mode)
2940 {
2941     FILE *fp;
2942     if (fob == NULL) {
2943         if (mode[0] == 'U')
2944             mode = "r" PY_STDIOTEXTMODE;
2945         fp = fopen(pathname, mode);
2946         if (fp == NULL)
2947             PyErr_SetFromErrno(PyExc_IOError);
2948     }
2949     else {
2950         fp = PyFile_AsFile(fob);
2951         if (fp == NULL)
2952             PyErr_SetString(PyExc_ValueError,
2953                             "bad/closed file object");
2954     }
2955     return fp;
2956 }
2957
2958 static PyObject *
2959 imp_load_compiled(PyObject *self, PyObject *args)
2960 {
2961     char *name;
2962     char *pathname;
2963     PyObject *fob = NULL;
2964     PyObject *m;
2965     FILE *fp;
2966     if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2967                           &PyFile_Type, &fob))
2968         return NULL;
2969     fp = get_file(pathname, fob, "rb");
2970     if (fp == NULL)
2971         return NULL;
2972     m = load_compiled_module(name, pathname, fp);
2973     if (fob == NULL)
2974         fclose(fp);
2975     return m;
2976 }
2977
2978 #ifdef HAVE_DYNAMIC_LOADING
2979
2980 static PyObject *
2981 imp_load_dynamic(PyObject *self, PyObject *args)
2982 {
2983     char *name;
2984     char *pathname;
2985     PyObject *fob = NULL;
2986     PyObject *m;
2987     FILE *fp = NULL;
2988     if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2989                           &PyFile_Type, &fob))
2990         return NULL;
2991     if (fob) {
2992         fp = get_file(pathname, fob, "r");
2993         if (fp == NULL)
2994             return NULL;
2995     }
2996     m = _PyImport_LoadDynamicModule(name, pathname, fp);
2997     return m;
2998 }
2999
3000 #endif /* HAVE_DYNAMIC_LOADING */
3001
3002 static PyObject *
3003 imp_load_source(PyObject *self, PyObject *args)
3004 {
3005     char *name;
3006     char *pathname;
3007     PyObject *fob = NULL;
3008     PyObject *m;
3009     FILE *fp;
3010     if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
3011                           &PyFile_Type, &fob))
3012         return NULL;
3013     fp = get_file(pathname, fob, "r");
3014     if (fp == NULL)
3015         return NULL;
3016     m = load_source_module(name, pathname, fp);
3017     if (fob == NULL)
3018         fclose(fp);
3019     return m;
3020 }
3021
3022 static PyObject *
3023 imp_load_module(PyObject *self, PyObject *args)
3024 {
3025     char *name;
3026     PyObject *fob;
3027     char *pathname;
3028     char *suffix; /* Unused */
3029     char *mode;
3030     int type;
3031     FILE *fp;
3032
3033     if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
3034                           &name, &fob, &pathname,
3035                           &suffix, &mode, &type))
3036         return NULL;
3037     if (*mode) {
3038         /* Mode must start with 'r' or 'U' and must not contain '+'.
3039            Implicit in this test is the assumption that the mode
3040            may contain other modifiers like 'b' or 't'. */
3041
3042         if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3043             PyErr_Format(PyExc_ValueError,
3044                          "invalid file open mode %.200s", mode);
3045             return NULL;
3046         }
3047     }
3048     if (fob == Py_None)
3049         fp = NULL;
3050     else {
3051         if (!PyFile_Check(fob)) {
3052             PyErr_SetString(PyExc_ValueError,
3053                 "load_module arg#2 should be a file or None");
3054             return NULL;
3055         }
3056         fp = get_file(pathname, fob, mode);
3057         if (fp == NULL)
3058             return NULL;
3059     }
3060     return load_module(name, fp, pathname, type, NULL);
3061 }
3062
3063 static PyObject *
3064 imp_load_package(PyObject *self, PyObject *args)
3065 {
3066     char *name;
3067     char *pathname;
3068     if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
3069         return NULL;
3070     return load_package(name, pathname);
3071 }
3072
3073 static PyObject *
3074 imp_new_module(PyObject *self, PyObject *args)
3075 {
3076     char *name;
3077     if (!PyArg_ParseTuple(args, "s:new_module", &name))
3078         return NULL;
3079     return PyModule_New(name);
3080 }
3081
3082 static PyObject *
3083 imp_reload(PyObject *self, PyObject *v)
3084 {
3085     return PyImport_ReloadModule(v);
3086 }
3087
3088
3089 /* Doc strings */
3090
3091 PyDoc_STRVAR(doc_imp,
3092 "This module provides the components needed to build your own\n\
3093 __import__ function.  Undocumented functions are obsolete.");
3094
3095 PyDoc_STRVAR(doc_reload,
3096 "reload(module) -> module\n\
3097 \n\
3098 Reload the module.  The module must have been successfully imported before.");
3099
3100 PyDoc_STRVAR(doc_find_module,
3101 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
3102 Search for a module.  If path is omitted or None, search for a\n\
3103 built-in, frozen or special module and continue search in sys.path.\n\
3104 The module name cannot contain '.'; to search for a submodule of a\n\
3105 package, pass the submodule name and the package's __path__.");
3106
3107 PyDoc_STRVAR(doc_load_module,
3108 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
3109 Load a module, given information returned by find_module().\n\
3110 The module name must include the full package name, if any.");
3111
3112 PyDoc_STRVAR(doc_get_magic,
3113 "get_magic() -> string\n\
3114 Return the magic number for .pyc or .pyo files.");
3115
3116 PyDoc_STRVAR(doc_get_suffixes,
3117 "get_suffixes() -> [(suffix, mode, type), ...]\n\
3118 Return a list of (suffix, mode, type) tuples describing the files\n\
3119 that find_module() looks for.");
3120
3121 PyDoc_STRVAR(doc_new_module,
3122 "new_module(name) -> module\n\
3123 Create a new module.  Do not enter it in sys.modules.\n\
3124 The module name must include the full package name, if any.");
3125
3126 PyDoc_STRVAR(doc_lock_held,
3127 "lock_held() -> boolean\n\
3128 Return True if the import lock is currently held, else False.\n\
3129 On platforms without threads, return False.");
3130
3131 PyDoc_STRVAR(doc_acquire_lock,
3132 "acquire_lock() -> None\n\
3133 Acquires the interpreter's import lock for the current thread.\n\
3134 This lock should be used by import hooks to ensure thread-safety\n\
3135 when importing modules.\n\
3136 On platforms without threads, this function does nothing.");
3137
3138 PyDoc_STRVAR(doc_release_lock,
3139 "release_lock() -> None\n\
3140 Release the interpreter's import lock.\n\
3141 On platforms without threads, this function does nothing.");
3142
3143 static PyMethodDef imp_methods[] = {
3144     {"reload",           imp_reload,       METH_O,       doc_reload},
3145     {"find_module",      imp_find_module,  METH_VARARGS, doc_find_module},
3146     {"get_magic",        imp_get_magic,    METH_NOARGS,  doc_get_magic},
3147     {"get_suffixes", imp_get_suffixes, METH_NOARGS,  doc_get_suffixes},
3148     {"load_module",      imp_load_module,  METH_VARARGS, doc_load_module},
3149     {"new_module",       imp_new_module,   METH_VARARGS, doc_new_module},
3150     {"lock_held",        imp_lock_held,    METH_NOARGS,  doc_lock_held},
3151     {"acquire_lock", imp_acquire_lock, METH_NOARGS,  doc_acquire_lock},
3152     {"release_lock", imp_release_lock, METH_NOARGS,  doc_release_lock},
3153     /* The rest are obsolete */
3154     {"get_frozen_object",       imp_get_frozen_object,  METH_VARARGS},
3155     {"init_builtin",            imp_init_builtin,       METH_VARARGS},
3156     {"init_frozen",             imp_init_frozen,        METH_VARARGS},
3157     {"is_builtin",              imp_is_builtin,         METH_VARARGS},
3158     {"is_frozen",               imp_is_frozen,          METH_VARARGS},
3159     {"load_compiled",           imp_load_compiled,      METH_VARARGS},
3160 #ifdef HAVE_DYNAMIC_LOADING
3161     {"load_dynamic",            imp_load_dynamic,       METH_VARARGS},
3162 #endif
3163     {"load_package",            imp_load_package,       METH_VARARGS},
3164     {"load_source",             imp_load_source,        METH_VARARGS},
3165     {NULL,                      NULL}           /* sentinel */
3166 };
3167
3168 static int
3169 setint(PyObject *d, char *name, int value)
3170 {
3171     PyObject *v;
3172     int err;
3173
3174     v = PyInt_FromLong((long)value);
3175     err = PyDict_SetItemString(d, name, v);
3176     Py_XDECREF(v);
3177     return err;
3178 }
3179
3180 typedef struct {
3181     PyObject_HEAD
3182 } NullImporter;
3183
3184 static int
3185 NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3186 {
3187     char *path;
3188     Py_ssize_t pathlen;
3189
3190     if (!_PyArg_NoKeywords("NullImporter()", kwds))
3191         return -1;
3192
3193     if (!PyArg_ParseTuple(args, "s:NullImporter",
3194                           &path))
3195         return -1;
3196
3197     pathlen = strlen(path);
3198     if (pathlen == 0) {
3199         PyErr_SetString(PyExc_ImportError, "empty pathname");
3200         return -1;
3201     } else {
3202 #ifndef RISCOS
3203 #ifndef MS_WINDOWS
3204         struct stat statbuf;
3205         int rv;
3206
3207         rv = stat(path, &statbuf);
3208         if (rv == 0) {
3209             /* it exists */
3210             if (S_ISDIR(statbuf.st_mode)) {
3211                 /* it's a directory */
3212                 PyErr_SetString(PyExc_ImportError,
3213                                 "existing directory");
3214                 return -1;
3215             }
3216         }
3217 #else /* MS_WINDOWS */
3218         DWORD rv;
3219         /* see issue1293 and issue3677:
3220          * stat() on Windows doesn't recognise paths like
3221          * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3222          */
3223         rv = GetFileAttributesA(path);
3224         if (rv != INVALID_FILE_ATTRIBUTES) {
3225             /* it exists */
3226             if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3227                 /* it's a directory */
3228                 PyErr_SetString(PyExc_ImportError,
3229                                 "existing directory");
3230                 return -1;
3231             }
3232         }
3233 #endif
3234 #else /* RISCOS */
3235         if (object_exists(path)) {
3236             /* it exists */
3237             if (isdir(path)) {
3238                 /* it's a directory */
3239                 PyErr_SetString(PyExc_ImportError,
3240                                 "existing directory");
3241                 return -1;
3242             }
3243         }
3244 #endif
3245     }
3246     return 0;
3247 }
3248
3249 static PyObject *
3250 NullImporter_find_module(NullImporter *self, PyObject *args)
3251 {
3252     Py_RETURN_NONE;
3253 }
3254
3255 static PyMethodDef NullImporter_methods[] = {
3256     {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3257      "Always return None"
3258     },
3259     {NULL}  /* Sentinel */
3260 };
3261
3262
3263 PyTypeObject PyNullImporter_Type = {
3264     PyVarObject_HEAD_INIT(NULL, 0)
3265     "imp.NullImporter",        /*tp_name*/
3266     sizeof(NullImporter),      /*tp_basicsize*/
3267     0,                         /*tp_itemsize*/
3268     0,                         /*tp_dealloc*/
3269     0,                         /*tp_print*/
3270     0,                         /*tp_getattr*/
3271     0,                         /*tp_setattr*/
3272     0,                         /*tp_compare*/
3273     0,                         /*tp_repr*/
3274     0,                         /*tp_as_number*/
3275     0,                         /*tp_as_sequence*/
3276     0,                         /*tp_as_mapping*/
3277     0,                         /*tp_hash */
3278     0,                         /*tp_call*/
3279     0,                         /*tp_str*/
3280     0,                         /*tp_getattro*/
3281     0,                         /*tp_setattro*/
3282     0,                         /*tp_as_buffer*/
3283     Py_TPFLAGS_DEFAULT,        /*tp_flags*/
3284     "Null importer object",    /* tp_doc */
3285     0,                             /* tp_traverse */
3286     0,                             /* tp_clear */
3287     0,                             /* tp_richcompare */
3288     0,                             /* tp_weaklistoffset */
3289     0,                             /* tp_iter */
3290     0,                             /* tp_iternext */
3291     NullImporter_methods,      /* tp_methods */
3292     0,                         /* tp_members */
3293     0,                         /* tp_getset */
3294     0,                         /* tp_base */
3295     0,                         /* tp_dict */
3296     0,                         /* tp_descr_get */
3297     0,                         /* tp_descr_set */
3298     0,                         /* tp_dictoffset */
3299     (initproc)NullImporter_init,      /* tp_init */
3300     0,                         /* tp_alloc */
3301     PyType_GenericNew          /* tp_new */
3302 };
3303
3304
3305 PyMODINIT_FUNC
3306 initimp(void)
3307 {
3308     PyObject *m, *d;
3309
3310     if (PyType_Ready(&PyNullImporter_Type) < 0)
3311         goto failure;
3312
3313     m = Py_InitModule4("imp", imp_methods, doc_imp,
3314                        NULL, PYTHON_API_VERSION);
3315     if (m == NULL)
3316         goto failure;
3317     d = PyModule_GetDict(m);
3318     if (d == NULL)
3319         goto failure;
3320
3321     if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3322     if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3323     if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3324     if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3325     if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3326     if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3327     if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3328     if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3329     if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3330     if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
3331
3332     Py_INCREF(&PyNullImporter_Type);
3333     PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3334   failure:
3335     ;
3336 }
3337
3338
3339 /* API for embedding applications that want to add their own entries
3340    to the table of built-in modules.  This should normally be called
3341    *before* Py_Initialize().  When the table resize fails, -1 is
3342    returned and the existing table is unchanged.
3343
3344    After a similar function by Just van Rossum. */
3345
3346 int
3347 PyImport_ExtendInittab(struct _inittab *newtab)
3348 {
3349     static struct _inittab *our_copy = NULL;
3350     struct _inittab *p;
3351     int i, n;
3352
3353     /* Count the number of entries in both tables */
3354     for (n = 0; newtab[n].name != NULL; n++)
3355         ;
3356     if (n == 0)
3357         return 0; /* Nothing to do */
3358     for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3359         ;
3360
3361     /* Allocate new memory for the combined table */
3362     p = our_copy;
3363     PyMem_RESIZE(p, struct _inittab, i+n+1);
3364     if (p == NULL)
3365         return -1;
3366
3367     /* Copy the tables into the new memory */
3368     if (our_copy != PyImport_Inittab)
3369         memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3370     PyImport_Inittab = our_copy = p;
3371     memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3372
3373     return 0;
3374 }
3375
3376 /* Shorthand to add a single entry given a name and a function */
3377
3378 int
3379 PyImport_AppendInittab(const char *name, void (*initfunc)(void))
3380 {
3381     struct _inittab newtab[2];
3382
3383     memset(newtab, '\0', sizeof newtab);
3384
3385     newtab[0].name = (char *)name;
3386     newtab[0].initfunc = initfunc;
3387
3388     return PyImport_ExtendInittab(newtab);
3389 }
3390
3391 #ifdef __cplusplus
3392 }
3393 #endif