home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Python / import.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  56.3 KB  |  2,415 lines

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