home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / programming / python / pysrc / !Python_Monty_c_import < prev    next >
Encoding:
Text File  |  1996-11-06  |  22.0 KB  |  1,061 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 "allobjects.h"
  35.  
  36. /* XXX Some of the following are duplicate with allobjects.h... */
  37. #include "node.h"
  38. #include "token.h"
  39. #include "graminit.h"
  40. #include "import.h"
  41. #include "errcode.h"
  42. #include "sysmodule.h"
  43. #include "bltinmodule.h"
  44. #include "pythonrun.h"
  45. #include "marshal.h"
  46. #include "compile.h"
  47. #include "eval.h"
  48. #include "osdefs.h"
  49. #include "importdl.h"
  50. #ifdef macintosh
  51. /* 'argument' is a grammar symbol, but also used in some mac header files */
  52. #undef argument
  53. #include "macglue.h"
  54. #endif
  55.  
  56. extern long getmtime(); /* In getmtime.c */
  57.  
  58. /* Magic word to reject .pyc files generated by other Python versions */
  59. /* Change for each incompatible change */
  60. /* The value of CR and LF is incorporated so if you ever read or write
  61.    a .pyc file in text mode the magic number will be wrong; also, the
  62.    Apple MPW compiler swaps their values, botching string constants */
  63. /* XXX Perhaps the magic number should be frozen and a version field
  64.    added to the .pyc file header? */
  65. #define MAGIC (5892 | ((long)'\r'<<16) | ((long)'\n'<<24))
  66.  
  67. object *import_modules; /* This becomes sys.modules */
  68.  
  69.  
  70. /* Initialize things */
  71.  
  72. void
  73. initimport()
  74. {
  75.     if (import_modules != NULL)
  76.         fatal("duplicate initimport() call");
  77.     if ((import_modules = newdictobject()) == NULL)
  78.         fatal("no mem for dictionary of modules");
  79. }
  80.  
  81.  
  82. /* Un-initialize things, as good as we can */
  83.  
  84. void
  85. doneimport()
  86. {
  87.     if (import_modules != NULL) {
  88.         object *tmp = import_modules;
  89.         import_modules = NULL;
  90.         /* This deletes all modules from sys.modules.
  91.            When a module is deallocated, it in turn clears its dictionary,
  92.            thus hopefully breaking any circular references between modules
  93.            and between a module's dictionary and its functions.
  94.            Note that "import" will fail while we are cleaning up.
  95.            */
  96.         mappingclear(tmp);
  97.         DECREF(tmp);
  98.     }
  99. }
  100.  
  101.  
  102. /* Helper for pythonrun.c -- return magic number */
  103.  
  104. long
  105. get_pyc_magic()
  106. {
  107.     return MAGIC;
  108. }
  109.  
  110.  
  111. /* Helper for sysmodule.c -- return modules dictionary */
  112.  
  113. object *
  114. get_modules()
  115. {
  116.     return import_modules;
  117. }
  118.  
  119.  
  120. /* Get the module object corresponding to a module name.
  121.    First check the modules dictionary if there's one there,
  122.    if not, create a new one and insert in in the modules dictionary.
  123.    Because the former action is most common, THIS DOES NOT RETURN A
  124.    'NEW' REFERENCE! */
  125.  
  126. object *
  127. add_module(name)
  128.     char *name;
  129. {
  130.     object *m;
  131.  
  132.     if (import_modules == NULL) {
  133.         err_setstr(SystemError, "sys.modules has been deleted");
  134.         return NULL;
  135.     }
  136.     if ((m = dictlookup(import_modules, name)) != NULL &&
  137.         is_moduleobject(m))
  138.         return m;
  139.     m = newmoduleobject(name);
  140.     if (m == NULL)
  141.         return NULL;
  142.     if (dictinsert(import_modules, name, m) != 0) {
  143.         DECREF(m);
  144.         return NULL;
  145.     }
  146.     DECREF(m); /* Yes, it still exists, in modules! */
  147.  
  148.     return m;
  149. }
  150.  
  151.  
  152. /* Execute a code object in a module and return the module object
  153.    WITH INCREMENTED REFERENCE COUNT */
  154.  
  155. object *
  156. exec_code_module(name, co)
  157.     char *name;
  158.     object *co;
  159. {
  160.     object *m, *d, *v;
  161.  
  162.     m = add_module(name);
  163.     if (m == NULL)
  164.         return NULL;
  165.     d = getmoduledict(m);
  166.     if (dictlookup(d, "__builtins__") == NULL) {
  167.         if (dictinsert(d, "__builtins__", getbuiltins()) != 0)
  168.             return NULL;
  169.     }
  170.     /* Remember the filename as the __file__ attribute */
  171.     if (dictinsert(d, "__file__", ((codeobject *)co)->co_filename) != 0)
  172.         err_clear(); /* Not important enough to report */
  173.     v = eval_code((codeobject *)co, d, d); /* XXX owner? */
  174.     if (v == NULL)
  175.         return NULL;
  176.     DECREF(v);
  177.     INCREF(m);
  178.  
  179.     return m;
  180. }
  181.  
  182.  
  183. /* Given a pathname for a Python source file, fill a buffer with the
  184.    pathname for the corresponding compiled file.  Return the pathname
  185.    for the compiled file, or NULL if there's no space in the buffer.
  186.    Doesn't set an exception. */
  187.  
  188. static char *
  189. make_compiled_pathname(pathname, buf, buflen)
  190.     char *pathname;
  191.     char *buf;
  192.     int buflen;
  193. {
  194.     int len;
  195.  
  196.     len = strlen(pathname);
  197.     if (len+2 > buflen)
  198.         return NULL;
  199.     strcpy(buf, pathname);
  200. #ifdef RISCOS
  201.         { char *stop=strrchr(buf,'.');
  202.           if(!stop) return NULL;
  203.           memmove(stop+1,stop,strlen(stop)+1);
  204.           *stop='c';
  205.         }
  206. #else
  207.     strcpy(buf+len, "c");
  208. #endif
  209.     return buf;
  210. }
  211.  
  212.  
  213. /* Given a pathname for a Python source file, its time of last
  214.    modification, and a pathname for a compiled file, check whether the
  215.    compiled file represents the same version of the source.  If so,
  216.    return a FILE pointer for the compiled file, positioned just after
  217.    the header; if not, return NULL.
  218.    Doesn't set an exception. */
  219.  
  220. static FILE *
  221. check_compiled_module(pathname, mtime, cpathname)
  222.     char *pathname;
  223.     long mtime;
  224.     char *cpathname;
  225. {
  226.     FILE *fp;
  227.     long magic;
  228.     long pyc_mtime;
  229.  
  230.     fp = fopen(cpathname, "rb");
  231.     if (fp == NULL)
  232.         return NULL;
  233.     magic = rd_long(fp);
  234.     if (magic != MAGIC) {
  235.         if (verbose)
  236.             fprintf(stderr, "# %s has bad magic\n", cpathname);
  237.         fclose(fp);
  238.         return NULL;
  239.     }
  240.     pyc_mtime = rd_long(fp);
  241.     if (pyc_mtime != mtime) {
  242.         if (verbose)
  243.             fprintf(stderr, "# %s has bad mtime\n", cpathname);
  244.         fclose(fp);
  245.         return NULL;
  246.     }
  247.     if (verbose)
  248.         fprintf(stderr, "# %s matches %s\n", cpathname, pathname);
  249.     return fp;
  250. }
  251.  
  252.  
  253. /* Read a code object from a file and check it for validity */
  254.  
  255. static codeobject *
  256. read_compiled_module(fp)
  257.     FILE *fp;
  258. {
  259.     object *co;
  260.  
  261.     co = rd_object(fp);
  262.     /* Ugly: rd_object() may return NULL with or without error */
  263.     if (co == NULL || !is_codeobject(co)) {
  264.         if (!err_occurred())
  265.             err_setstr(ImportError,
  266.                    "Non-code object in .pyc file");
  267.         XDECREF(co);
  268.         return NULL;
  269.     }
  270.     return (codeobject *)co;
  271. }
  272.  
  273.  
  274. /* Load a module from a compiled file, execute it, and return its
  275.    module object WITH INCREMENTED REFERENCE COUNT */
  276.  
  277. static object *
  278. load_compiled_module(name, cpathname, fp)
  279.     char *name;
  280.     char *cpathname;
  281.     FILE *fp;
  282. {
  283.     long magic;
  284.     codeobject *co;
  285.     object *m;
  286.  
  287.     magic = rd_long(fp);
  288.     if (magic != MAGIC) {
  289.         err_setstr(ImportError, "Bad magic number in .pyc file");
  290.         return NULL;
  291.     }
  292.     (void) rd_long(fp);
  293.     co = read_compiled_module(fp);
  294.     if (co == NULL)
  295.         return NULL;
  296.     if (verbose)
  297.         fprintf(stderr, "import %s # precompiled from %s\n",
  298.             name, cpathname);
  299.     m = exec_code_module(name, (object *)co);
  300.     DECREF(co);
  301.  
  302.     return m;
  303. }
  304.  
  305. /* Parse a source file and return the corresponding code object */
  306.  
  307. static codeobject *
  308. parse_source_module(pathname, fp)
  309.     char *pathname;
  310.     FILE *fp;
  311. {
  312.     codeobject *co;
  313.     node *n;
  314.  
  315.     n = parse_file(fp, pathname, file_input);
  316.     if (n == NULL)
  317.         return NULL;
  318.     co = compile(n, pathname);
  319.     freetree(n);
  320.  
  321.     return co;
  322. }
  323.  
  324.  
  325. /* Write a compiled module to a file, placing the time of last
  326.    modification of its source into the header.
  327.    Errors are ignored, if a write error occurs an attempt is made to
  328.    remove the file. */
  329.  
  330. static void
  331. write_compiled_module(co, cpathname, mtime)
  332.     codeobject *co;
  333.     char *cpathname;
  334.     long mtime;
  335. {
  336.     FILE *fp;
  337.  
  338.     fp = fopen(cpathname, "wb");
  339.     if (fp == NULL) {
  340.         if (verbose)
  341.             fprintf(stderr,
  342.                 "# can't create %s\n", cpathname);
  343.         return;
  344.     }
  345.     wr_long(MAGIC, fp);
  346.     /* First write a 0 for mtime */
  347.     wr_long(0L, fp);
  348.     wr_object((object *)co, fp);
  349.     if (ferror(fp)) {
  350.         if (verbose)
  351.             fprintf(stderr, "# can't write %s\n", cpathname);
  352.         /* Don't keep partial file */
  353.         fclose(fp);
  354.         (void) unlink(cpathname);
  355.         return;
  356.     }
  357.     /* Now write the true mtime */
  358.     fseek(fp, 4L, 0);
  359.     wr_long(mtime, fp);
  360.     fflush(fp);
  361.     fclose(fp);
  362.     if (verbose)
  363.         fprintf(stderr, "# wrote %s\n", cpathname);
  364. #ifdef macintosh
  365.     setfiletype(cpathname, 'Pyth', 'PYC ');
  366. #endif
  367. }
  368.  
  369.  
  370. /* Load a source module from a given file and return its module
  371.    object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
  372.    byte-compiled file, use that instead. */
  373.  
  374. static object *
  375. load_source_module(name, pathname, fp)
  376.     char *name;
  377.     char *pathname;
  378.     FILE *fp;
  379. {
  380.     long mtime;
  381.     FILE *fpc;
  382.     char buf[MAXPATHLEN+1];
  383.     char *cpathname;
  384.     codeobject *co;
  385.     object *m;
  386.  
  387.     mtime = getmtime(pathname);
  388.     cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1);
  389.     if (cpathname != NULL &&
  390.         (fpc = check_compiled_module(pathname, mtime, cpathname))) {
  391.         co = read_compiled_module(fpc);
  392.         fclose(fpc);
  393.         if (co == NULL)
  394.             return NULL;
  395.         if (verbose)
  396.             fprintf(stderr, "import %s # precompiled from %s\n",
  397.                 name, cpathname);
  398.     }
  399.     else {
  400.         co = parse_source_module(pathname, fp);
  401.         if (co == NULL)
  402.             return NULL;
  403.         if (verbose)
  404.             fprintf(stderr, "import %s # from %s\n",
  405.                 name, pathname);
  406.         write_compiled_module(co, cpathname, mtime);
  407.     }
  408.     m = exec_code_module(name, (object *)co);
  409.     DECREF(co);
  410.  
  411.     return m;
  412. }
  413.  
  414.  
  415. /* Search the path (default sys.path) for a module.  Return the
  416.    corresponding filedescr struct, and (via return arguments) the
  417.    pathname and an open file.  Return NULL if the module is not found. */
  418.  
  419. static struct filedescr *
  420. find_module(name, path, buf, buflen, p_fp)
  421.     char *name;
  422.     object *path;
  423.     /* Output parameters: */
  424.     char *buf;
  425.     int buflen;
  426.     FILE **p_fp;
  427. {
  428.     int i, npath, len, namelen;
  429.     struct filedescr *fdp;
  430.     FILE *fp = NULL;
  431.  
  432. #ifdef MS_COREDLL
  433.     if ((fp=PyWin_FindRegisteredModule(name, &fdp, buf, buflen))!=NULL) {
  434.         *p_fp = fp;
  435.         return fdp;
  436.     }
  437. #endif
  438.  
  439.  
  440.     if (path == NULL)
  441.         path = sysget("path");
  442.     if (path == NULL || !is_listobject(path)) {
  443.         err_setstr(ImportError,
  444.                "sys.path must be a list of directory names");
  445.         return NULL;
  446.     }
  447.     npath = getlistsize(path);
  448.     namelen = strlen(name);
  449.     for (i = 0; i < npath; i++) {
  450.         object *v = getlistitem(path, i);
  451.         if (!is_stringobject(v))
  452.             continue;
  453.         len = getstringsize(v);
  454.         if (len + 2 + namelen + import_maxsuffixsize >= buflen)
  455.             continue; /* Too long */
  456.         strcpy(buf, getstringvalue(v));
  457.         if (strlen(buf) != len)
  458.             continue; /* v contains '\0' */
  459. #ifdef macintosh
  460.         if ( PyMac_FindResourceModule(name, buf) ) {
  461.             static struct filedescr resfiledescr = { "", "", PY_RESOURCE};
  462.  
  463.             return &resfiledescr;
  464.         }
  465. #endif
  466.         if (len > 0 && buf[len-1] != SEP)
  467.             buf[len++] = SEP;
  468. #ifdef IMPORT_8x3_NAMES
  469.         /* see if we are searching in directory dos_8x3 */
  470.         if (len > 7 && !strncmp(buf + len - 8, "dos_8x3", 7)){
  471.             int j;
  472.             char ch;  /* limit name to eight lower-case characters */
  473.             for (j = 0; (ch = name[j]) && j < 8; j++)
  474.                 if (isupper(ch))
  475.                     buf[len++] = tolower(ch);
  476.                 else
  477.                     buf[len++] = ch;
  478.         }
  479.         else /* Not in dos_8x3, use the full name */
  480. #endif
  481.  
  482. #ifdef RISCOS
  483.         for (fdp = import_filetab; fdp->suffix != NULL; fdp++) {
  484.             strcpy(buf+len, fdp->suffix);
  485.             strcpy(buf+len+strlen(fdp->suffix), name);
  486. #else
  487.         {
  488.             strcpy(buf+len, name);
  489.             len += namelen;
  490.         }
  491.         for (fdp = import_filetab; fdp->suffix != NULL; fdp++) {
  492.             strcpy(buf+len, fdp->suffix);
  493. #endif
  494.             if (verbose > 1)
  495.                 fprintf(stderr, "# trying %s\n", buf);
  496.             fp = fopen(buf, fdp->mode);
  497.             if (fp != NULL)
  498.                 break;
  499.         }
  500.         if (fp != NULL)
  501.             break;
  502.     }
  503.     if (fp == NULL) {
  504.         char buf[256];
  505.         sprintf(buf, "No module named %.200s", name);
  506.         err_setstr(ImportError, buf);
  507.         return NULL;
  508.     }
  509.  
  510.     *p_fp = fp;
  511.     return fdp;
  512. }
  513.  
  514.  
  515. /* Load an external module using the default search path and return
  516.    its module object WITH INCREMENTED REFERENCE COUNT */
  517.  
  518. static object *
  519. load_module(name)
  520.     char *name;
  521. {
  522.     char buf[MAXPATHLEN+1];
  523.     struct filedescr *fdp;
  524.     FILE *fp = NULL;
  525.     object *m;
  526.  
  527.     fdp = find_module(name, (object *)NULL, buf, MAXPATHLEN+1, &fp);
  528.     if (fdp == NULL)
  529.         return NULL;
  530.  
  531.     switch (fdp->type) {
  532.  
  533.     case PY_SOURCE:
  534.         m = load_source_module(name, buf, fp);
  535.         break;
  536.  
  537.     case PY_COMPILED:
  538.         m = load_compiled_module(name, buf, fp);
  539.         break;
  540.  
  541.     case C_EXTENSION:
  542.         m = load_dynamic_module(name, buf, fp);
  543.         break;
  544.  
  545. #ifdef macintosh
  546.     case PY_RESOURCE:
  547.         m = PyMac_LoadResourceModule(name, buf);
  548.         break;
  549. #endif
  550.  
  551.     default:
  552.         err_setstr(SystemError,
  553.                "find_module returned unexpected result");
  554.         m = NULL;
  555.  
  556.     }
  557.     if ( fp )
  558.         fclose(fp);
  559.  
  560.     return m;
  561. }
  562.  
  563.  
  564. /* Initialize a built-in module.
  565.    Return 1 for succes, 0 if the module is not found, and -1 with
  566.    an exception set if the initialization failed. */
  567.  
  568. static int
  569. init_builtin(name)
  570.     char *name;
  571. {
  572.     int i;
  573.     for (i = 0; inittab[i].name != NULL; i++) {
  574.         if (strcmp(name, inittab[i].name) == 0) {
  575.             if (inittab[i].initfunc == NULL) {
  576.                 err_setstr(ImportError,
  577.                        "Cannot re-init internal module");
  578.                 return -1;
  579.             }
  580.             if (verbose)
  581.                 fprintf(stderr, "import %s # builtin\n",
  582.                     name);
  583.             (*inittab[i].initfunc)();
  584.             if (err_occurred())
  585.                 return -1;
  586.             return 1;
  587.         }
  588.     }
  589.     return 0;
  590. }
  591.  
  592.  
  593. /* Frozen modules */
  594.  
  595. static struct _frozen *
  596. find_frozen(name)
  597.     char *name;
  598. {
  599.     struct _frozen *p;
  600.  
  601.     for (p = frozen_modules; ; p++) {
  602.         if (p->name == NULL)
  603.             return NULL;
  604.         if (strcmp(p->name, name) == 0)
  605.             break;
  606.     }
  607.     return p;
  608. }
  609.  
  610. static object *
  611. get_frozen_object(name)
  612.     char *name;
  613. {
  614.     struct _frozen *p = find_frozen(name);
  615.  
  616.     if (p == NULL) {
  617.         err_setstr(ImportError, "No such frozen object");
  618.         return NULL;
  619.     }
  620.     return rds_object((char *)p->code, p->size);
  621. }
  622.  
  623. /* Initialize a frozen module.
  624.    Return 1 for succes, 0 if the module is not found, and -1 with
  625.    an exception set if the initialization failed.
  626.    This function is also used from frozenmain.c */
  627.  
  628. int
  629. init_frozen(name)
  630.     char *name;
  631. {
  632.     struct _frozen *p = find_frozen(name);
  633.     object *co;
  634.     object *m;
  635.  
  636.     if (p == NULL)
  637.         return 0;
  638.     if (verbose)
  639.         fprintf(stderr, "import %s # frozen\n", name);
  640.     co = rds_object((char *)p->code, p->size);
  641.     if (co == NULL)
  642.         return -1;
  643.     if (!is_codeobject(co)) {
  644.         DECREF(co);
  645.         err_setstr(TypeError, "frozen object is not a code object");
  646.         return -1;
  647.     }
  648.     m = exec_code_module(name, co);
  649.     DECREF(co);
  650.     if (m == NULL)
  651.         return -1;
  652.     DECREF(m);
  653.     return 1;
  654. }
  655.  
  656.  
  657. /* Import a module, either built-in, frozen, or external, and return
  658.    its module object WITH INCREMENTED REFERENCE COUNT */
  659.  
  660. object *
  661. import_module(name)
  662.     char *name;
  663. {
  664.     object *m;
  665.  
  666.     if (import_modules == NULL) {
  667.         err_setstr(SystemError, "sys.modules has been deleted");
  668.         return NULL;
  669.     }
  670.     if ((m = dictlookup(import_modules, name)) != NULL) {
  671.         INCREF(m);
  672.     }
  673.     else {
  674.         int i;
  675.         if ((i = init_builtin(name)) || (i = init_frozen(name))) {
  676.             if (i < 0)
  677.                 return NULL;
  678.             if ((m = dictlookup(import_modules, name)) == NULL) {
  679.                 if (err_occurred() == NULL)
  680.                     err_setstr(SystemError,
  681.                  "built-in module not initialized properly");
  682.             }
  683.             else
  684.                 INCREF(m);
  685.         }
  686.         else
  687.             m = load_module(name);
  688.     }
  689.  
  690.     return m;
  691. }
  692.  
  693.  
  694. /* Re-import a module of any kind and return its module object, WITH
  695.    INCREMENTED REFERENCE COUNT */
  696.  
  697. object *
  698. reload_module(m)
  699.     object *m;
  700. {
  701.     char *name;
  702.     int i;
  703.  
  704.     if (m == NULL || !is_moduleobject(m)) {
  705.         err_setstr(TypeError, "reload() argument must be module");
  706.         return NULL;
  707.     }
  708.     name = getmodulename(m);
  709.     if (name == NULL)
  710.         return NULL;
  711.     if (import_modules == NULL) {
  712.         err_setstr(SystemError, "sys.modules has been deleted");
  713.         return NULL;
  714.     }
  715.     if (m != dictlookup(import_modules, name)) {
  716.         err_setstr(ImportError, "reload() module not in sys.modules");
  717.         return NULL;
  718.     }
  719.     /* Check for built-in and frozen modules */
  720.     if ((i = init_builtin(name)) || (i = init_frozen(name))) {
  721.         if (i < 0)
  722.             return NULL;
  723.         INCREF(m);
  724.     }
  725.     else
  726.         m = load_module(name);
  727.     return m;
  728. }
  729.  
  730.  
  731. /* Module 'imp' provides Python access to the primitives used for
  732.    importing modules.
  733. */
  734.  
  735. static object *
  736. imp_get_magic(self, args)
  737.     object *self;
  738.     object *args;
  739. {
  740.     char buf[4];
  741.  
  742.     if (!newgetargs(args, ""))
  743.         return NULL;
  744.     buf[0] = (MAGIC >>  0) & 0xff;
  745.     buf[1] = (MAGIC >>  8) & 0xff;
  746.     buf[2] = (MAGIC >> 16) & 0xff;
  747.     buf[3] = (MAGIC >> 24) & 0xff;
  748.  
  749.     return newsizedstringobject(buf, 4);
  750. }
  751.  
  752. static object *
  753. imp_get_suffixes(self, args)
  754.     object *self;
  755.     object *args;
  756. {
  757.     object *list;
  758.     struct filedescr *fdp;
  759.  
  760.     if (!newgetargs(args, ""))
  761.         return NULL;
  762.     list = newlistobject(0);
  763.     if (list == NULL)
  764.         return NULL;
  765.     for (fdp = import_filetab; fdp->suffix != NULL; fdp++) {
  766.         object *item = mkvalue("ssi",
  767.                        fdp->suffix, fdp->mode, fdp->type);
  768.         if (item == NULL) {
  769.             DECREF(list);
  770.             return NULL;
  771.         }
  772.         if (addlistitem(list, item) < 0) {
  773.             DECREF(list);
  774.             DECREF(item);
  775.             return NULL;
  776.         }
  777.         DECREF(item);
  778.     }
  779.     return list;
  780. }
  781.  
  782. static object *
  783. imp_find_module(self, args)
  784.     object *self;
  785.     object *args;
  786. {
  787.     extern int fclose PROTO((FILE *));
  788.     char *name;
  789.     object *path = NULL;
  790.     object *fob, *ret;
  791.     struct filedescr *fdp;
  792.     char pathname[MAXPATHLEN+1];
  793.     FILE *fp;
  794.     if (!newgetargs(args, "s|O!", &name, &Listtype, &path))
  795.         return NULL;
  796.     fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
  797.     if (fdp == NULL)
  798.         return NULL;
  799.     fob = newopenfileobject(fp, pathname, fdp->mode, fclose);
  800.     if (fob == NULL) {
  801.         fclose(fp);
  802.         return NULL;
  803.     }
  804.     ret = mkvalue("Os(ssi)",
  805.               fob, pathname, fdp->suffix, fdp->mode, fdp->type);
  806.     DECREF(fob);
  807.     return ret;
  808. }
  809.  
  810. static object *
  811. imp_init_builtin(self, args)
  812.     object *self;
  813.     object *args;
  814. {
  815.     char *name;
  816.     int ret;
  817.     object *m;
  818.     if (!newgetargs(args, "s", &name))
  819.         return NULL;
  820.     ret = init_builtin(name);
  821.     if (ret < 0)
  822.         return NULL;
  823.     if (ret == 0) {
  824.         INCREF(None);
  825.         return None;
  826.     }
  827.     m = add_module(name);
  828.     XINCREF(m);
  829.     return m;
  830. }
  831.  
  832. static object *
  833. imp_init_frozen(self, args)
  834.     object *self;
  835.     object *args;
  836. {
  837.     char *name;
  838.     int ret;
  839.     object *m;
  840.     if (!newgetargs(args, "s", &name))
  841.         return NULL;
  842.     ret = init_frozen(name);
  843.     if (ret < 0)
  844.         return NULL;
  845.     if (ret == 0) {
  846.         INCREF(None);
  847.         return None;
  848.     }
  849.     m = add_module(name);
  850.     XINCREF(m);
  851.     return m;
  852. }
  853.  
  854. static object *
  855. imp_get_frozen_object(self, args)
  856.     object *self;
  857.     object *args;
  858. {
  859.     char *name;
  860.  
  861.     if (!newgetargs(args, "s", &name))
  862.         return NULL;
  863.     return get_frozen_object(name);
  864. }
  865.  
  866. static object *
  867. imp_is_builtin(self, args)
  868.     object *self;
  869.     object *args;
  870. {
  871.     int i;
  872.     char *name;
  873.     if (!newgetargs(args, "s", &name))
  874.         return NULL;
  875.     for (i = 0; inittab[i].name != NULL; i++) {
  876.         if (strcmp(name, inittab[i].name) == 0) {
  877.             if (inittab[i].initfunc == NULL)
  878.                 return newintobject(-1);
  879.             else
  880.                 return newintobject(1);
  881.         }
  882.     }
  883.     return newintobject(0);
  884. }
  885.  
  886. static object *
  887. imp_is_frozen(self, args)
  888.     object *self;
  889.     object *args;
  890. {
  891.     struct _frozen *p;
  892.     char *name;
  893.     if (!newgetargs(args, "s", &name))
  894.         return NULL;
  895.     for (p = frozen_modules; ; p++) {
  896.         if (p->name == NULL)
  897.             break;
  898.         if (strcmp(p->name, name) == 0)
  899.             return newintobject(1);
  900.     }
  901.     return newintobject(0);
  902. }
  903.  
  904. static FILE *
  905. get_file(pathname, fob, mode)
  906.     char *pathname;
  907.     object *fob;
  908.     char *mode;
  909. {
  910.     FILE *fp;
  911.     if (fob == NULL) {
  912.         fp = fopen(pathname, mode);
  913.         if (fp == NULL)
  914.             err_errno(IOError);
  915.     }
  916.     else {
  917.         fp = getfilefile(fob);
  918.         if (fp == NULL)
  919.             err_setstr(ValueError, "bad/closed file object");
  920.     }
  921.     return fp;
  922. }
  923.  
  924. static object *
  925. imp_load_compiled(self, args)
  926.     object *self;
  927.     object *args;
  928. {
  929.     char *name;
  930.     char *pathname;
  931.     object *fob = NULL;
  932.     object *m;
  933.     FILE *fp;
  934.     if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob))
  935.         return NULL;
  936.     fp = get_file(pathname, fob, "rb");
  937.     if (fp == NULL)
  938.         return NULL;
  939.     m = load_compiled_module(name, pathname, fp);
  940.     return m;
  941. }
  942.  
  943. static object *
  944. imp_load_dynamic(self, args)
  945.     object *self;
  946.     object *args;
  947. {
  948.     char *name;
  949.     char *pathname;
  950.     object *fob = NULL;
  951.     object *m;
  952.     FILE *fp = NULL;
  953.     if (!newgetargs(args, "ss|O!", &name, &pathname, &Filetype, &fob))
  954.         return NULL;
  955.     if (fob)
  956.         fp = get_file(pathname, fob, "r");
  957.     m = load_dynamic_module(name, pathname, fp);
  958.     return m;
  959. }
  960.  
  961. static object *
  962. imp_load_source(self, args)
  963.     object *self;
  964.     object *args;
  965. {
  966.     char *name;
  967.     char *pathname;
  968.     object *fob = NULL;
  969.     object *m;
  970.     FILE *fp;
  971.     if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob))
  972.         return NULL;
  973.     fp = get_file(pathname, fob, "r");
  974.     if (fp == NULL)
  975.         return NULL;
  976.     m = load_source_module(name, pathname, fp);
  977.     return m;
  978. }
  979.  
  980. #ifdef macintosh
  981. static object *
  982. imp_load_resource(self, args)
  983.     object *self;
  984.     object *args;
  985. {
  986.     char *name;
  987.     char *pathname;
  988.     object *m;
  989.  
  990.     if (!newgetargs(args, "ss", &name, &pathname))
  991.         return NULL;
  992.     m = PyMac_LoadResourceModule(name, pathname);
  993.     return m;
  994. }
  995. #endif /* macintosh */
  996.  
  997. static object *
  998. imp_new_module(self, args)
  999.     object *self;
  1000.     object *args;
  1001. {
  1002.     char *name;
  1003.     if (!newgetargs(args, "s", &name))
  1004.         return NULL;
  1005.     return newmoduleobject(name);
  1006. }
  1007.  
  1008. static struct methodlist imp_methods[] = {
  1009.     {"get_frozen_object",    imp_get_frozen_object,    1},
  1010.     {"get_magic",        imp_get_magic,        1},
  1011.     {"get_suffixes",    imp_get_suffixes,    1},
  1012.     {"find_module",        imp_find_module,    1},
  1013.     {"init_builtin",    imp_init_builtin,    1},
  1014.     {"init_frozen",        imp_init_frozen,    1},
  1015.     {"is_builtin",        imp_is_builtin,        1},
  1016.     {"is_frozen",        imp_is_frozen,        1},
  1017.     {"load_compiled",    imp_load_compiled,    1},
  1018.     {"load_dynamic",    imp_load_dynamic,    1},
  1019.     {"load_source",        imp_load_source,    1},
  1020.     {"new_module",        imp_new_module,        1},
  1021. #ifdef macintosh
  1022.     {"load_resource",    imp_load_resource,    1},
  1023. #endif
  1024.     {NULL,            NULL}        /* sentinel */
  1025. };
  1026.  
  1027. void
  1028. initimp()
  1029. {
  1030.     object *m, *d, *v;
  1031.  
  1032.     m = initmodule("imp", imp_methods);
  1033.     d = getmoduledict(m);
  1034.  
  1035.     v = newintobject(SEARCH_ERROR);
  1036.     dictinsert(d, "SEARCH_ERROR", v);
  1037.     XDECREF(v);
  1038.  
  1039.     v = newintobject(PY_SOURCE);
  1040.     dictinsert(d, "PY_SOURCE", v);
  1041.     XDECREF(v);
  1042.  
  1043.     v = newintobject(PY_COMPILED);
  1044.     dictinsert(d, "PY_COMPILED", v);
  1045.     XDECREF(v);
  1046.  
  1047.     v = newintobject(C_EXTENSION);
  1048.     dictinsert(d, "C_EXTENSION", v);
  1049.     XDECREF(v);
  1050.  
  1051. #ifdef macintosh
  1052.     v = newintobject(PY_RESOURCE);
  1053.     dictinsert(d, "PY_RESOURCE", v);
  1054.     XDECREF(v);
  1055. #endif
  1056.  
  1057.  
  1058.     if (err_occurred())
  1059.         fatal("imp module initialization failed");
  1060. }
  1061.