home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Python / import.c < prev    next >
C/C++ Source or Header  |  2000-12-21  |  59KB  |  2,480 lines

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